<?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>Alkampfer&#039;s Place&#187; Nhibernate</title>
	<atom:link href="http://www.codewrecks.com/blog/index.php/category/frameworks/nhibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codewrecks.com/blog</link>
	<description>Wrecks of code floating in the sea of Internet</description>
	<lastBuildDate>Tue, 27 Jul 2010 10:16:27 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>NHibernate HQL query with only date part of a datetimevalue</title>
		<link>http://www.codewrecks.com/blog/index.php/2010/06/04/nhibernate-hql-query-with-only-date-part-of-a-datetimevalue/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2010/06/04/nhibernate-hql-query-with-only-date-part-of-a-datetimevalue/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 12:54:24 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2010/06/04/nhibernate-hql-query-with-only-date-part-of-a-datetimevalue/</guid>
		<description><![CDATA[
			
				
			
		
DateTime values are one of the most feared type of data to store in database. Suppose you have an entity with a datetime Property, and you want to do a standard report finding the count of each entity for each day in a date range, if you groupBy the DateTime property, surely you will get [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F06%2F04%2Fnhibernate-hql-query-with-only-date-part-of-a-datetimevalue%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F06%2F04%2Fnhibernate-hql-query-with-only-date-part-of-a-datetimevalue%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>DateTime values are one of the most feared type of data to store in database. Suppose you have an entity with a datetime Property, and you want to do a standard report finding the count of each entity for each day in a date range, if you groupBy the DateTime property, surely you will get wrong results, because you will end with a lot of entries with count = 1, because it is really difficult that two entities will have the very same datetime value. What you want is to group by only with the date part of the datetime property.</p>
<p>Since NHibernate does not come with a predefined date function, you need to create a custom dialect to solve the problem, first of all I have a custom dialect for my SqlLite unit tests.</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> SqlLiteDialect : NHibernate.Dialect.SQLiteDialect</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">public</span> SqlLiteDialect()</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>         RegisterFunction(<span style="color: #006080">&quot;date&quot;</span>, <span style="color: #0000ff">new</span> SQLFunctionTemplate(NHibernateUtil.Date, <span style="color: #006080">&quot;date(?1)&quot;</span>));</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>     }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Since SqlLite already have a <a target="_blank" href="http://www.sqlite.org/cvstrac/wiki?p=DateAndTimeFunctions">date function</a> that extract the date part of a date, I simply need to instruct NHibernate dialect that such function exists registering the function “date” with a SqlFunctionTemplate, this means that whenever the HQL parser will find a call to date() function it will substitute the date(?1) string, where ?1 will be substituted with the real parameter of the function.</p>
<p>In production, the code will run against a sql server 2008, and we have already defined a function called dbo.trunc that will truncate the time part of the date in our databases, so I create a similar dialect for sql server.</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MySqlDialect : NHibernate.Dialect.MsSql2008Dialect</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">public</span> MySqlDialect ()</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>         RegisterFunction(<span style="color: #006080">&quot;date&quot;</span>, <span style="color: #0000ff">new</span> SQLFunctionTemplate(NHibernateUtil.Date, <span style="color: #006080">&quot;dbo.trunc(?1)&quot;</span>));</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span>     }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum8">   8:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>The great advantage of the dialect approach, is that you are able to write a hql query like this:</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">Select</span> <span style="color: #0000ff">date</span>(A.ActionDate), <span style="color: #0000ff">count</span>(*) </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> <span style="color: #0000ff">from</span> <span style="color: #0000ff">Action</span> A </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span> <span style="color: #0000ff">where</span> A.ActionDate &gt;= :startdate <span style="color: #0000ff">and</span> A.ActionDate &lt;= :enddate</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span> <span style="color: #0000ff">group</span> <span style="color: #0000ff">by</span> <span style="color: #0000ff">date</span>(A.ActionDate)</pre>
<p><!--CRLF--></div>
</div>
<p>Where I’m able to use date() function, but at the same time it gets translated in different way respect the dialect I use. If in the future I will need to use Oracle, I’ll simply create another dialect, without the need to modify any HQL query.</p>
<p>alk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2010/06/04/nhibernate-hql-query-with-only-date-part-of-a-datetimevalue/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Error log4net:ERROR [NHibernateProfilerAppender] Attempted to append to closed appender named [NHibernate.Profiler]</title>
		<link>http://www.codewrecks.com/blog/index.php/2010/05/24/error-log4neterror-nhibernateprofilerappender-attempted-to-append-to-closed-appender-named-nhibernate-profiler/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2010/05/24/error-log4neterror-nhibernateprofilerappender-attempted-to-append-to-closed-appender-named-nhibernate-profiler/#comments</comments>
		<pubDate>Mon, 24 May 2010 14:00:50 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2010/05/24/error-log4neterror-nhibernateprofilerappender-attempted-to-append-to-closed-appender-named-nhibernate-profiler/</guid>
		<description><![CDATA[
			
				
			
		
NHprofiler de facto is “THE TOOL” to work with NHibernate,   
If you work with NHibernate you must have NHProf, if you use it for 1 minute you can never work without it in the future, period.   
I started today to use NHProf even for unit testing, since I want to be [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F05%2F24%2Ferror-log4neterror-nhibernateprofilerappender-attempted-to-append-to-closed-appender-named-nhibernate-profiler%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F05%2F24%2Ferror-log4neterror-nhibernateprofilerappender-attempted-to-append-to-closed-appender-named-nhibernate-profiler%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p><a target="_blank" href="http://nhprof.com/">NHprofiler</a> de facto is “THE TOOL” to work with NHibernate, <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>If you work with NHibernate you must have NHProf, if you use it for 1 minute you can never work without it in the future, period. <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>I started today to use NHProf even for unit testing, since I want to be able to look at generated sql during tests of entities. I have a base test infrastructure to work with helper, so I have this snippet of code in fixture setup.</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">if</span> (inited == <span style="color: #0000ff">false</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     inited = <span style="color: #0000ff">true</span>;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>When I run the unit test I see that session initialization data will shown in nhibernate profiler ui, but the test then throws a </p>
<blockquote>
<p>log4net:ERROR [NHibernateProfilerAppender] Attempted to append to closed appender named [NHibernate.Profiler]</p>
</blockquote>
<p>This happens because NhProfiler uses log4net to intercept nhibernate calls, and it seems that someone closes the appender before nhprof has finished collecting data. This error happens because you need to configure log4net before the call to </p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();</pre>
<p><!--CRLF--></div>
</div>
<p>If you like me use the Castle Log4Net faciliy, you simply need to be sure that the facility configures log4net before starting nhprofiler</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">if</span> (inited == <span style="color: #0000ff">false</span>)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>     ILogger logger = IoC.Resolve&lt;ILogger&gt;();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>     inited = <span style="color: #0000ff">true</span>;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>     HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>In my situation the act of resolving an ILogger makes me sure that log4net is completely configured before I started nhprofiler appender and everything works well.</p>
<p>alk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2010/05/24/error-log4neterror-nhibernateprofilerappender-attempted-to-append-to-closed-appender-named-nhibernate-profiler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiple bag with Fetch=&#8221;join&#8221; in nhibernate</title>
		<link>http://www.codewrecks.com/blog/index.php/2010/04/03/multiple-bag-with-fetchjoin-in-nhibernate/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2010/04/03/multiple-bag-with-fetchjoin-in-nhibernate/#comments</comments>
		<pubDate>Sat, 03 Apr 2010 16:22:00 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2010/04/03/multiple-bag-with-fetchjoin-in-nhibernate/</guid>
		<description><![CDATA[
			
				
			
		
Suppose you have an entity like this
 
your NickName class has two bags, one containing a list of DomainRegistrations, and the other containing a series of Attachments. Now suppose you map both of these with fetch=”join”, this can cause a really really really big problem.
As you can read in this bug in NHibernate jira, you [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F04%2F03%2Fmultiple-bag-with-fetchjoin-in-nhibernate%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F04%2F03%2Fmultiple-bag-with-fetchjoin-in-nhibernate%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Suppose you have an entity like this</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2010/04/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2010/04/image_thumb.png" width="526" height="176" /></a> </p>
<p>your NickName class has two bags, one containing a list of DomainRegistrations, and the other containing a series of Attachments. Now suppose you map both of these with fetch=”join”, this can cause a really really really big problem.</p>
<p>As you can read in <a target="_blank" href="http://216.121.112.228/browse/NH-1471">this bug</a> in NHibernate jira, you should know that fetch join is not supported when there is more than one bag in the entity, because bag allows for duplicate items <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . When you do your unit testing of the basic mapping functionality (you should always unit test mappings&quot;) when you save a NickName with 2 domains and 2 attachments and reload it, the ISession will give you a nasty object with 4 Domains and 4 Attachments <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . If you think that NH should support this scenario think that bag allows duplicate, and this makes impossible for NH to understand from the resultset with fetch join, if the original object has 1 2 3 or 4 attachments. </p>
<p>The obvious solution is to change the fetch mode from join to select, but if you really want to be able to do a fetch=”join” you can consider if you really want to allow duplicates in your DomainRegistrations and Attachments properties. Mapping association from one to many with a bag is simple, because you can use an IList&lt;T&gt; interface in your domain classes. If you do not want to allow duplicates, and map the collection as a &lt;set&gt; instead of a &lt;bag&gt; you cannot use anymore the IList&lt;T&gt; interface. This is due to the fact that NHibernate rehydrate entities using a specific class that supports “set” semantic, not allowing a duplicate and it does not implement IList&lt;T&gt;. </p>
<p>In my situation, I can change those two properties from IList&lt;T&gt; to ICollection&lt;T&gt; and initialize them with HashSet&lt;T&gt; framework class. Now I’m able to map them with &lt;set&gt;, setting fetch mode to “join” avoiding the aforementioned duplicate problem. In the end I would prefer nhibernate to give me an error during mapping compile phase, something telling me “you cannot use fetch mode join on a bag when more than a bag is present in an entity”, instead of having strange behavior at runtime <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2010/04/03/multiple-bag-with-fetchjoin-in-nhibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Power of HQL &#8211; Condition on a collection</title>
		<link>http://www.codewrecks.com/blog/index.php/2010/03/09/power-of-hql-condition-on-a-collection/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2010/03/09/power-of-hql-condition-on-a-collection/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 11:27:34 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[HQL]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2010/03/09/power-of-hql-condition-on-a-collection/</guid>
		<description><![CDATA[
			
				
			
		
I have this piece of domain model.
 
The LinkResult class has a property called Link that point to a AnalyzedLink class that in turn has a collection of AnalyzedLinkExtClass called ExtData. All the relation are unidirectional, this means that there is nothing that bring me from AnalyzedLink to a linkResult and nothing that bring me [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F03%2F09%2Fpower-of-hql-condition-on-a-collection%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F03%2F09%2Fpower-of-hql-condition-on-a-collection%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I have this piece of domain model.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2010/03/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2010/03/image_thumb.png" width="683" height="180" /></a> </p>
<p>The LinkResult class has a property called Link that point to a AnalyzedLink class that in turn has a collection of AnalyzedLinkExtClass called ExtData. All the relation are unidirectional, this means that there is nothing that bring me from AnalyzedLink to a linkResult and nothing that bring me from AnalyzedLinkExtData to the AnalyzedLink. This is the typical situation where doing complex query can be tricky</p>
<p>Now I had to find all the LinkResult objects that have Status = LinkResultStatus.Ok and the associated AnalyzedLink must not contain an AnalyzedLinkExtData with the property Source equal to a certain value.</p>
<p>The query in HQL is</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #006080">@&quot;select L </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> from LinkResult L </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span> join L.Link AL </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span> where L.Status = :status and </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span> not exists (from AL.ExtData ED where ED.Source = :source) </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> order by L.AnalysisDate desc&quot;</span></pre>
<p><!--CRLF--></div>
</div>
<p>This is really powerful, I can simply start the query from the LinkResult object, then join to the L.Link and set a condition on L.Status property.</p>
<p>Now I add a<strong> not exists</strong> with the condition <em>(from AL.ExtData ED where ED.Source = :source)</em> as you can see I do not need to specify any join, but I can select directly from the ExtData Collection Property of the AnalyzedLink result. The SQL generated is</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">select</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span>        linkresult0_.Id <span style="color: #0000ff">as</span> Id175_,</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>        .....</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>    <span style="color: #0000ff">from</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>         LinkResult linkresult0_ </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>     <span style="color: #0000ff">inner</span> <span style="color: #0000ff">join</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span>         AnalyzedLink analyzedli1_ </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum8">   8:</span>     <span style="color: #0000ff">on</span> linkresult0_.link_id=analyzedli1_.link_id </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum9">   9:</span>     <span style="color: #0000ff">where</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum10">  10:</span>         linkresult0_.status=@p0 </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum11">  11:</span>         <span style="color: #0000ff">and</span>  <span style="color: #0000ff">not</span> (<span style="color: #0000ff">exists</span> (<span style="color: #0000ff">select</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum12">  12:</span>             extdata2_.aled_id </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum13">  13:</span>         <span style="color: #0000ff">from</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum14">  14:</span>             AnalyzedLinksExtData extdata2_ </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum15">  15:</span>         <span style="color: #0000ff">where</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum16">  16:</span>             analyzedli1_.link_id=extdata2_.aled_link_id </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum17">  17:</span>             <span style="color: #0000ff">and</span> extdata2_.aled_source=@p1)) </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum18">  18:</span>     <span style="color: #0000ff">order</span> <span style="color: #0000ff">by</span></pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum19">  19:</span>         linkresult0_.analysisDate <span style="color: #0000ff">desc</span>;</pre>
<p><!--CRLF--></div>
</div>
<p>The real magic is done in the subquery, because you can verify that the condition on subquery contains two condition, the first is the link with the outer query, and the second one is the one we put on HQL. But you can surely appreciate the fact that in HQL the query is really clearer and shorter <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2010/03/09/power-of-hql-condition-on-a-collection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Work with castle and NHibernate trunk</title>
		<link>http://www.codewrecks.com/blog/index.php/2010/02/26/work-with-castle-and-nhibernate-trunk/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2010/02/26/work-with-castle-and-nhibernate-trunk/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 17:37:56 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Castle]]></category>
		<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2010/02/26/work-with-castle-and-nhibernate-trunk/</guid>
		<description><![CDATA[
			
				
			
		
Working with open source software is fun, but sometimes can be difficult. Take as example castle and Nhibernate, since castle references nh with the NHIntegration facility, and at the same time NH references castle for Dynamic Proxy.
A good way to survive this chaos, is working with the trunk, as I usually do, but compiling everything [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F02%2F26%2Fwork-with-castle-and-nhibernate-trunk%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2010%2F02%2F26%2Fwork-with-castle-and-nhibernate-trunk%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Working with open source software is fun, but sometimes can be difficult. Take as example castle and Nhibernate, since castle references nh with the NHIntegration facility, and at the same time NH references castle for Dynamic Proxy.</p>
<p>A good way to survive this chaos, is working with the trunk, as I usually do, but compiling everything can be quite complex, but we are lucky because we have a project called <a target="_blank" href="http://github.com/dagda1/horn_src">Horn</a> that does everything for you.</p>
<p>First of all you need to install <a target="_blank" href="http://code.google.com/p/msysgit/downloads/list">nsysgit</a> first of all you need to grab the latest source of horn with the comand “git clone <a target="_blank" title="git://github.com/dagda1/horn_src.git" href="git://github.com/dagda1/horn_src.git">git://github.com/dagda1/horn_src.git</a>”. Once you get the source, you need to modify a source file called /src/horn.console/program.cs, in this file there is a function called GetRootFolderPath that ends with a line like</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> var ret = <span style="color: #0000ff">new</span> DirectoryInfo(rootFolder);</pre>
<p><!--CRLF--></div>
</div>
<p>This line needs to be modified with the following line</p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> var ret = <span style="color: #0000ff">new</span> DirectoryInfo(@&quot;d:\osdevelop\horn_src\&quot; + PackageTree.RootPackageTreeName);</pre>
<p><!--CRLF--></div>
</div>
<p>clearly the D:\osdevelop\horn_src is my physical path where git extracted horn source code. Now you can go project root and run the HornBuild.bat. If the compilation is successful the horn library was compiled correctly, so you can go to /src/build/net-3.5/debug and you should find a program called horn.exe. Go to this location with a command line and type </p>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> horn -install:castle.facilities.nhibernateintegration</pre>
<p><!--CRLF--></div>
</div>
<p>with this command horn try to build everything needed for castle facilities nhibernate integration, so horn contacts all various repositories of all the needed libraries, it downloads the latest source and compiles everything. IF everything is gone good, you can simply go to the directory .horn\result and find all the dll’s <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  without worrying about order of compilation, source repositories etc etc.</p>
<p>Alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> </p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/Castle" rel="tag">Castle</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2010/02/26/work-with-castle-and-nhibernate-trunk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Show NHibernate query in the trace of asp.net pages</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/10/13/show-nhibernate-query-in-the-trace-of-aspnet-pages/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/10/13/show-nhibernate-query-in-the-trace-of-aspnet-pages/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 17:27:04 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/10/13/show-nhibernate-query-in-the-trace-of-aspnet-pages/</guid>
		<description><![CDATA[
			
				
			
		
When you use NHibernate and asp.net one of the most interesting stuff is looking at sql generated for each page call. While NHProf is the best tool to accomplish this task, it is interesting to trace issued sql queries using asp.net trace engine.
To accomplish this task is really straightforward thanks to log4net, first of all [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F10%2F13%2Fshow-nhibernate-query-in-the-trace-of-aspnet-pages%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F10%2F13%2Fshow-nhibernate-query-in-the-trace-of-aspnet-pages%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>When you use NHibernate and asp.net one of the most interesting stuff is looking at sql generated for <em>each page call</em>. While <a target="_blank" href="http://www.nhprof.com/">NHProf</a> is the best tool to accomplish this task, it is interesting to trace issued sql queries using asp.net trace engine.</p>
<p>To accomplish this task is really straightforward thanks to log4net, first of all configure a suitable appender in log4net config file.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:f3c734d5-8004-499a-8e42-3dd7214904cb" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">appender </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="AspNetTraceAppender"</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">="log4net.Appender.AspNetTraceAppender"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">layout </span><span style="color: #FF0000;">type</span><span style="color: #0000FF;">="log4net.Layout.PatternLayout"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
        </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">conversionPattern </span><span style="color: #FF0000;">value</span><span style="color: #0000FF;">="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">layout</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">appender</span><span style="color: #0000FF;">&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This appender sends all messages to asp.net trace engine, then enable tracing in the web.config.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8d284894-8cb4-4943-9826-d5c12aebd9f2" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #000000;"> </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">trace </span><span style="color: #FF0000;">enabled</span><span style="color: #0000FF;">="true"</span><span style="color: #FF0000;"> pageOutput</span><span style="color: #0000FF;">="true"</span><span style="color: #FF0000;"> requestLimit</span><span style="color: #0000FF;">="100"</span><span style="color: #FF0000;"> localOnly</span><span style="color: #0000FF;">="true"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Now you need to configure log4net to issue all nhibernate logs to the previous appender.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:677753c2-1271-44fc-9b94-48700620d6e9" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">logger </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="NHibernate"</span><span style="color: #FF0000;"> additivity</span><span style="color: #0000FF;">="false"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">level </span><span style="color: #FF0000;">value</span><span style="color: #0000FF;">="INFO"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">appender-ref </span><span style="color: #FF0000;">ref</span><span style="color: #0000FF;">="AspNetTraceAppender"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">logger</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">

</span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">logger </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="NHibernate.SQL"</span><span style="color: #FF0000;"> additivity</span><span style="color: #0000FF;">="false"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">level </span><span style="color: #FF0000;">value</span><span style="color: #0000FF;">="DEBUG"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">appender-ref </span><span style="color: #FF0000;">ref</span><span style="color: #0000FF;">="AspNetTraceAppender"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">logger</span><span style="color: #0000FF;">&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>I keep the standard level of NHIbernate to INFO, but the NHibernate.SQL to DEBUG. The result is the following.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2009/10/image6.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2009/10/image-thumb6.png" width="642" height="204" /></a> </p>
<p>Et voila, you get all the query that were issued to the database in the trace of your page, without the need to attach debugger or trace or whatever else. This is especially interesting if you use continuous integration and all testers usually work with latest site version running on test server. With such a facility everyone can look at what is really happening to the database.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/10/13/show-nhibernate-query-in-the-trace-of-aspnet-pages/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate ICriteria and filters</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/10/13/nhibernate-icriteria-and-filters/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/10/13/nhibernate-icriteria-and-filters/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 16:05:38 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[ICriteria]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/10/13/nhibernate-icriteria-and-filters/</guid>
		<description><![CDATA[
			
				
			
		
I have a project where I need to access tables with millions of rows, the project was born without nhibernate so the database was not designed with ORM in mind. I decided to improve performances with an Indexed view that materialized a join between five tables, wrapped with another view that does a left outer [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F10%2F13%2Fnhibernate-icriteria-and-filters%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F10%2F13%2Fnhibernate-icriteria-and-filters%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I have a project where I need to access tables with millions of rows, the project was born without nhibernate so the database was not designed with ORM in mind. I decided to improve performances with an Indexed view that materialized a join between five tables, wrapped with another view that does a left outer joins with other 3 tables. Then I created an entity called XXXDto, and mapped with nhibernate, with update=”false” to prevent updating and pointed it to this view.</p>
<p>Everything runs fine, but now I have a little new feature to implement; that entity needs another property called Bookmark, and the value is specific of each user. In the software the user can search the aforementioned entity with some criteria, then he bookmarks the ones he likes most, and the software must signal bookmarked ones with a different image in the web ui. The problem is that bookmark table was already present in the database and has this schema.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2009/10/image5.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2009/10/image-thumb5.png" width="352" height="77" /></a> </p>
<p>This table works this way, if a user put a bookmark on an entity, a record with username and link_id (the foreign key to other table) is inserted, if the bookmark is removed the record is removed. Now I want to avoid the N+1 select, so I decided not to issue another query for each one of the original links, moreover I used ICriteria to recover entities, since the user can set complex filter through the UI and ICriteria makes really simple to compose the query. </p>
<p>Thanks to nhibernate I can use a formula in the mapping, but I need to put a condition on that formula, here is how I solved the problem.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:4e351cc7-6429-41bb-913b-bbdaf71e5ac2" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">property
</span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="Bookmark"</span><span style="color: #FF0000;">
formula</span><span style="color: #0000FF;">="(select count(*) from Bookmark B where B.bookmark_link_id = Id and B.bookmark_user = :UserContext.UserName)"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
  </span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>The formula is based on the fact that Bookmark is a boolean field, so if I issue a select count(*) everything is ok because if the bookmark is present the value is 1 if it is not present the value is 0, suitable for a boolean field. The condition is that bookmark_link_id = Id where id is the id column of the entity, and the user condition is B.Bookmark_User = :UserContext.UserName. This instruction uses a <a target="_blank" href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/filters.html">filter</a>, a global parameter supported by nhibernate, that permits me to put parameters in mappings. Now I need to define this filter in a mapping.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:473afb5e-f806-42a7-9754-1d694ba8c76b" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">hibernate-mapping </span><span style="color: #FF0000;">xmlns</span><span style="color: #0000FF;">="urn:nhibernate-mapping-2.2"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">filter-def </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">='UserContext'&gt;
        </span><span style="color: #FF0000;">&lt;filter-param name</span><span style="color: #0000FF;">='UserName' </span><span style="color: #FF0000;">type</span><span style="color: #0000FF;">='System.String'/&gt;
    </span><span style="color: #FF0000;">&lt;/filter-def</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">hibernate-mapping</span><span style="color: #0000FF;">&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Now that the filter is defined I need to set the appropriate value in code before issuing the query. Since I wrapped the query in a Query object specific of that project I have a similar code that translate my Query object to a ICriteria + Session in nhibernate</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:260a3b98-fc15-4239-8c03-a7ba37ea8e56" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (Query.Filter filter </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> myQuery.Filters)
{
    IFilter nhibFilter </span><span style="color: #000000;">=</span><span style="color: #000000;"> _session.EnableFilter(filter.Name);
    </span><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (KeyValuePair</span><span style="color: #000000;">&lt;</span><span style="color: #0000FF;">string</span><span style="color: #000000;">, </span><span style="color: #0000FF;">object</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> parameter </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> filter.Parameters)
    {
        nhibFilter.SetParameter(parameter.Key, parameter.Value);
    }
}</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>To create a filter you can simply call EnableFilter() method on a session, then you set specific filter on the IFilter object returned from the EnableFilter(). Here is the query generated by this mapping.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:1b470bdb-d7f6-4ef6-b773-179c07927fa1" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #0000FF;">select</span><span style="color: #000000;"> </span><span style="color: #0000FF;">top</span><span style="color: #000000;"> </span><span style="color: #800000; font-weight: bold;">20</span><span style="color: #000000;"> this_.Id </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> Id31_0_,
this_.Name, ....,
(</span><span style="color: #0000FF;">select</span><span style="color: #000000;"> </span><span style="color: #FF00FF;">count</span><span style="color: #000000;">(</span><span style="color: #808080;">*</span><span style="color: #000000;">) </span><span style="color: #0000FF;">from</span><span style="color: #000000;"> Bookmark B </span><span style="color: #0000FF;">where</span><span style="color: #000000;"> B.bookmark_link_id </span><span style="color: #808080;">=</span><span style="color: #000000;"> this_.Id </span><span style="color: #808080;">and</span><span style="color: #000000;"> B.bookmark_user </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #008000;">@p0</span><span style="color: #000000;">) </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> formula1_0_ </span><span style="color: #0000FF;">FRom</span><span style="color: #000000;"> ..... </span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The only drawback is that in formula mapping you must use the sql name of the column involved (in that example I need to use bookmark_link_id = Id where id is the real column name that contains id), but the query is correct and everything works perfectly.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Formula" rel="tag">Formula</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/10/13/nhibernate-icriteria-and-filters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Theta join in HQL &#8211; join with unrelated entities</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/09/04/theta-join-in-hql-join-with-unrelated-entities/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/09/04/theta-join-in-hql-join-with-unrelated-entities/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 11:14:21 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/09/04/theta-join-in-hql-join-with-unrelated-entities/</guid>
		<description><![CDATA[
			
				
			
		
NHibernate HQL language is really powerful, and work in many scenario. Suppose you have those two classes.
 
Action is an object capable of executing something, while ActionLog stores the result of the execution of an action. There is no direct relation between the two, so in ActionLog we have not a reference to Action, but [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F09%2F04%2Ftheta-join-in-hql-join-with-unrelated-entities%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F09%2F04%2Ftheta-join-in-hql-join-with-unrelated-entities%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>NHibernate HQL language is really powerful, and work in many scenario. Suppose you have those two classes.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2009/09/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2009/09/image-thumb.png" width="396" height="511" /></a> </p>
<p>Action is an object capable of executing something, while ActionLog stores the result of the execution of an action. There is no direct relation between the two, so in ActionLog we have not a reference to Action, but a simple field called ActionId that stores the id of the action. The reason for this choice is that Action objects can be deleted (and there is a special form of action called SpawnedAction that gets created, executed, and finally phisically deleted from the table); ActionLog must be retained even for deleted action, so we prefer not to store a direct relation.</p>
<p>Everything works fine, but today I need to create a dto that transfer for each failed ActionLog both the ActionLog class and the Action class to access field from action. A first solution is to retrieve all ActionLog, then for each ActionLog load the appropriate Action using ActionId, but this will cause N+1 select.</p>
<p>Thanks to HQL we can use theta joins, here is my HQL</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:f397b331-6620-4b8d-99c7-75ce6ba00517" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">Select</span><span style="color: #000000;"> L, A </span><span style="color: #0000FF;">from</span><span style="color: #000000;"> ActionLog L, Action A  </span><span style="color: #0000FF;">where</span><span style="color: #000000;"> L.ActionId </span><span style="color: #808080;">=</span><span style="color: #000000;"> A.id </span><span style="color: #808080;">and</span><span style="color: #000000;"> L.IsSuccess </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #800000; font-weight: bold;">0</span><span style="color: #000000;"> </span><span style="color: #0000FF;">order</span><span style="color: #000000;"> </span><span style="color: #0000FF;">by</span><span style="color: #000000;"> L.StartDate </span><span style="color: #0000FF;">desc</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>As you can see i select L and A from ActionLog and Action, then in where condition I’ll insert the join condition L.ActionId with A.id, where <em>id </em>is a special property name in HQL that gets translated to the name of the property used as identifier for the Action class.</p>
<p>The result of this query is an arraylist, where each element is an array of objects, an instance of ActionLog and the corresponding instance of Action. Then I proceed creating this object</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2009/09/image1.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2009/09/image-thumb1.png" width="170" height="190" /></a> </p>
<p>the ActionErrorLog is a Dto that returns to the caller a couple consisting of a Log and corresponding action. Retrieving a list of ActionErrorLog is really simple.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:2a5377f3-a2d0-4552-a4ca-46ed48ecd8b3" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #000000;">IList logs </span><span style="color: #000000;">=</span><span style="color: #000000;"> uow.Session.CreateQuery(</span><span style="color: #800000;">"</span><span style="color: #800000;">Select L, A from ActionLog L, Action A  where L.ActionId = A.id and L.IsSuccess = 0 order by L.StartDate desc</span><span style="color: #800000;">"</span><span style="color: #000000;">)
    .SetFirstResult(pageNum </span><span style="color: #000000;">*</span><span style="color: #000000;"> pageSize)
    .SetMaxResults(pageSize)
    .List();
</span><span style="color: #0000FF;">return</span><span style="color: #000000;"> logs
    .Cast</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Object[]</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">()
    .Select(ae </span><span style="color: #000000;">=&gt;</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> ActionErrorLog((ActionLog)ae[</span><span style="color: #800080;">0</span><span style="color: #000000;">], (Action)ae[</span><span style="color: #800080;">1</span><span style="color: #000000;">]))
    .ToList();</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>With the HQL query I recover all the couple Log-Action, then with a simple LINQ to object expression I can create all the object I need.</p>
<p>The only important stuff you need to remember, is that theta join are Inner join, so with the above query you do not find ActionLog where the corresponding action is deleted. I have no problem because I really need to show only result of actions that are still in the table. <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/09/04/theta-join-in-hql-join-with-unrelated-entities/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Browse NHibernate metadata to validate property Length</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/08/23/browse-nhibernate-metadata-to-validate-property-length/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/08/23/browse-nhibernate-metadata-to-validate-property-length/#comments</comments>
		<pubDate>Sun, 23 Aug 2009 17:08:00 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/08/23/browse-nhibernate-metadata-to-validate-property-length/</guid>
		<description><![CDATA[
			
				
			
		
One of the most basic validation rule for Entities that are stored in databases, is to be sure that String Properties are not too long for the corresponding field in database. There are a lot of validation framework over there, most of them using attributes to specify constraints on properties or fields, but what happens [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F08%2F23%2Fbrowse-nhibernate-metadata-to-validate-property-length%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F08%2F23%2Fbrowse-nhibernate-metadata-to-validate-property-length%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>One of the most basic validation rule for Entities that are stored in databases, is to be sure that String Properties are not too long for the corresponding field in database. There are a lot of validation framework over there, most of them using attributes to specify constraints on properties or fields, but what happens if someone changes a mapping setting a different length for a field? </p>
<p>I’m a great fan of database generation with NHibernate, so here is a typical mapping of mine.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:f53fbddf-48f9-4cf0-a917-8ddadb78acc6" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">hibernate-mapping </span><span style="color: #FF0000;">xmlns</span><span style="color: #0000FF;">="urn:nhibernate-mapping-2.2"</span><span style="color: #FF0000;">
                         assembly</span><span style="color: #0000FF;">="DotNetMarche.Validator.Tests"</span><span style="color: #FF0000;">
                         namespace</span><span style="color: #0000FF;">="DotNetMarche.Validator.Tests.Extras.NHibernate"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">class </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="EntityBase"</span><span style="color: #FF0000;"> table</span><span style="color: #0000FF;">="EntityBase"</span><span style="color: #FF0000;"> lazy</span><span style="color: #0000FF;">="false"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
        </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">id </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="Id"</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">="id"</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">="System.Int32"</span><span style="color: #FF0000;"> unsaved-value</span><span style="color: #0000FF;">="0"</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
            </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">generator </span><span style="color: #FF0000;">class</span><span style="color: #0000FF;">="native"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
        </span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">id</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">

        </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">property </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="MyName"</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">="code"</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">="System.String"</span><span style="color: #FF0000;"> length</span><span style="color: #0000FF;">="50"</span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
        </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">property </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="AnotherProperty"</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">="name"</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">="System.String"</span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">class</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">

</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">hibernate-mapping</span><span style="color: #0000FF;">&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This is a class for unit testing a specific routine, it has a property called MyName that have length specified in the mapping, now I want to create a Validator that is able to automatically create rules from the mapping. The goal is automatically find maximum string length from mapping, thus avoiding the extra work to create attributes for each property, and moreover if you change the mapping, the rule changes accordingly. Here is a routing that does this .</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:735eb527-9fe1-4951-be3b-b34d5770fddb" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">static</span><span style="color: #000000;"> Core.Validator GetValidatorFromSession(ISessionFactory sessionFactory)
{
    var allDefindedClasses </span><span style="color: #000000;">=</span><span style="color: #000000;"> sessionFactory.GetAllClassMetadata();
    Core.Validator validator </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Core.Validator();
    </span><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (KeyValuePair</span><span style="color: #000000;">&lt;</span><span style="color: #0000FF;">string</span><span style="color: #000000;">, IClassMetadata</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> pair </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> allDefindedClasses)
    {
        IClassMetadata metadata </span><span style="color: #000000;">=</span><span style="color: #000000;"> pair.Value;
        </span><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (</span><span style="color: #0000FF;">string</span><span style="color: #000000;"> propertyName </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> metadata.PropertyNames)
        {
            IType propertyType </span><span style="color: #000000;">=</span><span style="color: #000000;"> metadata.GetPropertyType(propertyName);
            StringType st </span><span style="color: #000000;">=</span><span style="color: #000000;"> propertyType </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> StringType;
            </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (st </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">)
            {
                </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (st.SqlType.Length </span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> </span><span style="color: #800080;">0</span><span style="color: #000000;">)
                {
                    validator.AddRule(Rule.For(metadata.GetMappedClass(EntityMode.Poco))
                        .OnMember(propertyName)
                          .MaxLength(st.SqlType.Length)
                          .Message(String.Format(
                                </span><span style="color: #800000;">"</span><span style="color: #800000;">Property {0} have a maximum length of {1}</span><span style="color: #800000;">"</span><span style="color: #000000;">,
                                    propertyName,
                                      st.SqlType.Length)));
                }
            }
        }
    }
    </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> validator;
}</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>Thanks to IClassMetadata class exposed from Nhibernate, we can inspect the content of mapping browsing nhibernate object model in memory. In this situation I iterate for each mapped class, then for each property I check if it is a String property and look for maximum length. If it is different from zero it means that there is some maximum length specified in the mapping, so I create a corresponding rule. This simple code makes this test pass.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:9a37a99f-7b02-40ad-a981-4c82e1778324" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">Core.Validator validator </span><span style="color: #000000;">=</span><span style="color: #000000;"> ValidatorFromMetadata.GetValidatorFromSession(Factory);
EntityBase eb </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> EntityBase() {MyName </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> </span><span style="color: #0000FF;">string</span><span style="color: #000000;">(</span><span style="color: #800000;">'</span><span style="color: #800000;">X</span><span style="color: #800000;">'</span><span style="color: #000000;">, </span><span style="color: #800080;">51</span><span style="color: #000000;">)};
ValidationResult res </span><span style="color: #000000;">=</span><span style="color: #000000;"> validator.ValidateObject(eb);
Assert.That(res.Success, Is.False);
Assert.That(res.ErrorMessages[</span><span style="color: #800080;">0</span><span style="color: #000000;">], Is.EqualTo(</span><span style="color: #800000;">"</span><span style="color: #800000;">Property MyName have a maximum length of 50</span><span style="color: #800000;">"</span><span style="color: #000000;">));</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This verifies that the validator reflects rules contained in nhibernate mappings.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Validation" rel="tag">Validation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/08/23/browse-nhibernate-metadata-to-validate-property-length/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Manage Scope or Execution Context of Repository</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/08/07/manage-scope-or-execution-context-of-repository/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/08/07/manage-scope-or-execution-context-of-repository/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 10:52:00 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Castle]]></category>
		<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/08/07/manage-scope-or-execution-context-of-repository/</guid>
		<description><![CDATA[
			
				
			
		
In a project I’m working with Guardian, we are using NHibernate behind a Repository Pattern. Despite the question if is good or not good to shield the session behind a Repository,we encountered a classic problem.
The software is structured as service, we use Castle Nhibernate Facility and Wcf Integration Facility plus a simple interceptor that manages [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F08%2F07%2Fmanage-scope-or-execution-context-of-repository%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F08%2F07%2Fmanage-scope-or-execution-context-of-repository%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In a project I’m working with <a target="_blank" href="http://www.nablasoft.com/guardian">Guardian</a>, we are using <a target="_blank" href="https://www.hibernate.org/343.html">NHibernate</a> behind a Repository Pattern. Despite the question if is good or not good to shield the session behind a Repository,we encountered a classic problem.</p>
<p>The software is structured as service, we use <a target="_blank" href="http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html">Castle Nhibernate Facility</a> and <a target="_blank" href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html">Wcf Integration Facility</a> plus a simple interceptor that manages the concept of “Single session per service call”. Now we are developing some interface in WPF, and this program can dialogate directly with database, without the need to access the db through wcf service. Since we are using MVVM, we makes heavy use of binding, and we like to use lazy load, to keep the logic simple. Instead of returning Dto, a special service class is used to directly return NHibernate persistent object, and if the user want to browse some internal collection of this object we can simply bind the view to entity collection property, and the collection will be fetched when needed with lazy load. Since we have a tree structure this solution is really simple and works really well.</p>
<p>The problem arise because the repository use a single session per call, so when the ViewModel ask for an object, the service return a disconnected object.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2009/08/image15.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="484" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2009/08/image-thumb15.png" width="219" border="0" /></a> </p>
<p>This happens because the repository does not have control over the lifetime of the session, it simply open the session, does whatever he need to does with the session, and then Dispose it. Nhibernate Castle integration helps a lot because it keeps track of session reference counting, so if you open a session, and in the same CallContext you open another session, you get a sort of a “weak reference” to the original session. This means that the session gets disposed only when the first created session is disposed.</p>
<p>To use Lazy load in the ViewModel we could simply call ISessionManager.OpenSession() in the constructor of the ViewModel and dispose resulting session in ViewModel Dispose() function. This is not good because it violates repository encapsulation, because you must know how repository is implemented internally.</p>
<p>Moreover it is really ugly to see a nhibernate ISession created in the ViewModel, only to keep session alive, because it vanished all benefit of shielding the ISession behind a repository. A better solution is to create a class like this one.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:76d1b492-d235-4388-9fc4-f975d41d9673" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">class</span><span style="color: #000000;"> RepositoryScope : IDisposable
{
    </span><span style="color: #0000FF;">private</span><span style="color: #000000;"> ISessionManager SessionManager { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }
    </span><span style="color: #0000FF;">private</span><span style="color: #000000;"> ISession Session { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }

    </span><span style="color: #0000FF;">protected</span><span style="color: #000000;"> RepositoryScope(ISessionManager manager)
    {
        SessionManager </span><span style="color: #000000;">=</span><span style="color: #000000;"> manager;
    }

    </span><span style="color: #0000FF;">#region</span><span style="color: #000000;"> IDisposable Members</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> Dispose()
    {
        </span><span style="color: #808080;">///</span><span style="color: #008000;">close the most external scope</span><span style="color: #808080;">
</span><span style="color: #000000;">        Session.Dispose();
    }

    </span><span style="color: #0000FF;">#endregion</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">static</span><span style="color: #000000;"> RepositoryScope BeginScope()
    {
        RepositoryScope scope </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> RepositoryScope(
            IoC.Resolve</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">ISessionManager</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">());
        scope.Session </span><span style="color: #000000;">=</span><span style="color: #000000;"> scope.SessionManager.OpenSession(
            ConfigurationRegistry.MainDatabaseConnectionName);
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> scope;
    }
}</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This simple class does internally a simple task, it creates a session and dispose in Dispose() method. In this way if you call RepositoryScope.BeginScope() you are actually creating a ISEssion that will be disposed when you will call Dispose() on the RepositoryScope object. </p>
<p>With this simple class the repository remains unchanged, and the caller can manage the lifecycle of repository context, without the need to know his internal implementation. </p>
<p>Alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/Castle" rel="tag">Castle</a> <a target="_blank" href="http://technorati.com/tag/Nhibernate" rel="tag">Nhibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/08/07/manage-scope-or-execution-context-of-repository/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manage In memory nhibernate test with sqlite and database schema</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/07/24/manage-in-memory-nhibernate-test-with-sqlite-and-database-schema/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/07/24/manage-in-memory-nhibernate-test-with-sqlite-and-database-schema/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 17:07:23 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/07/24/manage-in-memory-nhibernate-test-with-sqlite-and-database-schema/</guid>
		<description><![CDATA[
			
				
			
		
When you work with nhibernate you usually write a lot of tests that interact with your database, mainly to test your mapping but also when you do not want to shield the session behind a IRepository. To avoid Slow Test you should use some In Memory database like Sqlite, but it can be problematic when [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F07%2F24%2Fmanage-in-memory-nhibernate-test-with-sqlite-and-database-schema%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F07%2F24%2Fmanage-in-memory-nhibernate-test-with-sqlite-and-database-schema%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>When you work with nhibernate you usually write a lot of tests that interact with your database, mainly to test your mapping but also when you do not want to shield the session behind a IRepository. To avoid <a target="_blank" href="http://xunitpatterns.com/Slow%20Tests.html">Slow Test</a> you should use some In Memory database like <a target="_blank" href="http://www.sqlite.org/">Sqlite</a>, but it can be problematic when you use features of your real database (like Sql Server) that are not supported by the Sqlite engine.</p>
<p>One of the most frustrating one is the lack of schema support. When you have hundreds of entities, it is of fundamental importance that you use schema, avoiding to pollute the dbo with all the table, but this makes difficult to use Sqlite for testing purpose. Suppose you map an entity to the table <em><strong>myschema.RawMetabaseData</strong></em>, when you create the schema with schemaexport you will obtain this error</p>
<p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:46694319-abd5-4813-a132-971cbe0b6319" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">Error: Error during fixture setup NHibernate</span><span style="color: #000000;">.</span><span style="color: #000000;">HibernateException: SQLite error
unknown database myschema ---</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> System</span><span style="color: #000000;">.</span><span style="color: #000000;">Data</span><span style="color: #000000;">.</span><span style="color: #000000;">SQLite</span><span style="color: #000000;">.</span><span style="color: #000000;">SQLiteException: SQLite error
unknown database myschema
</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>SQlite does not know the concept of schema, so it believes that myschema is a database name and not&#160; a schema. There are some solution to this problem, but the most simple one is to change the mapping directly in memory. </p>
<p><div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:9c10c731-8157-4f7e-9dd4-effd5b941158" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">cfg.AddAssembly(</span><span style="color: #800000;">"</span><span style="color: #800000;">myassembly</span><span style="color: #800000;">"</span><span style="color: #000000;">);
</span><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (PersistentClass pc </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> cfg.ClassMappings)
{
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (pc.Table.Name.Contains(</span><span style="color: #800000;">"</span><span style="color: #800000;">.</span><span style="color: #800000;">"</span><span style="color: #000000;">))
    {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">this is a table with schema</span><span style="color: #008000;">
</span><span style="color: #000000;">        pc.Table.Name </span><span style="color: #000000;">=</span><span style="color: #000000;"> pc.Table.Name.Replace(</span><span style="color: #800000;">"</span><span style="color: #800000;">.</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">_</span><span style="color: #800000;">"</span><span style="color: #000000;">);
    }
}
ISessionFactory sf </span><span style="color: #000000;">=</span><span style="color: #000000;"> cfg.BuildSessionFactory();</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>After you have called the AddAssembly() method, but before you create the SessionFactory with BuildSessionFactory(), mappings are compiled in memory, so you can browse the object model created from the xml mapping files, looking for table that contains dot character, and change the dot into an underscore, so the table can be used by Sqlite. This code is executed only for tests that uses SqlLite so my standard test that use Sql Server are not affected by the modification, but I can still use Sqlite to do fast in memory test even with tables in custom schema.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Sqlite" rel="tag">Sqlite</a> <a target="_blank" href="http://technorati.com/tag/Unit Testing" rel="tag">Unit Testing</a></p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/07/24/manage-in-memory-nhibernate-test-with-sqlite-and-database-schema/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Saving a generic Object property with nhibernate</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/05/22/saving-a-generic-object-property-with-nhibernate/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/05/22/saving-a-generic-object-property-with-nhibernate/#comments</comments>
		<pubDate>Fri, 22 May 2009 06:35:34 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/05/22/saving-a-generic-object-property-with-nhibernate/</guid>
		<description><![CDATA[
			
				
			
		
In a old post I explained how to save an object in XML format in database with a UserType. Since this technique worked well I decided to use it in another situation. Now I have an object that have a property of type Object, and I want to be able to save xml serialiation of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F22%2Fsaving-a-generic-object-property-with-nhibernate%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F22%2Fsaving-a-generic-object-property-with-nhibernate%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In a <a href="http://www.codewrecks.com/blog/index.php/2009/05/14/use-xml-field-in-sqlserver-with-nhibernate/">old post</a> I explained how to save an object in XML format in database with a UserType. Since this technique worked well I decided to use it in another situation. Now I have an object that have a property of type Object, and I want to be able to save xml serialiation of it into database.</p>
<p>First of all I decided that it is better to use two columns, one will store the xml serialization, while the other will contain type name of the object, so I build a simple ICompositeUserType</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6ebd69e1-2b01-49a6-9707-8d55e010565e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">class</span><span style="color: #000000;"> XmlSerializedObject : ICompositeUserType
{
    </span><span style="color: #0000FF;">#region</span><span style="color: #000000;"> Equals member</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">bool</span><span style="color: #000000;"> ICompositeUserType.Equals(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> x, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> y)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> (x </span><span style="color: #000000;">==</span><span style="color: #000000;"> y) </span><span style="color: #000000;">||</span><span style="color: #000000;"> ((x </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">) </span><span style="color: #000000;">&amp;&amp;</span><span style="color: #000000;"> x.Equals(y));
    }

    </span><span style="color: #0000FF;">#endregion</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">#region</span><span style="color: #000000;"> ICompositeUserType Members</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> Assemble(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> cached, NHibernate.Engine.ISessionImplementor session, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> cached;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> DeepCopy(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value)
    {
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">) </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #0000FF;">is</span><span style="color: #000000;"> ICloneable) </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> ((ICloneable) value).Clone();
        </span><span style="color: #0000FF;">throw</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> NotSupportedException(
            String.Format(
                </span><span style="color: #800000;">"</span><span style="color: #800000;">You can use XmlSerializedObject only to serialize ICloneable objects. Type {0} does not support ICloneable</span><span style="color: #800000;">"</span><span style="color: #000000;">,
                value.GetType()));
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> Disassemble(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value, NHibernate.Engine.ISessionImplementor session)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> value;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> GetHashCode(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> x)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> x.GetHashCode();
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> GetPropertyValue(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> component, </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> property)
    {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">0 is the object and 1 is the type.</span><span style="color: #008000;">
</span><span style="color: #000000;">        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (property </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #800080;">0</span><span style="color: #000000;">) </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> component;
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> component.GetType().FullName;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">bool</span><span style="color: #000000;"> IsMutable
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">true</span><span style="color: #000000;">; }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> NullSafeGet(System.Data.IDataReader dr, </span><span style="color: #0000FF;">string</span><span style="color: #000000;">[] names, NHibernate.Engine.ISessionImplementor session, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
    {
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (dr </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">) </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (dr.IsDBNull(dr.GetOrdinal(names[</span><span style="color: #800080;">0</span><span style="color: #000000;">]))) </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;

        String serializedData </span><span style="color: #000000;">=</span><span style="color: #000000;"> (String) dr[names[</span><span style="color: #800080;">0</span><span style="color: #000000;">]];
        Type serializedType </span><span style="color: #000000;">=</span><span style="color: #000000;"> Type.GetType((String)dr[names[</span><span style="color: #800080;">1</span><span style="color: #000000;">]]);
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> XmlHelper.FromXml(serializedData, serializedType);
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> NullSafeSet(System.Data.IDbCommand cmd, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value, </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> index, NHibernate.Engine.ISessionImplementor session)
    {
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;"> </span><span style="color: #000000;">||</span><span style="color: #000000;"> value </span><span style="color: #000000;">==</span><span style="color: #000000;"> DBNull.Value)
        {
            NHibernateUtil.String.NullSafeSet(cmd, </span><span style="color: #0000FF;">null</span><span style="color: #000000;">, index, session);
            NHibernateUtil.String.NullSafeSet(cmd, </span><span style="color: #0000FF;">null</span><span style="color: #000000;">, index </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800080;">1</span><span style="color: #000000;">, session);
        }
        </span><span style="color: #0000FF;">else</span><span style="color: #000000;">
        {

            String typeName </span><span style="color: #000000;">=</span><span style="color: #000000;"> TypeUtils.GetTypeNameAssemblyQualified(value);
            NHibernateUtil.String.NullSafeSet(cmd, XmlHelper.ToXml(value), index, session);
            NHibernateUtil.String.NullSafeSet(cmd, typeName, index </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800080;">1</span><span style="color: #000000;">, session);
        }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">string</span><span style="color: #000000;">[] PropertyNames
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> []{</span><span style="color: #800000;">"</span><span style="color: #800000;">XmlData</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">Type</span><span style="color: #800000;">"</span><span style="color: #000000;">}; }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> NHibernate.Type.IType[] PropertyTypes
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> [] {NHibernateUtil.String, NHibernateUtil.String}; }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> Replace(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> original, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> target, NHibernate.Engine.ISessionImplementor session, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> original;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> Type ReturnedClass
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">typeof</span><span style="color: #000000;"> (Object); }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> SetPropertyValue(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> component, </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> property, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value)
    {

    }

    </span><span style="color: #0000FF;">#endregion</span><span style="color: #000000;">
}</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>It works quite well, but it has some drawbacks. First of all since this property is mutable, the object must implement ICLoneable to create a copy of it. This fact has another implication, when the session flushes, NHibernate calls Equals to verify if actual instance is changed from the time it was loaded, now since the copy used to keep the original value is created with Clone, if the object does not implement equals, it would be always considered different from the copy in the cache, and it will be saved at each flush. To avoid this, all objects used in this property must implement equals.</p>
<p>The rest of the code is quite simple. This userType gives me great flexibility, moreover, since the database have mixed access stored+nhibernate, I used a Xml column in sql server, so I’m able to do XPath query in my stored.</p>
<p>Alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/05/22/saving-a-generic-object-property-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using ISQlQuery to load data with nhibernate</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/05/19/using-isqlquery-to-load-data-with-nhibernate/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/05/19/using-isqlquery-to-load-data-with-nhibernate/#comments</comments>
		<pubDate>Tue, 19 May 2009 12:58:50 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/05/19/using-isqlquery-to-load-data-with-nhibernate/</guid>
		<description><![CDATA[
			
				
			
		
I have a project that uses both nhibernate and StoredProcedures, based on a legacy project written without nhibernate. Today I need to load a lot of data from five tables. The problem is that all these tables are managed with nhibernate, but I have no relation between them. Moreover these tables have a lot of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F19%2Fusing-isqlquery-to-load-data-with-nhibernate%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F19%2Fusing-isqlquery-to-load-data-with-nhibernate%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I have a project that uses both nhibernate and StoredProcedures, based on a legacy project written without nhibernate. Today I need to load a lot of data from five tables. The problem is that all these tables are managed with nhibernate, but I have no relation between them. Moreover these tables have a lot of objects, and I need to retrieve only 10 objects at a time with pagination, but I cannot express pagination in nhibernate, because I have condition that must be satisfied on tables that are not mapped. </p>
<p>I decided to create a new class that stores some basic data taken from two of these five tables, then add three properties to create relation with other three. The real objects that manage those three tables are not related because there is not foreign key in tables, but there are some business rules, expressed with stored procedure, that relates them all.</p>
<p>Thanks to <a target="_blank" href="https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/querysql.html">SQlQuery</a> I created a stored that accepts three parameters, it paginates record server-side with temp tables, and it is superfast. Then I begin to think how to map it into nhibernate. Moreover in client code I do not access directly the ISession, because the NHibernate layer was based on a previous query model… (that sooner or later will be dropped to permits direct access to ISession=, but for now all legacy nhibernate layer uses this custom query model, so I have no way to remove it.</p>
<p>Moreover, since I need to join tables, if I ask for 10 records, actually the stored returns higher number of records, because it returns 10 records from the base table, but after joins with other tables the number of returned records is greater than 10. I made the stored so it returns rows from all five tables, and I create all foreign key directly in the stored, now I’m able to write code like.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:c0585f8d-e962-4bef-bf61-ed8dc16732cb" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">DirectSqlQuery query </span><span style="color: #000000;">=</span><span style="color: #000000;"> DirectSqlQuery.Create(</span><span style="color: #800000;">"</span><span style="color: #800000;">fictiousEntity</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">root</span><span style="color: #800000;">"</span><span style="color: #000000;">)
    .SetInt32(</span><span style="color: #800000;">"</span><span style="color: #800000;">clieid</span><span style="color: #800000;">"</span><span style="color: #000000;">, customerId)
    .SetInt32(</span><span style="color: #800000;">"</span><span style="color: #800000;">startindex</span><span style="color: #800000;">"</span><span style="color: #000000;">, startIndex)
    .SetInt32(</span><span style="color: #800000;">"</span><span style="color: #800000;">maxresult</span><span style="color: #800000;">"</span><span style="color: #000000;">, maxResults)
    .AddJoin(</span><span style="color: #800000;">"</span><span style="color: #800000;">fetchTargets</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">root.Targets</span><span style="color: #800000;">"</span><span style="color: #000000;">)
    .AddJoin(</span><span style="color: #800000;">"</span><span style="color: #800000;">fetchAnalyzedLink</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">root.AnalyzedLink</span><span style="color: #800000;">"</span><span style="color: #000000;">)
    .AddJoin(</span><span style="color: #800000;">"</span><span style="color: #800000;">fetchExtData</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">fetchAnalyzedLink.ExtData</span><span style="color: #800000;">"</span><span style="color: #000000;">)
    .SetResultTransformer(</span><span style="color: #0000FF;">new</span><span style="color: #000000;"> DistinctResultTransformer(</span><span style="color: #800080;">0</span><span style="color: #000000;">));
var result </span><span style="color: #000000;">=</span><span style="color: #000000;"> UnitOfWorkBaseDbDao</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">fictiousEntity</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">.GetByCriteria(query);</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>entity called <strong>fictiousEntity </strong>is used only to join data from two base tables and contains relations with other three tables, then I tell to ISQlQuery that in resultset there are all the columns to rebuild other related entities with <strong>AddJoin. </strong>Finally I use a DistinctResultTransformer to take only the first element of the tuple. When you use AddJoin(), NHibernate does not return an object for each row in the resultset, but instead returns one object for each join. (see this figure)</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2009/05/image2.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="104" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2009/05/image-thumb2.png" width="700" border="0" /></a> </p>
<p>This is a snapshot of the TransformTuple of my DistinctResultTransformer object, that simply takes the object whose index was specified in constructor. So when I wrote <strong>SetResultTransformer(new DistinctResultTransformer(0))</strong> I’m asking to return only the first element, that was my fictiousEntity used to aggregate the result. </p>
<p>Since I specified to NH that all data is included in the original recordset, entities are fully hydrated without N+1 Select problem. With this simple trick I’m able to retrieve data from a stored in a really high efficient way, while maintaining full power of NHibernate, because except the fictiousEntity that is mutable=”false”, and is used only for aggregation, all related classes can be used as usual with full persistence power.</p>
<p>alk. </p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/05/19/using-isqlquery-to-load-data-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Use Xml field in SqlServer with nhibernate</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/05/14/use-xml-field-in-sqlserver-with-nhibernate/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/05/14/use-xml-field-in-sqlserver-with-nhibernate/#comments</comments>
		<pubDate>Thu, 14 May 2009 14:49:37 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/05/14/use-xml-field-in-sqlserver-with-nhibernate/</guid>
		<description><![CDATA[
			
				
			
		
Xml fields in sql server are really useful, you can use xpath or xQuery to filter and impose condition on part of the xml fragment. Today we decided to store some data in an XML field of a table, and since this table was accessed both by nhibernate and both from T-Sql code, I begin [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F14%2Fuse-xml-field-in-sqlserver-with-nhibernate%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F14%2Fuse-xml-field-in-sqlserver-with-nhibernate%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Xml fields in sql server are really useful, you can use xpath or xQuery to filter and impose condition on part of the xml fragment. Today we decided to store some data in an XML field of a table, and since this table was accessed both by nhibernate and both from T-Sql code, I begin to think on how to map this situation on NHibernate.</p>
<p>I immediately think to a usertype that is able to store data using XMLSerialization, here is the class, It took to me 10 minutes to create it, </p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:9da47401-81b1-4de3-b5eb-4d50cca258c0" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">class</span><span style="color: #000000;"> XmlFieldUserType</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">T</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> : IUserType </span><span style="color: #0000FF;">where</span><span style="color: #000000;"> T : ICloneable
{
    </span><span style="color: #0000FF;">#region</span><span style="color: #000000;"> Equals member</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">bool</span><span style="color: #000000;"> IUserType.Equals(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> x, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> y)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> (x </span><span style="color: #000000;">==</span><span style="color: #000000;"> y) </span><span style="color: #000000;">||</span><span style="color: #000000;"> ((x </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">) </span><span style="color: #000000;">&amp;&amp;</span><span style="color: #000000;"> x.Equals(y));
    }

    </span><span style="color: #0000FF;">#endregion</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">#region</span><span style="color: #000000;"> IUserType Members</span><span style="color: #000000;">

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> Assemble(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> cached, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> cached;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> DeepCopy(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value)
    {
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">) </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;

        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> ((T)value).Clone();
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> Disassemble(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> value;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> GetHashCode(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> x)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> x.GetHashCode();
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">bool</span><span style="color: #000000;"> IsMutable
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">true</span><span style="color: #000000;">; }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> NullSafeGet(System.Data.IDataReader rs, </span><span style="color: #0000FF;">string</span><span style="color: #000000;">[] names, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
    {
        Int32 index </span><span style="color: #000000;">=</span><span style="color: #000000;"> rs.GetOrdinal(names[</span><span style="color: #800080;">0</span><span style="color: #000000;">]);
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (rs.IsDBNull(index))
        {
            </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;
        }

        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> XmlHelper.FromXml</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">T</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">((String)rs[index]);
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> NullSafeSet(System.Data.IDbCommand cmd, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value, </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> index)
    {
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;"> </span><span style="color: #000000;">||</span><span style="color: #000000;"> value </span><span style="color: #000000;">==</span><span style="color: #000000;"> DBNull.Value)
        {
            NHibernateUtil.String.NullSafeSet(cmd, </span><span style="color: #0000FF;">null</span><span style="color: #000000;">, index);
        }
        </span><span style="color: #0000FF;">else</span><span style="color: #000000;">
        {

            NHibernateUtil.String.Set(cmd, XmlHelper.ToXml(value), index);
        }

    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> Replace(</span><span style="color: #0000FF;">object</span><span style="color: #000000;"> original, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> target, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> original;
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> Type ReturnedType
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(Uri); }
    }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> NHibernate.SqlTypes.SqlType[] SqlTypes
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> SqlType[] { NHibernateUtil.String.SqlType }; }
    }

    </span><span style="color: #0000FF;">#endregion</span><span style="color: #000000;">
}</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>I use a simple XmlHelper class that serialize to and from XML string, and thanks to this class writing the usertype is a breeze, since Xml serialization needs to know the type of the class you operate with, this user type is generic, here is a typical use.</p>
</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:4a7ce7fb-8552-44c0-b72c-b090e4251eb9" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">property </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="DetailData"</span><span style="color: #FF0000;">
          type</span><span style="color: #0000FF;">="NHibernateExt.XmlFieldUserType`1[[MyProject.DetailData, MyProject]], NHibernateExt"</span><span style="color: #FF0000;">
           column</span><span style="color: #0000FF;">="link_detail"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This is the standard way to specify a class with generics. Now when I save the class here is the SQL generated.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:3ea5122f-3bc2-42bb-b097-08009dff5a80" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">INSERT</span><span style="color: #000000;"> </span><span style="color: #0000FF;">INTO</span><span style="color: #000000;"> MyTable (link_url, link_sha256, link_target_id, link_details) </span><span style="color: #0000FF;">VALUES</span><span style="color: #000000;"> (</span><span style="color: #008000;">@p0</span><span style="color: #000000;">, </span><span style="color: #008000;">@p1</span><span style="color: #000000;">, </span><span style="color: #008000;">@p2</span><span style="color: #000000;">, </span><span style="color: #008000;">@p3</span><span style="color: #000000;">); </span><span style="color: #0000FF;">select</span><span style="color: #000000;"> </span><span style="color: #FF00FF;">SCOPE_IDENTITY</span><span style="color: #000000;">(); </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">http://www.nablasoft.com</span><span style="color: #FF0000;">'</span><span style="color: #000000;">, </span><span style="color: #008000;">@p1</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">BD827105DDFBEE299C04B461A322FFC21A1CC919D2FDB5A3E1CCC78B3D3BF93F</span><span style="color: #FF0000;">'</span><span style="color: #000000;">, </span><span style="color: #008000;">@p2</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">0</span><span style="color: #FF0000;">'</span><span style="color: #000000;">, </span><span style="color: #008000;">@p3</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">&lt;DetailData
  UserName="Alkampfer"
  Title="Nablasoft HomePAge"
  Description="Not avaliable"
  Category="MySite"&gt;
  &lt;Tags&gt;one&lt;/Tags&gt;
  &lt;Tags&gt;two&lt;/Tags&gt;
  &lt;Tags&gt;three&lt;/Tags&gt;
&lt;/DetailData&gt;</span><span style="color: #FF0000;">'</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>Now I can simply use the DetailData property of the class, working with a full object, but when the object gets saved, the DetailData property is simply serialized into an xml stream.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/nhibernate" rel="tag">nhibernate</a> <a target="_blank" href="http://technorati.com/tag/Xml Serialization" rel="tag">Xml Serialization</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/05/14/use-xml-field-in-sqlserver-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Maintain integrity in NHibernate bidirectional association</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/05/05/maintain-integrity-in-nhibernate-bidirectional-association/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/05/05/maintain-integrity-in-nhibernate-bidirectional-association/#comments</comments>
		<pubDate>Tue, 05 May 2009 12:38:01 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[Software Architecture]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/05/05/maintain-integrity-in-nhibernate-bidirectional-association/</guid>
		<description><![CDATA[
			
				
			
		
Using Bidirectional Associations in nhibernate can be tricky, the problem is that you need to manage associations for both ends. This is really important: suppose you have a class called Parent with a collection of childs called Childs, and a child class with a property called Parent; if you expose these two property to the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F05%2Fmaintain-integrity-in-nhibernate-bidirectional-association%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F05%2F05%2Fmaintain-integrity-in-nhibernate-bidirectional-association%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Using Bidirectional Associations in nhibernate can be tricky, the problem is that you need to manage associations for both ends. This is really important: suppose you have a class called Parent with a collection of childs called Childs, and a child class with a property called Parent; if you expose these two property to the user, you can write this</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:ce8e548f-5626-435f-b7f5-086a685a2387" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">Parent John </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Parent();
Parent Mark </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Parent();
Child Bart </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Child();

John.Childs.Add(Bart);
Bart.Parent </span><span style="color: #000000;">=</span><span style="color: #000000;"> Mark;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>With such a code Bart’s parent is Mark, but Bart is in John Child collection, this is WRONG. To avoid this problem you should maintain integrity in the domain model, managing the consistency of the relationship. Suppose you have the same situation with two objects, a StockKeepingUnit and a StockContainer, here it is the code for StockKeepingUnit</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8d123a49-dee1-4116-8d09-d3a93b239f8d" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;"> </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">virtual</span><span style="color: #000000;"> StockContainer Parent
 {
    </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> parent;}
    </span><span style="color: #0000FF;">set</span><span style="color: #000000;">
    {
       </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (parent </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">)
          parent._Content.Remove(</span><span style="color: #0000FF;">this</span><span style="color: #000000;">);

       parent </span><span style="color: #000000;">=</span><span style="color: #000000;"> value;

       </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">)
          value._Content.Add(</span><span style="color: #0000FF;">this</span><span style="color: #000000;">);
    }
 }

 </span><span style="color: #0000FF;">private</span><span style="color: #000000;"> StockContainer parent;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>As you can see in the setter part I first check if this object has a parent, if yes we need to remove it from the _Content collection of the parent object (because actually I’m detatching from it); then if the value is different from null it means that we have a new parent, so the object assign itself to the _Content collection of the new father to mantain integrity. Surely you now need to map this property in directly on the field to avoid problem</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:49913753-53e5-4175-80df-24cd1f74c89e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">many-to-one </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="parent"</span><span style="color: #FF0000;"> access</span><span style="color: #0000FF;">="field"</span><span style="color: #FF0000;"> class</span><span style="color: #0000FF;">="StockKeepingUnit"</span><span style="color: #FF0000;"> ... </span><span style="color: #0000FF;">/&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>It is of fundamental importance that you map to the field, this because when nhibernate rebuild the object from database, you must avoiding calling the Set part of the Parent property, because the coherence of the objects are guaranteed by nhibernate itself. Now here is how I implemented the Collection part on the SockContainer class</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:5d6c4df4-489d-440b-9bfb-9f4c63f1b37d" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;"> </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">virtual</span><span style="color: #000000;"> IEnumerable </span><span style="color: #000000;">&lt;</span><span style="color: #000000;">StockKeepingUnit</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> Content
 {
    </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> _Content;}
 }

 </span><span style="color: #0000FF;">internal</span><span style="color: #000000;"> </span><span style="color: #0000FF;">virtual</span><span style="color: #000000;"> ISet</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">StockKeepingUnit</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> _Content
 {
    </span><span style="color: #0000FF;">get</span><span style="color: #000000;">
    {
       </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> content </span><span style="color: #000000;">??</span><span style="color: #000000;"> (content </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> HashedSet </span><span style="color: #000000;">&lt;</span><span style="color: #000000;">StockKeepingUnit</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">());
    }
    </span><span style="color: #0000FF;">set</span><span style="color: #000000;">
    {
        content </span><span style="color: #000000;">=</span><span style="color: #000000;"> value;
    }
 }
 </span><span style="color: #0000FF;">private</span><span style="color: #000000;"> ISet</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">StockKeepingUnit</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> content;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>First of all the ISet class is a private field, and the accessor property, called _Content, is internal because it must be accessed by the StockKeepingUnit code seen before, but must not be accessed from external code. The property is implemented with lazy creation, if the content property is null, I simply create an HashedSet, this is useful when you first create the object, because initially this property is null. When nhibernate rebuild the object from database data, the content private field is set by nhibernate, so I can avoid unnecessary creation of HashedSet. With this kind of structure you can map nhibernate to the _Content property and not to the field.</p>
<p>Now a question arise: How can the user of this class access the Collection of StockKeepingUnit if the _Content property is private? The answer is in the property Content that is of type <em>IEnumerable&lt;StockKeepingUnit&gt;.</em> With Ienumerable I permit the user to use fully LINQ syntax to access collection of StockKeepingUnit, this is enough for most scenarios because with LINQ you can iterate, filter, select and doing whatever you want to access all StockKeepingUnit contained in a stockContainer.</p>
<p>Alk</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Domain Model" rel="tag">Domain Model</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/05/05/maintain-integrity-in-nhibernate-bidirectional-association/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>NHibernate ICriteria and composite-id with key-many-to-one</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/04/29/nhibernate-icriteria-and-composite-id-with-key-many-to-one/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/04/29/nhibernate-icriteria-and-composite-id-with-key-many-to-one/#comments</comments>
		<pubDate>Wed, 29 Apr 2009 16:29:19 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/04/29/nhibernate-icriteria-and-composite-id-with-key-many-to-one/</guid>
		<description><![CDATA[
			
				
			
		
Suppose you have a legacy database, and an entity called ViewOfBaseData that have this id.

 &#60;composite-id class="ViewOfBaseDataId" name="Id"  &#62;
    &#60;key-many-to-one class="LinkResult" name="Link" column="AnalysisId" lazy="proxy" /&#62;
    &#60;key-property name="AnalysisDate" type="System.DateTime" column="AnalysisDate" /&#62;
 &#60;/composite-id&#62;

Resulting SQL query is a simple join between the two tables, but now suppose you cannot use HQL [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F04%2F29%2Fnhibernate-icriteria-and-composite-id-with-key-many-to-one%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F04%2F29%2Fnhibernate-icriteria-and-composite-id-with-key-many-to-one%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Suppose you have a legacy database, and an entity called ViewOfBaseData that have this id.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:53034c24-6b21-4dda-a052-d6bad6b697e3" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;"> </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">composite-id </span><span style="color: #FF0000;">class</span><span style="color: #0000FF;">="ViewOfBaseDataId"</span><span style="color: #FF0000;"> name</span><span style="color: #0000FF;">="Id"</span><span style="color: #FF0000;">  </span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">key-many-to-one </span><span style="color: #FF0000;">class</span><span style="color: #0000FF;">="LinkResult"</span><span style="color: #FF0000;"> name</span><span style="color: #0000FF;">="Link"</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">="AnalysisId"</span><span style="color: #FF0000;"> lazy</span><span style="color: #0000FF;">="proxy"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">key-property </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">="AnalysisDate"</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">="System.DateTime"</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">="AnalysisDate"</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
 </span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">composite-id</span><span style="color: #0000FF;">&gt;</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Now suppose you need to retrieve all object ViewOfBaseData linked to a LinkResult object with a property KeyList equal to a certain value. In HQL is really simple</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:1c7359f9-08d5-4658-b2c7-dc92bc0746ce" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">select</span><span style="color: #000000;"> v </span><span style="color: #0000FF;">from</span><span style="color: #000000;"> ViewOfBaseData v </span><span style="color: #0000FF;">where</span><span style="color: #000000;"> v.Id.Link.KeyList </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">blabla</span><span style="color: #FF0000;">'</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Resulting SQL query is a simple join between the two tables, but now suppose you cannot use HQL and instead you are forced to use ICriteria, you can try this one.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:ebd4ba5e-8bb2-49c7-88e3-bf4618d49fb8" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">ICriteria c </span><span style="color: #000000;">=</span><span style="color: #000000;"> uow.TheSession.CreateCriteria(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(ViewOfBaseData ))
 .CreateCriteria(</span><span style="color: #800000;">"</span><span style="color: #800000;">Id</span><span style="color: #800000;">"</span><span style="color: #000000;">).CreateCriteria(</span><span style="color: #800000;">"</span><span style="color: #800000;">Link</span><span style="color: #800000;">"</span><span style="color: #000000;">)
               .Add(Expression.Eq(</span><span style="color: #800000;">"</span><span style="color: #800000;">KeyList</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">blabla</span><span style="color: #800000;">"</span><span style="color: #000000;">));</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>But this failed with the error: <strong><em>no such column: linkresult2_.keyList </em></strong>, if you look at the SQL query issued to the database, you can verify that the query does not contain the join with the table for LinkResult entity. If you change the constant “blabla” with the integer 10 you will obtain the error <strong><em>Type mismatch in NHibernate.Criterion.SimpleExpression: KeyList expected type System.String, actual type System.Int32 </em></strong>thus confirming me that the path is specified correctly.</p>
<p>If you examine the inner metadata of the session you can find that the composite id ViewOfBaseDataId is a ComponentType and probably internally, when the engine that build sql query verify that Id property of ViewOfBaseData is a componentType determines that each column is contained in the base table. I do not know if it is a bug of nhibernate or if there is another way to specify the criteria, but if you absolutely need not to use HQL you can use DetatchedCriteria</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:2564525b-ad0c-4a5c-966a-19594d381a09" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #000000;">ICriteria c </span><span style="color: #000000;">=</span><span style="color: #000000;"> uow.TheSession.CreateCriteria(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(ViewOfBaseeData), </span><span style="color: #800000;">"</span><span style="color: #800000;">root</span><span style="color: #800000;">"</span><span style="color: #000000;">);

DetachedCriteria dc </span><span style="color: #000000;">=</span><span style="color: #000000;"> DetachedCriteria.For(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;"> (LinkResult))
   .Add(Expression.Eq(</span><span style="color: #800000;">"</span><span style="color: #800000;">KeyList</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #800000;">"</span><span style="color: #800000;">blabla</span><span style="color: #800000;">"</span><span style="color: #000000;">))
   .SetProjection(Projections.Property(</span><span style="color: #800000;">"</span><span style="color: #800000;">Id</span><span style="color: #800000;">"</span><span style="color: #000000;">))
   .Add(Property.ForName(</span><span style="color: #800000;">"</span><span style="color: #800000;">Id</span><span style="color: #800000;">"</span><span style="color: #000000;">).EqProperty(</span><span style="color: #800000;">"</span><span style="color: #800000;">root.Id.Link.Id</span><span style="color: #800000;">"</span><span style="color: #000000;">));

c.Add(Subqueries.Exists(dc));
c.List();</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This generates the following query</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:e59b0ba9-9350-4283-9203-bc9b195b6250" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;white-space:-moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word;overflow: auto;"><span style="color: #0000FF;">SELECT</span><span style="color: #000000;"> this_.AnalysisId </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> AnalysisId98_0_, this_.AnalysisDate </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> Analysis2_98_0_, ...
</span><span style="color: #0000FF;">FROM</span><span style="color: #000000;"> ViewOfBaseData this_ </span><span style="color: #0000FF;">WHERE</span><span style="color: #000000;"> </span><span style="color: #808080;">exists</span><span style="color: #000000;"> (</span><span style="color: #0000FF;">SELECT</span><span style="color: #000000;"> this_0_.Id </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> y0_ </span><span style="color: #0000FF;">FROM</span><span style="color: #000000;"> LinkResult this_0_
</span><span style="color: #0000FF;">WHERE</span><span style="color: #000000;"> this_0_.keyList </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">and</span><span style="color: #000000;"> this_0_.Id </span><span style="color: #808080;">=</span><span style="color: #000000;"> this_.AnalysisId); </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">blabla</span><span style="color: #FF0000;">'</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>From the point of view of performance, probably this query is worst than a direct join, but it works <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/ICriteria" rel="tag">ICriteria</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/04/29/nhibernate-icriteria-and-composite-id-with-key-many-to-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate &#8220;null identifier&#8221; error</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/04/02/nhibernate-null-identifier-error/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/04/02/nhibernate-null-identifier-error/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 15:48:29 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/04/02/nhibernate-null-identifier-error/</guid>
		<description><![CDATA[
			
				
			
		
Today I received a strange “null identifier” error when saving an object to db with nhibernate. Immediatly I realize that this error is caused by a Trigger INSTEAD OF INSERT, that apperars to broke the SCOPE_IDENTITY() function. Since NHibernate uses SCOPE_IDENTITY() to retrieve the id of the generated object, when you use INSTEAD OF INSERT [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F04%2F02%2Fnhibernate-null-identifier-error%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F04%2F02%2Fnhibernate-null-identifier-error%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I received a strange “null identifier” error when saving an object to db with nhibernate. Immediatly I realize that this error is caused by a Trigger INSTEAD OF INSERT, that apperars to broke the SCOPE_IDENTITY() function. Since NHibernate uses SCOPE_IDENTITY() to retrieve the id of the generated object, when you use INSTEAD OF INSERT Trigger the SCOPE_IDENTITY() returns null, and nhibernate could not know the value of the inserted record.</p>
<p>I first tried to specify with &lt;sql.insert&gt; the query to use, to make use of @@identity, but it does not work. After some time I discovered a <a target="_blank" href="http://nhjira.koah.net/browse/NH-727">issue</a> that was fixed only in the trunk. My only solution was removing the trigger (fortunately I can do it) because nhibernate does not permits me to use &lt;sql-insert&gt; with entities that use identity to generate ids. </p>
<p>Another good reason not to use identity with nhibernate, but my project is a legacy one where a lot of operations are massive ones performed by stored procedure.</p>
<p>alk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/04/02/nhibernate-null-identifier-error/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Querying NHibernate user type with HQL or criteria</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/03/31/querying-nhibernate-user-type-with-hql-or-criteria/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/03/31/querying-nhibernate-user-type-with-hql-or-criteria/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 11:08:26 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/03/31/querying-nhibernate-user-type-with-hql-or-criteria/</guid>
		<description><![CDATA[
			
				
			
		
Some time ago I posted a link about a user type to store list of strings in a single database field. In a project of mine I have another usertype very similar, that stores list of integers into a single string database field in a # separated value, like #1#8#23# (note that the character # [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F03%2F31%2Fquerying-nhibernate-user-type-with-hql-or-criteria%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F03%2F31%2Fquerying-nhibernate-user-type-with-hql-or-criteria%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Some time ago I posted a link about a <a href="http://www.codewrecks.com/blog/index.php/2008/10/21/some-details-on-older-post-about-usertype/">user type</a> to store list of strings in a single database field. In a project of mine I have another usertype very similar, that stores list of integers into a single string database field in a # separated value, like #1#8#23# (note that the character # appears at the begin and the end of the string). Now Suppose you need to made some query on it like “select all Domains where activeCustomerList is not empty and contains at least one id:</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:ab759178-1afb-4697-afeb-6c564cf647bb" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #000000;">IList</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Domain</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> res </span><span style="color: #000000;">=</span><span style="color: #000000;"> session
.CreateQuery(</span><span style="color: #800000;">"</span><span style="color: #800000;">from Domain D where D.ActiveCustomerList != \"\"</span><span style="color: #800000;">"</span><span style="color: #000000;">)
.List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Domain</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>In HQL the criteria needs to be expressed in string format, so I simply check for domain where the ActiveCustomerList is not an empty string, if you need to use Criteria API the situation is little different.</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:72a1554f-c099-4a80-83bc-66aad92e4fd6" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #000000;">IList</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Domain</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> res </span><span style="color: #000000;">=</span><span style="color: #000000;"> session.CreateCriteria(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(Domain))
   .Add(Restrictions.Not(
      Restrictions.Eq(</span><span style="color: #800000;">"</span><span style="color: #800000;">ActiveCustomerList</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Int32</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">())))
      .List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Domain</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>With criteria API you need to specify that you want the field not to be equal to a real empty string of IntegerList. This happens because the Criteria API works on the model on the entity, so if the property is of type List&lt;Int32&gt; for an equality operator it need to compare it with the result of applying the UserType to the Empty Integer List. In HQL you can also express some interesting query, as for example “All domains that contains and active customer with ID 9”</p>
<div class="wlWriterEditableSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:b3f6e605-1b7e-406a-803e-31dc986a5871" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:#FFFFFF;overflow: auto;"><span style="color: #000000;">IList</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Domain</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> res </span><span style="color: #000000;">=</span><span style="color: #000000;"> session
.CreateQuery(</span><span style="color: #800000;">"</span><span style="color: #800000;">from Domain D where D.ActiveCustomerList like '%#9#%'</span><span style="color: #800000;">"</span><span style="color: #000000;">)
.List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Domain</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This is&#160; a simple like operator, the only problem is that the % at the begin and the end of the like will makes any index ineffective, so the query can be slow for a high number of record. Doing this with Criteria API is probably impossible because the Like Restriction accepts only strings, and we have no way to pass a sample object. I’ll keep investigating but for now I’m using the HQL version</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/03/31/querying-nhibernate-user-type-with-hql-or-criteria/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>NHibernate and TooManyRowsAffectedException</title>
		<link>http://www.codewrecks.com/blog/index.php/2009/03/25/nhibernate-and-toomanyrowsaffectedexception/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2009/03/25/nhibernate-and-toomanyrowsaffectedexception/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 08:42:51 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2009/03/25/nhibernate-and-toomanyrowsaffectedexception/</guid>
		<description><![CDATA[
			
				
			
		
Today I received a log of an error in a windows service that runs some scheduled actions, the error was TooManyRowsAffectedException and it is thrown by nhibernate when a session is flushed. The exact message said Unexpected row count: 2; expected: 1 , after a little moment of confusion I immediately realize that the problem [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F03%2F25%2Fnhibernate-and-toomanyrowsaffectedexception%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2009%2F03%2F25%2Fnhibernate-and-toomanyrowsaffectedexception%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I received a log of an error in a windows service that runs some scheduled actions, the error was <strong><em>TooManyRowsAffectedException</em></strong> and it is thrown by nhibernate when a session is flushed. The exact message said <em><strong>Unexpected row count: 2; expected: 1</strong></em> , after a little moment of confusion I immediately realize that the problem is due to a trigger.</p>
<p>I modified a table to keep a log of all modifications of every row, and I did this with a simple trigger that, for each update, saves the last value of each modified row in an history table. Since the trigger runs in the same context of the update operation, when you update a row, the trigger fired, insert a row in history table and the whole update operation returns 2 as the number of affected rows. NHibernate check the affected row count to verify that the row was really updated by the UPDATE statement, when he saw a rowcount of 2 he throws exception because something was wrong since it issue an update of a single row.</p>
<p>The obvious solution is to issue a <strong><em>SET NOCOUNT ON</em> </strong>at the beginning of the trigger and a <em><strong>SET NOCOUNT OFF</strong></em> at the end. This is a good practice, because in this way the trigger does not affect the number of affected rows. After all the trigger should be completely transparent to the application, and this is the best way to achieve this result.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Triggers" rel="tag">Triggers</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2009/03/25/nhibernate-and-toomanyrowsaffectedexception/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Improving the WCF logger</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 07:35:12 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[.NET framework]]></category>
		<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/</guid>
		<description><![CDATA[
			
				
			
		
One of the first improvement to the WCF logger is the ability to choose the list of logger to monitor during registration. A real application can generate tons of logs, suppose you are interested only in looking at the NHibernate generated query. The solution is to add another registration method and internally use an object [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F11%2F06%2Fimproving-the-wcf-logger%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F11%2F06%2Fimproving-the-wcf-logger%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>One of the first improvement to the WCF logger is the ability to choose the list of logger to monitor during registration. A real application can generate tons of logs, suppose you are interested only in looking at the NHibernate generated query. The solution is to add another registration method and internally use an object that keeps care of the registration and senting log progress. Here is the new interface</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:9fcbc7e6-42c0-4649-88d0-47a66f1b13ce" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">[ServiceContract(SessionMode </span><span style="color: #000000;">=</span><span style="color: #000000;"> SessionMode.Required, CallbackContract </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(IL4NClient))]
</span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">interface</span><span style="color: #000000;"> IL4NServer
{
    [OperationContract]
    Boolean Register();

    [OperationContract]
    Boolean RegisterForSpecificLogger(</span><span style="color: #0000FF;">params</span><span style="color: #000000;"> String[] loggerNameList);
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>Now I can choose the name of the logger I’m interested to filter messages log.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2008/11/image2.png"><img title="image" style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="562" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2008/11/image-thumb2.png" width="877" border="0" /></a></p>
</p>
</p>
<p>But this is not the only improvement I need. Quite often it happens that developer X called you telling “When I press the button Y the application responds after 20 seconds”, then you see with the SQL profiler that tons of query gets issued to the database. For a layered and complex application it can be difficult to understand where that queries are issued in the code, so I need a way to get a valid stack trace from the logger. To accomplish this task I modified the LogMessage object </p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:e58ba77e-50be-4922-9ba3-34b53c0b3df2" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">[DataContract]
</span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">class</span><span style="color: #000000;"> LogMessage
{
    [DataMember]
    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> String Message { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }

    [DataMember]
    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">StackStep</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">  StackSteps { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> LogMessage()
    {
        StackSteps </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">StackStep</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();
        StackTrace trace </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> StackTrace(</span><span style="color: #0000FF;">true</span><span style="color: #000000;">);
        var interestingFrames </span><span style="color: #000000;">=</span><span style="color: #000000;"> from StackFrame frame </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> trace.GetFrames()
                                </span><span style="color: #0000FF;">where</span><span style="color: #000000;"> frame.GetMethod().DeclaringType.Assembly.GetName().Name </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">LiveLogger4Log4Net</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">
                                      </span><span style="color: #000000;">&amp;&amp;</span><span style="color: #000000;"> frame.GetMethod().DeclaringType.Assembly.GetName().Name </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">log4net</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">
                                                </span><span style="color: #000000;">&amp;&amp;</span><span style="color: #000000;"> frame.GetFileLineNumber() </span><span style="color: #000000;">!=</span><span style="color: #000000;"> </span><span style="color: #800080;">0</span><span style="color: #000000;">
                                select </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> StackStep()
                                           {
                                               SourceFile </span><span style="color: #000000;">=</span><span style="color: #000000;"> frame.GetFileName(),
                                               LineNumber </span><span style="color: #000000;">=</span><span style="color: #000000;"> frame.GetFileLineNumber()
                                           };
        StackSteps.AddRange(interestingFrames);
    }
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
</p>
<p>First I have inserted in the message a list of stacksteps, a class that contains filename and line number, in the constructor of the message I use the StackTrace .NET class to obtain the stack trace, then I do a linq query to remove all the steps that have no source file or are part of my logging system. The result is really interesting.</p>
<p><a href="http://www.codewrecks.com/blog/wp-content/uploads/2008/11/image3.png"><img title="image" style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="220" alt="image" src="http://www.codewrecks.com/blog/wp-content/uploads/2008/11/image-thumb3.png" width="982" border="0" /></a> </p>
<p>Not only I’m able to intercept NHibernate generated SQL, but I have a full stack trace that tells me where the query is generated, now the next step is to build a better client interface to present the result in a more usable and readable form.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/log4net" rel="tag">log4net</a> <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/" rel="tag"></a></p>
<div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"><script type="text/javascript">var dzone_url = 'http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/';</script><script type="text/javascript">var dzone_title = 'Improving the WCF logger';</script><script type="text/javascript">var dzone_blurb = 'Improving the WCF logger';</script><script type="text/javascript">var dzone_style = '2';</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </div>
<div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"><a target="_blank" href="http://www.dotnetkicks.com/kick/?url=http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/&amp;bgcolor=0080C0&amp;fgcolor=FFFFFF&amp;border=000000&amp;cbgcolor=D4E1ED&amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"></a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/11/06/improving-the-wcf-logger/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inspecting NHibernate Metadata</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/08/12/inspecting-nhibernate-metadata/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/08/12/inspecting-nhibernate-metadata/#comments</comments>
		<pubDate>Tue, 12 Aug 2008 11:04:45 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/08/12/inspecting-nhibernate-metadata/</guid>
		<description><![CDATA[
			
				
			
		
I have a little project based on NSK, it uses a query model to abstract the caller from nhibernate. Despite the reason for having or not a Query Model, I expanded the base translator to translate my Query object into a NHIbernate ICriteria.
To make this translation you need to create alias, if I you create [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F08%2F12%2Finspecting-nhibernate-metadata%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F08%2F12%2Finspecting-nhibernate-metadata%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I have a little project based on <a target="_blank" href="http://www.codeplex.com/NSK">NSK</a>, it uses a query model to abstract the caller from nhibernate. Despite the reason for having or not a Query Model, I expanded the base translator to translate my Query object into a NHIbernate ICriteria.</p>
<p>To make this translation you need to create alias, if I you create a query for the order object and setup a constraint for Customer.Name, the ICriteria tells you that the Order object does not have a property called Customer.Name. This can be easily accomplished using Alias, but only if the object is mapped as an entity and not as a component.</p>
<p>If the customer has an Address of type Address mapped as a component and you create a constraint for the property <em>Customer.MainAddress.Number, </em>we need to create only an alias for Customer (because is an entity). This means that my translator has to distinguish between entities and components. The solution to these kind of problems can be solved inspecting metadata mapping for nhibernate.</p>
<p>I created a class that handle alias creation</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:61332a94-1260-47e0-91af-61eaf25efdc9" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; width: 803px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">CriteriaAliasTranslator cat </span><span style="color: #000000;">=</span><span style="color: #000000;">
</span><span style="color: #0000FF;">new</span><span style="color: #000000;"> CriteriaAliasTranslator(
_session.SessionFactory.GetAllClassMetadata(), _rootType);</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This translator needs only the type of the root object, and a dictionary of all types metadata, obtained from the method <em>GetAllClassMetadata()</em> from the SessionFactory object.</p>
<p>Then for each dotted constraint found in the query object, I pass it to this alias translator</p>
</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:15ab69f2-29ab-429d-a013-6ed1660adb6c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> String AddAlias(String fullpath)
{
    String[] path </span><span style="color: #000000;">=</span><span style="color: #000000;"> fullpath.Split(</span><span style="color: #800000;">'</span><span style="color: #800000;">.</span><span style="color: #800000;">'</span><span style="color: #000000;">);
    String CurrentAliasPath </span><span style="color: #000000;">=</span><span style="color: #000000;"> path[</span><span style="color: #800080;">0</span><span style="color: #000000;">];
    String ReturnValue </span><span style="color: #000000;">=</span><span style="color: #000000;"> path[</span><span style="color: #800080;">0</span><span style="color: #000000;">];
    Type currentType </span><span style="color: #000000;">=</span><span style="color: #000000;"> baseType;

    </span><span style="color: #0000FF;">for</span><span style="color: #000000;"> (Int32 I </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800080;">0</span><span style="color: #000000;">; I </span><span style="color: #000000;">&lt;</span><span style="color: #000000;"> path.Length </span><span style="color: #000000;">-</span><span style="color: #000000;"> </span><span style="color: #800080;">1</span><span style="color: #000000;">; </span><span style="color: #000000;">++</span><span style="color: #000000;">I)
    {
        IEntityPersister mapping </span><span style="color: #000000;">=</span><span style="color: #000000;"> (IEntityPersister) mappingMetadata[currentType];
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (mapping.GetPropertyType(path[I]) </span><span style="color: #0000FF;">is</span><span style="color: #000000;"> ComponentType)
        {
            </span><span style="color: #0000FF;">for</span><span style="color: #000000;"> (Int32 innerI </span><span style="color: #000000;">=</span><span style="color: #000000;"> I</span><span style="color: #000000;">+</span><span style="color: #800080;">1</span><span style="color: #000000;">; innerI </span><span style="color: #000000;">&lt;</span><span style="color: #000000;"> path.Length; </span><span style="color: #000000;">++</span><span style="color: #000000;">innerI)
                ReturnValue </span><span style="color: #000000;">+=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">.</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> path[innerI];
            </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> ReturnValue;
        }

        ...</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>I split the string with &#8220;.&#8221; character, then cycles through all the part of the property, and for each property I first check from the metadata if this is a component or not. If is a component than I can return from the function, because I do not need to create alias for components. The IEntityPersister interface stores all information for a type, then with the <em>GetPropertyType</em> you can get the NHibernate type of the property; to verify if the property is a component you can check with the is operator against the ComponentType.</p>
<p>If the component is an entity, then I go through the standard path, and store the aliases into a dictionary. When all the properties of the query gets translated I call the method <em>CreateAlias()</em> of the CriteriaAliasTranslator, that cycles through all values from the alias dictionary, and call create alias on the real ICriteria object.</p>
<p>A lot of thanks to <a target="_blank" href="http://www.codemetropolis.com/">Marco</a> that originally told me this problem. In this little project I never used query model with components, so I never hit it. Marco created another querymodel, and when we made some confrontation he told me &#8220;Hey, you have this bug&#8221; <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> , thanks again.</p>
<p>alk.</p>
</p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:4e080a20-9b2f-4378-ad1a-87019fbe9314" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><!--dotnetkickit--></div>
</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Mapping Metadata" rel="tag">Mapping Metadata</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/08/12/inspecting-nhibernate-metadata/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate and deleting a group of objects</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/06/19/nhibernate-and-deleting-a-group-of-objects/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/06/19/nhibernate-and-deleting-a-group-of-objects/#comments</comments>
		<pubDate>Thu, 19 Jun 2008 14:45:47 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/06/19/nhibernate-and-deleting-a-group-of-objects/</guid>
		<description><![CDATA[
			
				
			
		
If you do not mind to issue a delete for each object, you can delete multiple objects using an overload version of the ISession.Delete() Method, here is an example.



uow.Session.Delete(&#34;select A from ActionSpawned A where A.ParentAction = :act&#34;,
 ParentAction, NHibernateUtil.Entity(typeof(Action)));



With this query you can issue a very efficient DELETE instruction, but remember that you have to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F06%2F19%2Fnhibernate-and-deleting-a-group-of-objects%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F06%2F19%2Fnhibernate-and-deleting-a-group-of-objects%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>If you do not mind to issue a delete for each object, you can delete multiple objects using an overload version of the ISession.Delete() Method, here is an example.</p>
<p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:dcb05d35-586b-4198-813d-d77e04d42289" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">uow.Session.Delete(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">select A from ActionSpawned A where A.ParentAction = :act</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">,
 ParentAction, NHibernateUtil.Entity(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(Action)));</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>The code is quite concise, you specify the query to select a series of object, and pass it to the Delete method of the ISession, along with the parameters of the query. The result is that NHibernate executes the query, loads all objects and deletes each one. </p>
<p>If you have to delete a really great amount of objects, you can resort to use direct SQL to obtain greater performance, since all objects are deleted in a single roundtrip</p>
<p><div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:2b9b93f6-a575-424e-b297-de23987e5849" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">Object result </span><span style="color: #000000;">=</span><span style="color: #000000;"> theSession.CreateSQLQuery(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">DELETE from SchedulerAction where acti_parent = :act</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">)
    .AddScalar(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">count</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, NHibernateUtil.Int32)
    .SetParameter(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">act</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, act1.Id)
    .UniqueResult();</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>With this query you can issue a very efficient DELETE instruction, but remember that you have to specify the real table and columns names, so you lose the advantage to abstract the model from the database. The above query returns null, because the delete instruction does not select any data, if you want to know the number of deleted  row you can use</p>
<p><div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:a252299e-24e3-493b-b5da-3504056523fc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">Object result </span><span style="color: #000000;">=</span><span style="color: #000000;"> theSession.CreateSQLQuery(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">DELETE from SchedulerAction where acti_parent = :act ; select @@ROWCOUNT count;</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">)
    .AddScalar(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">count</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, NHibernateUtil.Int32)
    .SetParameter(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">act</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, act1.Id)
    .UniqueResult();</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>alk.</p>
<p><div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:793cdc51-6ed0-463c-a385-1950a2efe7f8" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><!--dotnetkickit--></div>
</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate, Bulk Operation" rel="tag">NHibernate, Bulk Operation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/06/19/nhibernate-and-deleting-a-group-of-objects/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Second IUserType of the day &#8211; Store a list of string in database with NHIbernate.</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/05/30/second-iusertype-of-the-day-store-a-list-of-string-in-database-with-nhibernate/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/05/30/second-iusertype-of-the-day-store-a-list-of-string-in-database-with-nhibernate/#comments</comments>
		<pubDate>Fri, 30 May 2008 14:54:46 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/05/30/second-iusertype-of-the-day-store-a-list-of-string-in-database-with-nhibernate/</guid>
		<description><![CDATA[
			
				
			
		
I have an object that has 4 properties of IList&#60;String&#62; type. You can natively map these properties in a separate table with this simple mapping



&#60;bag name=&#34;keys&#34; access=&#34;field&#34; cascade=&#34;all-delete-orphan&#34; table=&#34;Keys&#34; fetch=&#34;join&#34;&#62;
    &#60;key column=&#34;deps_id&#34; /&#62;
    &#60;element column=&#34;deps_key&#34; type=&#34;String&#34; /&#62;
&#60;/bag&#62;


If the data in database is null, or is an empty string I [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F30%2Fsecond-iusertype-of-the-day-store-a-list-of-string-in-database-with-nhibernate%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F30%2Fsecond-iusertype-of-the-day-store-a-list-of-string-in-database-with-nhibernate%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I have an object that has 4 properties of IList&lt;String&gt; type. You can natively map these properties in a separate table with this simple mapping</p>
<p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:73882fda-55d9-49d7-8c8e-179e45dc2b8f" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">bag </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">=&quot;keys&quot;</span><span style="color: #FF0000;"> access</span><span style="color: #0000FF;">=&quot;field&quot;</span><span style="color: #FF0000;"> cascade</span><span style="color: #0000FF;">=&quot;all-delete-orphan&quot;</span><span style="color: #FF0000;"> table</span><span style="color: #0000FF;">=&quot;Keys&quot;</span><span style="color: #FF0000;"> fetch</span><span style="color: #0000FF;">=&quot;join&quot;</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">key </span><span style="color: #FF0000;">column</span><span style="color: #0000FF;">=&quot;deps_id&quot;</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">element </span><span style="color: #FF0000;">column</span><span style="color: #0000FF;">=&quot;deps_key&quot;</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">=&quot;String&quot;</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">bag</span><span style="color: #0000FF;">&gt;</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>Ok, this is a simple mapping that store all the keys into another table with two columns, one is the foreign key to the main object, the other is a string column to store the data. But a similar mapping does not satisfy me, because I need to create 4 more table to store string coming from my 4 IList&lt;String&gt; properties&#8230;too bad.</p>
<p>The solution is&#8230;again&#8230;.IUserType. The solution is store the strings in a single column, combining the strings in one with a separator that does not happens to be part of any string, as an example, if the collection contains (&#8220;Key1&#8243;, &#8220;Key2&#8243;) I want to be stored as &#8220;Key1#Key2&#8243;, here is the get part of the usertype</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:f2c461a3-5301-4624-ac21-f6a67e4dd34c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> NullSafeGet(System.Data.IDataReader rs, </span><span style="color: #0000FF;">string</span><span style="color: #000000;">[] names, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
{
    List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">String</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> result </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">String</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();
    Int32 index </span><span style="color: #000000;">=</span><span style="color: #000000;"> rs.GetOrdinal(names[</span><span style="color: #800080;">0</span><span style="color: #000000;">]);
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (rs.IsDBNull(index) </span><span style="color: #000000;">||</span><span style="color: #000000;"> String.IsNullOrEmpty((String) rs[index]))
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> result;
    </span><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (String s </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> ((String)rs[index]).Split(cStringSeparator))
        result.Add(s);
    </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> result;
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>If the data in database is null, or is an empty string I return an empty List&lt;String&gt;, but if the data is not empty I split the string with the separator, and then add each single string in the list. The set part is similar</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:bd753ac4-72d7-413d-9bc8-23795ef168df" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> NullSafeSet(System.Data.IDbCommand cmd, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value, </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> index)
{
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;"> </span><span style="color: #000000;">||</span><span style="color: #000000;"> value </span><span style="color: #000000;">==</span><span style="color: #000000;"> DBNull.Value)
    {
        NHibernateUtil.String.NullSafeSet(cmd, </span><span style="color: #0000FF;">null</span><span style="color: #000000;">, index);
    }
    IEnumerable</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">String</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> stringList </span><span style="color: #000000;">=</span><span style="color: #000000;"> (IEnumerable</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">String</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">) value;
    StringBuilder sb </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> StringBuilder();
    </span><span style="color: #0000FF;">foreach</span><span style="color: #000000;">(String s </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> stringList) {
        sb.Append(s);
        sb.Append(cStringSeparator);
    }
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (sb.Length </span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> </span><span style="color: #800080;">0</span><span style="color: #000000;">) sb.Length</span><span style="color: #000000;">--</span><span style="color: #000000;">;
    NHibernateUtil.String.Set(cmd, sb.ToString(), index);
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>If the value is null I set null value, if not I simply cast the original value as an IEnumerable&lt;String&gt;, that is sufficient for me to enumerate all the string, store them in a StringBuilder, and finally remove the trailing separator and store the string in database. Here is a Test</p>
<p><div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:423162ab-c526-4de7-9762-f397d62b1096" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">...
Domain d </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Domain();
d.BaseUri </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Uri(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">http://www.nablasoft.com</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
d.ContentBlackList.Add(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Key1</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
d.ContentBlackList.Add(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Key2</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
...</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This piece of code produces this SQL</p>
<p><div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:a7e2b2d8-d356-44b5-9542-fd9d647a3f67" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: hidden;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">INSERT INTO Domain (doma_baseUrl, doma_contentBlackList, doma_Id)
VALUES (@p0, @p1, @p2);
@p0 </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">'</span><span style="color: #800000;">http://www.nablasoft.com/</span><span style="color: #800000;">'</span><span style="color: #000000;">, @p1 </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">'</span><span style="color: #800000;">Key1#Key2</span><span style="color: #800000;">'</span><span style="color: #000000;">, @p2 </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">'</span><span style="color: #800000;">28857095-f642-4d11-875a-714eb35f0537</span><span style="color: #800000;">'</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>As you can see the <a href="http://www.codewrecks.com/blog/index.php/2008/05/30/today-menu-nhibernate-user-type/">Uri is translated into a string</a> and the two keywords are combined into one, in this way I can store all the 4 properties in the same table, having a clearer structure of the database.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/IUserType" rel="tag">IUserType</a></p>
<p><div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:e1be81e5-53f2-4684-b0d0-73555d666b4d" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><!--dotnetkickit--></div>
</p>
<div class="wlWriterSmartContent" id="scid:B3E14793-948F-49af-A347-D19C374A7C4F:87997b74-3e54-4193-a0d6-c621b3d11f96" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<script type="text/javascript"><!--
digg_bodytext = 'I have an object that has 4 properties of IList&lt;String&gt; type. You can natively map these properties in a separate table with this simple mapping';
//--></script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/05/30/second-iusertype-of-the-day-store-a-list-of-string-in-database-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Today Menu: NHibernate User Type</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/05/30/today-menu-nhibernate-user-type/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/05/30/today-menu-nhibernate-user-type/#comments</comments>
		<pubDate>Fri, 30 May 2008 14:20:41 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/05/30/today-menu-nhibernate-user-type/</guid>
		<description><![CDATA[
			
				
			
		
Ok, today I faced a really simple problem, I have a domain class with a property of type uri, that seems to be not natively supported by NHibernate. Whenever you face a problem of this type the solution is IUserType, here is the full file, it is so simple to write a user type that [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F30%2Ftoday-menu-nhibernate-user-type%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F30%2Ftoday-menu-nhibernate-user-type%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Ok, today I faced a really simple problem, I have a domain class with a property of type uri, that seems to be not natively supported by NHibernate. Whenever you face a problem of this type the solution is IUserType, <a href="http://www.codewrecks.com/blog/storage/uriusertype.zip">here is the full file</a>, it is so simple to write a user type that I really does not check with google, after I write my class I found that other people had already created it, but it is worth to take a look to some particular piece of code.</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:6be82e02-e5cb-4885-bbce-e363a36e9dfa" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> NullSafeGet(System.Data.IDataReader rs, </span><span style="color: #0000FF;">string</span><span style="color: #000000;">[] names, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> owner)
{
    Int32 index </span><span style="color: #000000;">=</span><span style="color: #000000;"> rs.GetOrdinal(names[</span><span style="color: #800080;">0</span><span style="color: #000000;">]);
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (rs.IsDBNull(index))
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;
    }
    </span><span style="color: #0000FF;">try</span><span style="color: #000000;">
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Uri(rs[index].ToString());
    }
    </span><span style="color: #0000FF;">catch</span><span style="color: #000000;"> (FormatException)
    {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">The uri is malformed, maybe it is worth to doing something else.</span><span style="color: #008000;">
</span><span style="color: #000000;">        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;">;
    }
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The NullSafeGet is called to retrieve the value from database columns in a null safe way, first of all get the index of the data into resultset, then check if it is null, (if is null return null is ok) then if some data is contained into the resultset you can try to create the uri trapping the FormatException. If you prefer you can call Uri.TryCreate that probably is a better solution respect trapping the exception <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:6381c462-7591-4ea7-a4eb-a1838623c618" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> NullSafeSet(System.Data.IDbCommand cmd, </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> value, </span><span style="color: #0000FF;">int</span><span style="color: #000000;"> index)
{
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (value </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #0000FF;">null</span><span style="color: #000000;"> </span><span style="color: #000000;">||</span><span style="color: #000000;"> value </span><span style="color: #000000;">==</span><span style="color: #000000;"> DBNull.Value)
    {
        NHibernateUtil.String.NullSafeSet(cmd, </span><span style="color: #0000FF;">null</span><span style="color: #000000;">, index);
    }
    Uri uri </span><span style="color: #000000;">=</span><span style="color: #000000;"> (Uri)value;
    NHibernateUtil.String.Set(cmd, uri.AbsoluteUri, index);
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The NullSafeSet has the duty to transform data from the original .net type (Uri) to something that can be stored in database, since I need to work only with AbsoluteUri, I store into the database the AbsoluteUri value or the Uri. Then we need to tell nhibernate the types involved</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:67b864f8-38e0-40ea-8e1d-48ec5563286d" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> Type ReturnedType
{
    </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(Uri); }
}

</span><span style="color: #0000FF;">public</span><span style="color: #000000;"> NHibernate.SqlTypes.SqlType[] SqlTypes
{
    </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> SqlType[] { NHibernateUtil.String.SqlType }; }
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The ReturnedType tells nhibernate the .Net type handled by this UserType, the SqlTypes is used to tell nhibernate the structure of the data in the table, in this example a string is sufficient to store the AbsoluteUri and so I returned an array with only a string type.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate UserType" rel="tag">NHibernate UserType</a> <a target="_blank" href="http://technorati.com/tag/Uri and NHibernate" rel="tag">Uri and NHibernate</a> </p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:29b53efb-7d42-4f9b-a83f-cd119338ff56" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><!--dotnetkickit--></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/05/30/today-menu-nhibernate-user-type/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>NHIbernate and &quot;collection was not an association&quot; when using bag and composite-element</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/05/20/nhibernate-and-collection-was-not-an-association-when-using-bag-and-composite-element/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/05/20/nhibernate-and-collection-was-not-an-association-when-using-bag-and-composite-element/#comments</comments>
		<pubDate>Tue, 20 May 2008 12:28:23 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/?p=263</guid>
		<description><![CDATA[
			
				
			
		
Look at this mapping



&#60;bag name=&#34;searchDefinition&#34; access=&#34;field&#34; cascade=&#34;all-delete-orphan&#34; table=&#34;RawSearchDefinition&#34; fetch=&#34;join&#34;&#62;
    &#60;key column=&#34;ParentObjectId&#34; /&#62;
    &#60;composite-element class=&#34;RawSearchDefinition&#34;&#62;
        &#60;property name=&#34;ExcludeKeyword&#34; column=&#34;raws_excludeKeyword&#34; type=&#34;String&#34; /&#62;
        &#60;property name=&#34;IncludeKeyword&#34; column=&#34;raws_includeKeyword&#34; type=&#34;String&#34; /&#62;
    &#60;/composite-element&#62;
&#60;/bag&#62;

]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F20%2Fnhibernate-and-collection-was-not-an-association-when-using-bag-and-composite-element%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F20%2Fnhibernate-and-collection-was-not-an-association-when-using-bag-and-composite-element%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Look at this mapping</p>
<p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:fd431021-185e-47fd-8697-140f80586b7c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">bag </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">=&quot;searchDefinition&quot;</span><span style="color: #FF0000;"> access</span><span style="color: #0000FF;">=&quot;field&quot;</span><span style="color: #FF0000;"> cascade</span><span style="color: #0000FF;">=&quot;all-delete-orphan&quot;</span><span style="color: #FF0000;"> table</span><span style="color: #0000FF;">=&quot;RawSearchDefinition&quot;</span><span style="color: #FF0000;"> fetch</span><span style="color: #0000FF;">=&quot;join&quot;</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">key </span><span style="color: #FF0000;">column</span><span style="color: #0000FF;">=&quot;ParentObjectId&quot;</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">composite-element </span><span style="color: #FF0000;">class</span><span style="color: #0000FF;">=&quot;RawSearchDefinition&quot;</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
        </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">property </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">=&quot;ExcludeKeyword&quot;</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">=&quot;raws_excludeKeyword&quot;</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">=&quot;String&quot;</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
        </span><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">property </span><span style="color: #FF0000;">name</span><span style="color: #0000FF;">=&quot;IncludeKeyword&quot;</span><span style="color: #FF0000;"> column</span><span style="color: #0000FF;">=&quot;raws_includeKeyword&quot;</span><span style="color: #FF0000;"> type</span><span style="color: #0000FF;">=&quot;String&quot;</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span><span style="color: #000000;">
    </span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">composite-element</span><span style="color: #0000FF;">&gt;</span><span style="color: #000000;">
</span><span style="color: #0000FF;">&lt;/</span><span style="color: #800000;">bag</span><span style="color: #0000FF;">&gt;</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>It seems ok but it has a subtle error, when you try to save the object,&nbsp; a &#8220;<em>collection was not an association</em>&#8221; error will arise. This error is derived from the cascade=&#8221;all-delete-orphan&#8221;, this attribute is used for real entity object not value ones. A mapping with composite element does not need cascade, the RawSearchDefinition is a value object, its lifecycle will span that of the owner.</p>
<p>The solution is simply to remove cascade attribute, that is not required.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> </p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:4ccf0fdf-fd5f-48b4-b95d-62ff346d1310" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><!--dotnetkickit--></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/05/20/nhibernate-and-collection-was-not-an-association-when-using-bag-and-composite-element/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mapping a boolean field to char in nhibernate</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/05/08/mapping-a-boolean-field-to-char-in-nhibernate/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/05/08/mapping-a-boolean-field-to-char-in-nhibernate/#comments</comments>
		<pubDate>Thu, 08 May 2008 09:51:05 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/?p=236</guid>
		<description><![CDATA[
			
				
			
		
When you work with legacy database is not infrequent that boolean value are mapped to char(1) field in databse, with Y/N or 0/1 or some other chars. In the literature there are a lot of solution, you can find for example a discussion here. When you use a user type to handle this kind of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F08%2Fmapping-a-boolean-field-to-char-in-nhibernate%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F05%2F08%2Fmapping-a-boolean-field-to-char-in-nhibernate%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>When you work with legacy database is not infrequent that boolean value are mapped to char(1) field in databse, with Y/N or 0/1 or some other chars. In the literature there are a lot of solution, you can find for example a discussion <a target="_blank" href="http://forum.hibernate.org/viewtopic.php?t=980891&amp;highlight=boolean+char">here</a>. When you use a user type to handle this kind of situation when you build HQL query you cannot use true or false in condition, for example</p>
<p>Select o from Orders where o.IsProcessed = false</p>
<p>This usually lead to a SQL error because you are trying to compare a char(1) column with the value false. The solution is to use this setting in the setting file.</p>
<p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:f1eea4ee-6a6a-4a45-98a9-87877b4b783e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">&lt;</span><span style="color: #800000;">add </span><span style="color: #FF0000;">key</span><span style="color: #0000FF;">=&quot;hibernate.query.substitutions&quot;</span><span style="color: #FF0000;"> value</span><span style="color: #0000FF;">=&quot;true 1, false 0&quot;</span><span style="color: #FF0000;"> </span><span style="color: #0000FF;">/&gt;</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This permits to substitue the value true with the literal 1 and false with the literal 0,&nbsp; but you can use whatever constant you want.</p>
<p>Alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/NHibernate" rel="tag">NHibernate</a> <a target="_blank" href="http://technorati.com/tag/Boolean To Char Mapping" rel="tag">Boolean To Char Mapping</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/05/08/mapping-a-boolean-field-to-char-in-nhibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate and batch update</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/04/02/nhibernate-and-batch-update/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/04/02/nhibernate-and-batch-update/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 11:12:39 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=182</guid>
		<description><![CDATA[
			
				
			
		
Today in a project I need to delete a lot of object from a table, the objects are instances of ActionLog and I want to delete all logs related to action when an action is deleted.
The problem is that nhibernate does not still support batch query as hibernate for java does (as explained in hibnernate [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F04%2F02%2Fnhibernate-and-batch-update%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F04%2F02%2Fnhibernate-and-batch-update%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today in a project I need to delete a lot of object from a table, the objects are instances of ActionLog and I want to delete all logs related to action when an action is deleted.</p>
<p>The problem is that nhibernate does not still support batch query as hibernate for java does (as explained in hibnernate in action). So I was forced to do a direct sql query. </p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:dc8e2a98-8308-4db8-84fc-a1ff512fe3da" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">uow.Session.CreateSQLQuery(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Delete from SchedulerActionLog where aclg_ActionId = :actId</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">)
   .AddScalar(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">count</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, NHibernateUtil.Int32)
   .SetInt32(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">actId</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, actionDto.Id)
   .UniqueResult();</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>This does not like me very much since with sqlquery you are actually bypassing the mapping and dialect. Today I&#8217;ve no time, but if someone knows a better solution please let me know <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Alk.</p>
<div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:1fbb2888-5aaa-4358-b18b-a70c39dbb33b" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati Tags: <a target="_blank" href="http://technorati.com/tags/NHibernate" rel="tag">NHibernate</a>,<a target="_blank" href="http://technorati.com/tags/Bulk%20Operations" rel="tag">Bulk Operations</a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/04/02/nhibernate-and-batch-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate ICriteria Count and the missing &quot;Having&quot;</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/02/27/nhibernate-icriteria-count-and-the-missing-of-having-clause/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/02/27/nhibernate-icriteria-count-and-the-missing-of-having-clause/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 18:41:26 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=152</guid>
		<description><![CDATA[
			
				
			
		
One of the most feared missing feature of the ICriteria API is the possibility to specify condition on projection with Having. Suppose you have this simple connection between a container and a contained object,
 
The EntityContainer class has a property called Test, is an IList&#60;EntityTest&#62; and EntityTest has a Container property to link back to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F02%2F27%2Fnhibernate-icriteria-count-and-the-missing-of-having-clause%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F02%2F27%2Fnhibernate-icriteria-count-and-the-missing-of-having-clause%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>One of the most feared missing feature of the ICriteria API is the possibility to specify condition on projection with Having. Suppose you have this simple connection between a container and a contained object,</p>
<p><a target="_blank" href="http://www.nablasoft.com/Alkampfer/wp-content/uploads/2008/02/image4.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="275" alt="image" src="http://www.nablasoft.com/Alkampfer/wp-content/uploads/2008/02/image-thumb4.png" width="504" border="0"></a> </p>
<p>The EntityContainer class has a property called Test, is an IList&lt;EntityTest&gt; and EntityTest has a Container property to link back to the container. This is the classic bidirectional association. Now we want to express with ICriteria API the following query</p>
<p>Select all EntityContainer that have more than one EntityTest in the Test collection</p>
<p>And I want to solve this problem using both the direction of association, I mean two criteria, one that use the many-to-one and the other that use the &lt;bag&gt; part. This is important because bidirectional association is not always the best solution, so it is possible to have a domain where the association is unidirectional.</p>
<p><strong>Using the many-to-one part</strong></p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:2a3887f5-3a41-41ae-8848-87a456d7f1ea" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">ICriteria c </span><span style="color: #000000;">=</span><span style="color: #000000;"> session.CreateCriteria(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(EntityContainer), </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">RootClass</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);

NEX.DetachedCriteria d </span><span style="color: #000000;">=</span><span style="color: #000000;"> NEX.DetachedCriteria.For(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(EntityTest))
    .SetProjection(NEX.Projections.RowCount())
    .Add(NEX.Property.ForName(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Container</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">).EqProperty(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">RootClass.Id</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">));

</span><span style="color: #008000;">//</span><span style="color: #008000;">You can use also
</span><span style="color: #008000;">//</span><span style="color: #008000;">.Add(NEX.Expression.EqProperty(&quot;Encontained&quot;, &quot;RootClass.Id&quot;));</span><span style="color: #008000;">
</span><span style="color: #000000;">
c.Add(NEX.Subqueries.Lt(</span><span style="color: #800080;">1</span><span style="color: #000000;">, d));
IList</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">EntityContainer</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> result </span><span style="color: #000000;">=</span><span style="color: #000000;"> c.List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">EntityContainer</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The result is achieved using a <em>DetatchedCriteria </em>and a subquery, the detatched criteria is on the EntityTest class, set a simple count projection and set the join with the original query with a Expression.EqProperty. Once the DetatchedCriteria is build I simply add it to the root Criteria using the Subqueries.Lt (Less Than). Here is the SQL</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:6c37b4c7-99ca-4d0e-8883-ed1d77d60ba6" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">SELECT</span><span style="color: #000000;"> this_.Id </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> Id2_0_, this_.PStr </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> PStr2_0_, this_.RegDate </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> RegDate2_0_
</span><span style="color: #0000FF;">FROM</span><span style="color: #000000;"> EntityContainer this_
</span><span style="color: #0000FF;">WHERE</span><span style="color: #000000;">
  </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">&lt;</span><span style="color: #000000;"> (</span><span style="color: #0000FF;">SELECT</span><span style="color: #000000;"> </span><span style="color: #FF00FF;">count</span><span style="color: #000000;">(</span><span style="color: #808080;">*</span><span style="color: #000000;">) </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> y0_
              </span><span style="color: #0000FF;">FROM</span><span style="color: #000000;"> EntityTest this_0_
              </span><span style="color: #0000FF;">WHERE</span><span style="color: #000000;"> this_0_.ContainerId </span><span style="color: #808080;">=</span><span style="color: #000000;"> this_.Id); </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">1</span><span style="color: #FF0000;">'</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The code is quite good, I simply use a subquery to calculate the number of EntityTest associated to the object and I take the EntityContainer if this value is greater than 1. (Actually the syntax force me to use 1 is less than count <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>
<p><strong>Using the &lt;bag&gt; part</strong></p>
<p>This is more difficult, because the direction of the association is from EntityContainer to EntityTest so the detatched criteria should be on EntityContainer.</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:ed582855-ca41-4b1f-a3bb-905c81a915e6" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">ICriteria c </span><span style="color: #000000;">=</span><span style="color: #000000;"> session.CreateCriteria(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(EntityContainer), </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">RootClass</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);

NEX.DetachedCriteria d </span><span style="color: #000000;">=</span><span style="color: #000000;"> NEX.DetachedCriteria.For(</span><span style="color: #0000FF;">typeof</span><span style="color: #000000;">(EntityContainer))
    .CreateAlias(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Tests</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">, </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Tests</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">)
    .SetProjection(NEX.Projections.ProjectionList()
        .Add(NEX.Projections.RowCount()))
    .Add(NEX.Property.ForName(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Id</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">).EqProperty(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">RootClass.Id</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">));

c.Add(NEX.Subqueries.Lt(</span><span style="color: #800080;">1</span><span style="color: #000000;">, d));
IList</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">EntityContainer</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> result </span><span style="color: #000000;">=</span><span style="color: #000000;"> c.List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">EntityContainer</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The solution is simple, I call CreateAlias to make the join with EntityTest through the Tests collection, add the projection rowCount and simply join with the original criteria with the EqProperty Id == RootClass.Id</p>
<p>Here is the sql generated</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:8de5b213-3207-4206-a732-bd83c26f9915" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">SELECT</span><span style="color: #000000;"> this_.Id </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> Id18_0_, this_.PStr </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> PStr18_0_, this_.RegDate </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> RegDate18_0_
</span><span style="color: #0000FF;">FROM</span><span style="color: #000000;"> EntityContainer this_
</span><span style="color: #0000FF;">WHERE</span><span style="color: #000000;"> </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">&lt;</span><span style="color: #000000;">
(</span><span style="color: #0000FF;">SELECT</span><span style="color: #000000;"> </span><span style="color: #FF00FF;">count</span><span style="color: #000000;">(</span><span style="color: #808080;">*</span><span style="color: #000000;">) </span><span style="color: #0000FF;">as</span><span style="color: #000000;"> y0_
</span><span style="color: #0000FF;">FROM</span><span style="color: #000000;"> EntityContainer this_0_ </span><span style="color: #0000FF;">inner</span><span style="color: #000000;"> </span><span style="color: #808080;">join</span><span style="color: #000000;"> EntityTest tests1_ </span><span style="color: #0000FF;">on</span><span style="color: #000000;"> this_0_.Id</span><span style="color: #808080;">=</span><span style="color: #000000;">tests1_.ContainerId
</span><span style="color: #0000FF;">WHERE</span><span style="color: #000000;"> this_0_.Id </span><span style="color: #808080;">=</span><span style="color: #000000;"> this_.Id); </span><span style="color: #008000;">@p0</span><span style="color: #000000;"> </span><span style="color: #808080;">=</span><span style="color: #000000;"> </span><span style="color: #FF0000;">'</span><span style="color: #FF0000;">1</span><span style="color: #FF0000;">'</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>And the game is done <img src='http://www.codewrecks.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Alk.</p>
<div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:624104e4-4f23-4b0c-a959-dae3507f0e47" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati Tags: <a target="_blank" href="http://technorati.com/tags/NHibernate" rel="tag">NHibernate</a>,<a target="_blank" href="http://technorati.com/tags/ICriteria" rel="tag">ICriteria</a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/02/27/nhibernate-icriteria-count-and-the-missing-of-having-clause/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Errata corrige</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/08/06/errata-corrige/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/08/06/errata-corrige/#comments</comments>
		<pubDate>Mon, 06 Aug 2007 21:22:34 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=102</guid>
		<description><![CDATA[
			
				
			
		
Thanks to my friend Janky for notice that I made a mistake in a previous post. In that post I speak about a &#8220;conversation&#8221; but actually I was describing a UnitOfWork, that was my fault. The exact definition of a conversation is given in &#8220;Hibernate In Action&#8221; where Gavin King states that.

&#8220;We call a unit [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F08%2F06%2Ferrata-corrige%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F08%2F06%2Ferrata-corrige%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Thanks to my friend <a target="_blank" href="http://blogs.ugidotnet.org/janky">Janky</a> for notice that I made a mistake in a <a target="_blank" href="http://www.nablasoft.com/Alkampfer/?p=100">previous post</a>. In that post I speak about a &#8220;conversation&#8221; but actually I was describing a UnitOfWork, that was my fault. The exact definition of a conversation is given in &#8220;Hibernate In Action&#8221; where Gavin King states that.
</p>
<p><em>&#8220;We call a unit of work that completes in several client/server request and response cycles a <strong>conversation</strong>&#8220;.<br />
</em></p>
<p>So a conversation is really a unit of work, but more complex than a standard one because it span several request, and naturally it use more than one NHibernate session.
</p>
<p>Thanks again to janky for making me notice the error.
</p>
<p>Alk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/08/06/errata-corrige/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manage conversation to a database</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/08/04/manage-conversation-to-a-database/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/08/04/manage-conversation-to-a-database/#comments</comments>
		<pubDate>Sat, 04 Aug 2007 08:12:11 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Nhibernate]]></category>
		<category><![CDATA[Sql Server]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=100</guid>
		<description><![CDATA[
			
				
			
		
When you begin to work with an ORM you encounter the concept of conversation, a conversation is the analogous of a transaction for database code, in a conversation I must be able to make a dialog to the ORM using the same context. In database there is no such concept, but I like it, and [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F08%2F04%2Fmanage-conversation-to-a-database%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F08%2F04%2Fmanage-conversation-to-a-database%2F&amp;source=alkampfer&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>When you begin to work with an ORM you encounter the concept of conversation, a conversation is the analogous of a transaction for database code, in a conversation I must be able to make a dialog to the ORM using the same context. In database there is no such concept, but I like it, and since sometimes I need to share nhibernate code and standard sql code in the same project I wish to be able to create a &#8220;conversation&#8221; that spans direct database access and nhibernate code. Basically a conversation has these properties
</p>
<ul>
<li>All operation done into a conversation are transactional
</li>
<li>Inside a conversation Nhibernate share the same connection used by direct SQL code
</li>
<li>Inside a conversation I must use the same Nhibernate session.
</li>
<li>Code must be unaware of the presence of a conversation, this means that the code should not matter if we are in or outside a conversation
</li>
</ul>
<p>The first class I create is the Conversation,  a class that takes care of the creation of the connection, session, transaction and so on. This class should implement IDisposable so I can use the semantic of <em>using keyword</em> that is really useful.
</p>
<p><span style="font-family:Consolas"><span style="color:black">   </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">class</span><span style="color:black"> </span><span style="color:#2b91af">Conversation</span><span style="color:black"> : </span><span style="color:#2b91af">IDisposable</span><span style="color:black"> {<br/> <br/>      </span><span style="color:blue">private</span><span style="color:black"> </span><span style="color:#2b91af">DbConnection</span><span style="color:black"> mConnection = </span><span style="color:blue">null</span><span style="color:black">;<br/>      </span><span style="color:blue">private</span><span style="color:black"> </span><span style="color:#2b91af">DbTransaction</span><span style="color:black"> mTransaction = </span><span style="color:blue">null</span><span style="color:black">;<br/>      </span><span style="color:blue">private</span><span style="color:black"> </span><span style="color:#2b91af">ISession</span><span style="color:black"> mSession = </span><span style="color:blue">null</span><span style="color:black">;<br/>      </span><span style="color:blue">private</span><span style="color:black"> </span><span style="color:#2b91af">Boolean</span><span style="color:black"> mIsDirty = </span><span style="color:blue">false</span><span style="color:black">;<br/> <br/></span><span style="color:blue">    </span><span style="color:black">  </span><span style="color:blue">internal</span><span style="color:black"> </span><span style="color:blue">virtual</span><span style="color:black"> </span><span style="color:#2b91af">DbConnection</span><span style="color:black"> Connection {<br/>         </span><span style="color:blue">get</span><span style="color:black"> {</span><span style="color:blue">return</span><span style="color:black"> mConnection ?? (mConnection = CreateConnection());}<br/>      }<br/> <br/>      </span><span style="color:blue">internal</span><span style="color:black"> </span><span style="color:blue">virtual</span><span style="color:black"> </span><span style="color:#2b91af">DbTransaction</span><span style="color:black"> Transaction {<br/>         </span><span style="color:blue">get</span><span style="color:black"> {</span><span style="color:blue">return</span><span style="color:black"> mTransaction;}<br/>      }<br/> <br/>      </span><span style="color:blue">internal</span><span style="color:black"> </span><span style="color:blue">virtual</span><span style="color:black"> </span><span style="color:#2b91af">ISession</span><span style="color:black"> Session {<br/>         </span><span style="color:blue">get</span><span style="color:black"> {r</span><span style="color:blue">eturn</span><span style="color:black"> mSession ?? (mSession = </span><span style="color:#2b91af">SessionManager</span><span style="color:black">.CreateNewSession(Connection));}<br/>      }<br/><br/>      </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">virtual</span><span style="color:black"> </span><span style="color:blue">void</span><span style="color:black"> MarkDirty() {<br/>         mIsDirty = </span><span style="color:blue">true</span><span style="color:black">;<br/>      }<br/> <br/>      </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">virtual</span><span style="color:black"> </span><span style="color:blue">void</span><span style="color:black"> Close() {<br/>         </span><span style="color:blue">try</span><span style="color:black"> {<br/>            </span><span style="color:blue">if</span><span style="color:black"> (!mIsDirty)<br/>               mTransaction.Commit();<br/>         }<br/>         </span><span style="color:blue">finally</span><span style="color:black"> {<br/>            mTransaction.Dispose();<br/>            Session.Dispose();<br/>            mConnection.Dispose();<br/>         }<br/>      }<br/> <br/>      </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">void</span><span style="color:black"> Dispose() {<br/>         Close();<br/>      }<br/>    }<br/>}<br />
</span></span></p>
<p>This class creates a connection when needed, it does the same thing with the Nhibernate session, using a session manager that inject code into nhibernate session. It is disposable, and when dispose is called the transaction will be committed if no one had called the <em>ISDirty()</em> method. If you want to rollback the conversation simply call <em>IsDirty()</em>  method and when the conversation will be closed, all operations will be rolled back. Now we need a static class called ConversationManager to keep track of the concept of &#8220;Current Conversation&#8221;
</p>
<p><img src="http://www.nablasoft.com/Alkampfer/wp-content/uploads/2007/08/080407-0812-manageconve1.png" alt=""/>
	</p>
<p>BeginConversation() will return a conversation object and since it is diposable you can use code like this.
</p>
<p><span style="font-family:Consolas"><span style="color:blue">using</span><span style="color:black"> (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> conv = </span><span style="color:#2b91af">ConversationManager</span><span style="color:black">.BeginConversation()) {<br/>   </span><span style="color:green">//do your access code here using conv.Transaction or conv.Session</span><span style="color:black"><br/>}<br />
</span></span></p>
<p>When code wants to access a database and wish to be enlisted in a Conversation, it should call <em>ConversationManager.GetConversation()</em>, this return a reference to the current conversation.
</p>
<p><span style="font-family:Consolas"><span style="color:blue">using</span><span style="color:black"> (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> conversation = </span><span style="color:#2b91af">ConversationManager</span><span style="color:black">.GetConversation()) {<br/>   </span><span style="color:green">//do your access code here using conv.Transaction or conv.Session</span><span style="color:black"><br/>}<br />
</span></span></p>
<p>To make this code work The <em>GetConversation()</em> function in the ConversationManager class should not return a direct reference to the current conversation, because the caller code will dispose it before the conversation is really ended, so I use a weak reference.
</p>
<p><span style="font-family:Consolas"><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">class</span><span style="color:black"> </span><span style="color:#2b91af">ConversationWeakReference</span><span style="color:black"> : </span><span style="color:#2b91af">Conversation</span><span style="color:black"> {<br/> <br/>   </span><span style="color:blue">private</span><span style="color:black"> </span><span style="color:#2b91af">Conversation</span><span style="color:black"> mOriginal;<br/>   </span><span style="color:blue">public</span><span style="color:black"> ConversationWeakReference (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> original) {<br/>      mOriginal = original;<br/>   }<br/> <br/>   </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">override</span><span style="color:black"> System.Data.Common.</span><span style="color:#2b91af">DbConnection</span><span style="color:black"> Connection {<br/>      </span><span style="color:blue">get</span><span style="color:black"> {</span><span style="color:blue">return</span><span style="color:black"> mOriginal.Connection;}<br/>   }<br/> <br/>   </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">override</span><span style="color:black"> </span><span style="color:blue">global</span><span style="color:black">::NHibernate.</span><span style="color:#2b91af">ISession</span><span style="color:black"> Session {<br/>      </span><span style="color:blue">get</span><span style="color:black"> {</span><span style="color:blue">return</span><span style="color:black"> mOriginal.Session;}<br/>   }<br/> <br/>   </span><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">override</span><span style="color:black"> System.Data.Common.</span><span style="color:#2b91af">DbTransaction</span><span style="color:black"> Transaction {<br/>      </span><span style="color:blue">get</span><span style="color:black"> {</span><span style="color:blue">return</span><span style="color:black"> mOriginal.Transaction;}<br/>   }<br/> <br/>   </span><span style="color:blue">protected</span><span style="color:black"> </span><span style="color:blue">override</span><span style="color:black"> </span><span style="color:blue">void</span><span style="color:black"> Close() {}<br/>}<br />
</span></span></p>
<p>As you can see this class Inherit from a Conversation and wraps the real Conversation, but override the CloseMethod with a no op method. This means that when a ConversationWeakReference gets disposed the real conversation still remain open. The key is in the GetConversation() method of the ConversationManager.
</p>
<p><span style="font-family:Consolas"><span style="color:blue">public</span><span style="color:black"> </span><span style="color:blue">static</span><span style="color:black"> </span><span style="color:#2b91af">Conversation</span><span style="color:black"> GetConversation() {<br/>   </span><span style="color:#2b91af">Conversation</span><span style="color:black"> current = GetFromStorage();<br/>   </span><span style="color:blue">return</span><span style="color:black"> current == </span><span style="color:blue">null</span><span style="color:black"> ? </span><span style="color:blue">new</span><span style="color:black"> </span><span style="color:#2b91af">Conversation</span><span style="color:black">() : </span><span style="color:blue">new</span><span style="color:black"> </span><span style="color:#2b91af">ConversationWeakReference</span><span style="color:black">(current);   <br/>}<br />
</span></span></p>
<p>As you can notice the ConversationManager check if there is an active Conversation, and returns a new conversation or a new conversationWeakReference if there is an active conversation. With this trick if the caller is in a ConversationScope he will get a weak reference, but if the code is not in a conversation it will obtain a full conversation object that gets committed at the end of the scope. Real code has some more check but this is the general idea. Basically if we are not in a Conversation the code
</p>
<p style="background: white"><span style="font-family:Consolas"><span style="color:blue">using</span><span style="color:black"> (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> conversation = </span><span style="color:#2b91af">ConversationManager</span><span style="color:black">.GetConversation()) {<br/>   </span><span style="color:green">//do your access code here using conversation.Transaction or conversation.Session</span><span style="color:black"><br/>}<br />
</span></span></p>
<p style="background: white">
 </p>
<p style="background: white">creates a new conversation that gets closed at the end of the scope, actually committing all work. But if the call chain is the following
</p>
<p><span style="font-family:Consolas"><span style="color:blue"><br/>using</span><span style="color:black"> (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> conv = </span><span style="color:#2b91af">ConversationManager</span><span style="color:black">.BeginConversation()) {<br/>   </span><span style="color:green">&#8230;</span><span style="color:black"><br/>   </span><span style="color:green">//in another class or method called <br/></span><span style="color:blue">   using</span><span style="color:black"> (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> conversation = </span><span style="color:#2b91af">ConversationManager</span><span style="color:black">.GetConversation()) {<br/>      </span><span style="color:green">//do your access code here with conversation</span><span style="color:black"><br/>   }<br/></span><span style="color:green">   &#8230;</span><span style="color:black"><br/>   </span><span style="color:green">//in another class or method called <br/></span><span style="color:blue">   using</span><span style="color:black"> (</span><span style="color:#2b91af">Conversation</span><span style="color:black"> conversation = </span><span style="color:#2b91af">ConversationManager</span><span style="color:black">.GetConversation()) {<br/>      </span><span style="color:green">//do your access code here with conversation</span><span style="color:black"><br/>   }<br/>}<br />
</span></span></p>
<p>The two inner using block will share the same conversation, accessed by two distinct ConnectionWeakReference. The good of this technique is that the inner code is unaware of the presence or absence of a conversation.
</p>
<p>Final question is &#8220;where do you store the reference to the current conversation&#8221;? I use <em>System.Runtime.Remoting.Messaging.CallContext</em> because it can manage the concept of call context, and works well even in web scenario where the context will span a whole ASP.NET Request. If you dig with reflector in the HttpContext object you will end finding that the web context is stored in a CallContext.
</p>
<p>Alk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/08/04/manage-conversation-to-a-database/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
