<?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>James Gregory &#187; NHibernate</title>
	<atom:link href="http://jagregory.com/writings/category/nhibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://jagregory.com</link>
	<description>Monkeying with the code</description>
	<lastBuildDate>Tue, 22 Jun 2010 11:07:25 +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>Empty NHibernate logs and poor performance</title>
		<link>http://jagregory.com/writings/empty-nhibernate-logs-and-poor-performance/</link>
		<comments>http://jagregory.com/writings/empty-nhibernate-logs-and-poor-performance/#comments</comments>
		<pubDate>Fri, 12 Sep 2008 17:33:28 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Work]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=105</guid>
		<description><![CDATA[We had an issue recently where NHibernate was performing very poorly on our production server, but not on our developer machines or our test server. I investigated the issue and narrowed it down to two symptoms.
Symptom 1:
Very poor performance. I&#8217;m talking 10+ seconds per page load, with no more than 5 queries being executed by [...]]]></description>
			<content:encoded><![CDATA[<p>We had an issue recently where NHibernate was performing very poorly on our production server, but not on our developer machines or our test server. I investigated the issue and narrowed it down to two symptoms.</p>
<p><strong>Symptom 1:</strong><br />
Very poor performance. I&#8217;m talking 10+ seconds per page load, with no more than 5 queries being executed by NHibernate.</p>
<p><strong>Symptom 2:</strong><br />
Empty log files. None of our log files had any data in on the live server, but they did on our other systems.</p>
<p>I decided to investigate the second symptom first, as it may be causing the first (ends up it was).</p>
<p>Firstly, I noticed that our logging was set to DEBUG. Must&#8217;ve been a leftover from when we first deployed NHibernate, very sloppy, I know. So I reset that to WARN, but it had no effect.</p>
<p>When files aren&#8217;t being written to, you should always check the directory permissions. Low and behold, it was a permissions problem. Our test server had different users allowed to write to the Logs directory than our production server. I granted the same users access, NETWORK SERVICE and IUSR_MACHINENAME in our case.</p>
<p>After I recycled the IIS worker processes, we were flying again. We&#8217;re back to having < 1sec page loads.</p>
<p>This is pure speculation, but what I believe was happening is this: Logging was set to DEBUG, so it was logging <em>a lot</em>. With each log call, the logger was failing to get write access to the files and throwing an exception, that exception would probably have propagated a bit too. The combination of the sheer amount of data being written to the log, and an exception per log call, were responsible for the severe slowdown.</p>
<p>So in short: Always make sure NHibernate has write access to its own log directory!</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/empty-nhibernate-logs-and-poor-performance/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Introducing Fluent NHibernate</title>
		<link>http://jagregory.com/writings/introducing-fluent-nhibernate/</link>
		<comments>http://jagregory.com/writings/introducing-fluent-nhibernate/#comments</comments>
		<pubDate>Fri, 08 Aug 2008 16:56:40 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hobby Projects]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[DotNet]]></category>
		<category><![CDATA[FluentInterface]]></category>
		<category><![CDATA[OpenSource]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/?p=95</guid>
		<description><![CDATA[A couple of people have already covered this already, specifically Bobby Johnson, Matt Hinze, and Zachariah Young. I figure I should say something on it anyway.
I&#8217;ve adopted a project from Jeremy Miller that I think has the potential to be a really useful tool. It&#8217;s called Fluent NHibernate, and it&#8217;s primarily a fluent API for [...]]]></description>
			<content:encoded><![CDATA[<p><em>A couple of people have already covered this already, specifically <a href="http://www.IAmNotMyself.com/2008/08/07/SkinningTheCatWithFluentNHibernate.aspx">Bobby Johnson</a>, <a href="http://mhinze.com/fluent-nhibernate-project/">Matt Hinze</a>, and <a href="http://zachariahyoung.com/zy/post/2008/08/fluent-nhibernate-for-creating-entity-mapping-files.aspx">Zachariah Young</a>. I figure I should say something on it anyway.</em></p>
<p>I&#8217;ve adopted a project from <a href="http://codebetter.com/blogs/jeremy.miller/">Jeremy Miller</a> that I think has the potential to be a really useful tool. It&#8217;s called <a href="http://code.google.com/p/fluent-nhibernate/">Fluent NHibernate</a>, and it&#8217;s primarily a fluent API for mapping classes with NHibernate.</p>
<p>We&#8217;re all well aware how awesome NHibernate is, but I think we all also have a bit of a dislike for the amount of XML you need to write to get your classes mapped; not only that, but also how the mappings are distinctly separate from the rest of your application. They&#8217;re often neglected and untested. One of the core tenets of the project is that we need a more succinct, readable, and testable way of writing your mappings.</p>
<h4>The API</h4>
<p>Take the following simple hbm file:</p>
<pre name="code" class="xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;hibernate-mapping xmlns=&quot;urn:nhibernate-mapping-2.2&quot;
    namespace=&quot;Eg&quot; assembly=&quot;Eg&quot;&gt;

    &lt;class name=&quot;Customer&quot; table=&quot;Customers&quot;&gt;
        &lt;id name=&quot;ID&quot;&gt;
            &lt;generator class=&quot;identity&quot; /&gt;
        &lt;/id&gt;

        &lt;property name=&quot;Name&quot; /&gt;
        &lt;property name=&quot;Credit&quot; /&gt;

        &lt;bag name=&quot;Products&quot; table=&quot;Products&quot;&gt;
            &lt;key column=&quot;CustomerID&quot;/&gt;
            &lt;one-to-many class=&quot;Eg.Product, Eg&quot;/&gt;
        &lt;/bag&gt;

        &lt;component name=&quot;Address&quot; class=&quot;Eg.Address, Eg&quot;&gt;
            &lt;property name=&quot;AddressLine1&quot; /&gt;
            &lt;property name=&quot;AddressLine2&quot; /&gt;
            &lt;property name=&quot;CityName&quot; /&gt;
            &lt;property name=&quot;CountryName&quot; /&gt;
        &lt;/component&gt;
    &lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p>Then compare it to the same mapping, created using the fluent API:</p>
<pre name="code" class="c-sharp">
public CustomerMap : ClassMap&lt;Customer&gt;
{
  public CustomerMap()
  {
    Id(x =&gt; x.ID);
    Map(x =&gt; x.Name);
    Map(x =&gt; x.Credit);
    HasMany&lt;Product&gt;(x =&gt; x.Products)
      .AsBag();
    Component&lt;Address&gt;(x =&gt; x.Address, m =&gt;
    {
        m.Map(x =&gt; x.AddressLine1);
        m.Map(x =&gt; x.AddressLine2);
        m.Map(x =&gt; x.CityName);
        m.Map(x =&gt; x.CountryName);
    });
  }
}
</pre>
<p>Firstly, you&#8217;ll note that there is a marginal reduction in lines of code, but that&#8217;s not what we&#8217;re particularly striving for. Instead we&#8217;re intent on reducing the verbosity and <strong>noise</strong> of the code. This manifests itself in a <a href="http://en.wikipedia.org/wiki/Convention_over_Configuration">convention over configuration</a> design for the API, where we choose the most common setups and use those as the default. For example with the <code>id</code> element in the hbm file, you&#8217;re required to specify what the generator type is; however, in our fluent API we check the type of your identity property and decide what generator we should use. Int&#8217;s and longs default to identity, while GUIDs use the guid.comb generator. You can change these explicitly, but when you are using the default, it greatly reduces the verbosity of your mapping.</p>
<h4>Testability</h4>
<p>Another one of our goals is to make your mappings more robust. I imagine most people have had the problem where you&#8217;ve renamed a property and not updated the mapping file; due to there being no compile time validation, the only way to catch these mistakes are at run time (hopefully you had tests to cover that!). With the way our API is designed, you use the actual properties on your classes to create the mapping, so there&#8217;s nothing to forget. If you rename a property, your IDE will either rename the property in the mapping, or fail at compilation.</p>
<p>We also want to help you verify that your mappings are set up properly, not just syntactically valid. So to make your 	integration tests a bit easier, we&#8217;re providing an API for testing your mappings.</p>
<pre name="code" class="c-sharp">
[Test]
public void VerifyCustomerSaves()
{
    new PersistenceSpecification&lt;Customer&gt;()
        .CheckProperty(x =&gt; x.Name, &quot;James Gregory&quot;)
        .CheckProperty(x =&gt; x.Age, 22)
        .VerifyTheMappings();
}
</pre>
<p>Behind the scenes the <code>PersistenceSpecification</code> creates an instance of your entity, then populates it with the values you specify through the <code>CheckProperty</code> method. This entity is then saved to the database, then reloaded through a separate connection. The returned entity is then compared to the one originally saved, and any differences fail the test. It&#8217;s a fairly standard integration test, except we&#8217;ve taken the time to write all the wiring up that needs to be done, so you don&#8217;t have to.</p>
<h4>The Framework</h4>
<p>We&#8217;re working towards our first official release, which will have a fairly solid implementation of the API. Once that&#8217;s out in the wild, we&#8217;re going to focus on our Framework.</p>
<p>Our framework is a layer that sits on-top of the API to provide an even better experience. We&#8217;re looking to integrate with your favorite container, which will reduce the code you need to write to integrate NHibernate into your system. Then we&#8217;re going to tackle extensible conventions, which will allow you to specify your own implied conventions for your application. For example, if you&#8217;re <strong>always</strong> going to call your identifier &#8220;ID&#8221;, then why should you have to specify it every time? <em>You shouldn&#8217;t!</em></p>
<p>Development is progressing at a nice pace, and I expect we&#8217;ll be able to get our first release out within the next few weeks. The testing API hasn&#8217;t been kept quite as up to date as the main API, but we&#8217;re working on that too. It&#8217;s open-source, so suggestions and patches are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/introducing-fluent-nhibernate/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Introducing the filterable DeleGrid</title>
		<link>http://jagregory.com/writings/introducing-the-filterable-delegrid/</link>
		<comments>http://jagregory.com/writings/introducing-the-filterable-delegrid/#comments</comments>
		<pubDate>Wed, 05 Mar 2008 20:41:10 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hobby Projects]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/2008/03/05/introducing-the-filterable-delegrid/</guid>
		<description><![CDATA[The DeleGrid is a paged GridView control that handles data-binding through the use of events and delegates rather than with a traditional collection.
What this means is that you have full control over the data that is shown in the currently displayed page. Traditionally you&#8217;d retrieve the whole recordset then page it locally, but with the [...]]]></description>
			<content:encoded><![CDATA[<p>The DeleGrid is a paged GridView control that handles data-binding through the use of events and delegates rather than with a traditional collection.</p>
<p>What this means is that you have full control over the data that is shown in the currently displayed page. Traditionally you&#8217;d retrieve the whole recordset then page it locally, but with the DeleGrid you can utilise your database/ORMs paging features.</p>
<p>To quote myself from when I first <a href="http://blog.jagregory.com/2007/12/09/delegrid/">introduced the DeleGrid</a>:</p>
<blockquote><p>
[The DeleGrid] came about because I wanted a nice way of implementing paging using NHibernate without having the grid know about it. I really didn’t want NHibernate to leave my data layer, so I needed a nice way of the grid calling my DAL with the paging parameters.
</p></blockquote>
<h4>What&#8217;s new?</h4>
<p>The biggest change in version 1.1 is the introduction of filtering. The filter isn&#8217;t generated in some black-box fashion, instead it&#8217;s defined by the programmer. It&#8217;s built up from the columns in the grid, which define their own filtering behavior.</p>
<p>The filter acts upon any columns in the grid that implement the IFilterableField interface. Implementing this interface in your own fields is easy, so you&#8217;re quickly able to create custom filtering behavior for your grid. An example would be a date column, that has a date-picker as a filter control.</p>
<p><img src='http://blog.jagregory.com/wp-content/uploads/2008/03/picture-1.png' alt='Filter Screenshot' /></p>
<p>I&#8217;ve chosen not to implement the wealth of appearance customisations that are available in the normal templated controls. This is down to two reasons, firstly I don&#8217;t agree with it, appearance should be controlled soley through CSS. Secondly, there are so many, I couldn&#8217;t be bothered. So you&#8217;re only able to attach CSS classes to the buttons and cells, and specify the image urls for the buttons.</p>
<h4>An example implementation</h4>
<p>The grid now has a companion project, it&#8217;s own data library. This separation is to keep you from having to reference System.Web in your data-layer. To use the DeleGrid in your project you&#8217;ll need to reference JAGregory.Controls.DeleGrid.dll and the JAGregory.Controls.Data.dll in your web project, then reference JAGregory.Controls.Data.dll in your data layer, if they&#8217;re separate projects.</p>
<p>So to begin with, add the reference to JAGregory.Controls.DeleGrid.dll and JAGregory.Controls.Data.dll into your web project. This will allow you to use the DeleGrid in your page. Once you&#8217;ve done that, you&#8217;ll need to reference the control in your page, you can either do this using a Register tag in your page, or in the web.config as so:</p>
<pre name="code" class="xml">
&lt;pages&gt;
  &lt;controls&gt;
    &lt;add tagPrefix=&quot;jag&quot; namespace=&quot;JAGregory.Controls&quot;
      assembly=&quot;JAGregory.Controls.DeleGrid&quot; /&gt;
  &lt;/controls&gt;
&lt;/pages&gt;
</pre>
<p>With that in place, you can now put the DeleGrid into your page:</p>
<pre name="code" class="html">
&lt;jag:DeleGrid ID=&quot;grid&quot; Runat=&quot;server&quot; AllowFiltering=&quot;true&quot;
  AutoGenerateColumns=&quot;false&quot;&gt;
    &lt;FilterStyle ToggleOnImageUrl=&quot;img/find.png&quot; ToggleOffImageUrl=&quot;img/find.png&quot;
      ExecuteImageUrl=&quot;img/go.png&quot; /&gt;
    &lt;Columns&gt;
        &lt;jag:FilterableTextField HeaderText=&quot;Name&quot; DataField=&quot;Name&quot; /&gt;
        &lt;jag:FilterableBooleanField HeaderText=&quot;Active&quot; DataField=&quot;Active&quot; /&gt;
    &lt;/Columns&gt;
&lt;/jag:DeleGrid&gt;
</pre>
<p>n.b. In this example I&#8217;m using a Customer object to bind against it, which simply has the Name and Active properties.</p>
<p>For this grid we&#8217;ve set AllowFiltering to true, which enables the filter, then we&#8217;ve set AutoGenerateColumns to false so we can add our own custom columns. The two columns both implement the aforementioned IFilterableField interface, which allows them to define their own filtering behavior.</p>
<p>I&#8217;ve also set the image urls so the buttons will be visible.</p>
<p>Now that the page is set up, we need to get down to the binding. In your code-behind:</p>
<pre name="code" class="c-sharp">
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    // attach the events for requesting the data and totals
    grid.TotalRecordCountRequest += grid_TotalRecordCountRequest;
    grid.PageDataRequest += grid_PageDataRequest;
}

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if (!IsPostBack)
        grid.DataBind();
}
</pre>
<p>What&#8217;ve just done is attach the TotalRecordCountRequest and PageDataRequest handlers to the grid, which respectively fetch the total record count for the full grid, and fetch the current page of data from the database; the implementations are below.</p>
<pre name="code" class="c-sharp">
private IEnumerable grid_PageDataRequest(object sender, PageDataRequestEventArgs e)
{
    CustomerRepository repos = new CustomerRepository();

    // get the requested page of data from the database
    return repos.FindAllPaged(e.Range, e.Sort, e.Filters);
}

private int grid_TotalRecordCountRequest(object sender, DataRequestEventArgs e)
{
    CustomerRepository repos = new CustomerRepository();

    // get the total records
    return repos.GetAllCount(e.Filters);
}
</pre>
<p>I&#8217;m using a <a href="http://www.martinfowler.com/eaaCatalog/repository.html">repository pattern</a> to handle data-access. In the PageDataRequest handler we&#8217;re taking the range, sort, and filter info that the grid passed us and sending it off to the repository to get the data. Similarily the TotalRecordCountRequest handler does a similar thing but without the range or sort info.</p>
<p>That&#8217;s it really for using the DeleGrid, you just need to take the filter info and handle it using your specific ORM.</p>
<h4>Repository implementation</h4>
<p>Ok I&#8217;ll throw you a bone, here&#8217;s the repository implementation to show how easy it is using NHibernate:</p>
<pre name="code" class="c-sharp">
public class CustomerRepository
{
    /// &lt;summary&gt;
    /// Creates a NHibernate ICriteria based on the filters.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;filters&quot;&gt;Filters to apply.&lt;/param&gt;
    /// &lt;returns&gt;ICriteria&lt;/returns&gt;
    private ICriteria CreateFilteredCriteria(FilterCriterionCollection filters)
    {
        ICriteria criteria = SessionManager.CurrentSession
            .CreateCriteria(typeof(Customer));

        // criterion handling - write this yourself depending on how your
        // db filters (and what filter types you're supporting)
        foreach (FilterCriterion filter in filters)
        {
            if (filter.Type == typeof(string))
                criteria.Add(Expression.Like(filter.FieldName, &quot;%&quot; + filter.Value + &quot;%&quot;));
            else if (filter.Type == typeof(bool))
                criteria.Add(Expression.Eq(filter.FieldName, filter.Value));
        }

        return criteria;
    }

    /// &lt;summary&gt;
    /// Gets the total record count from the database using the filters.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;filters&quot;&gt;Filters to apply before getting the count.&lt;/param&gt;
    /// &lt;returns&gt;Total number of records in the filtered list&lt;/returns&gt;
    public int GetAllCount(FilterCriterionCollection filters)
    {
        return CreateFilteredCriteria(filters)
            .SetProjection(Projections.Count(&quot;ID&quot;))
            .UniqueResult&lt;int&gt;();
    }

    /// &lt;summary&gt;
    /// Gets one page of data from the database.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;range&quot;&gt;Select range (start ID and number of records).&lt;/param&gt;
    /// &lt;param name=&quot;sort&quot;&gt;Sorting to apply.&lt;/param&gt;
    /// &lt;param name=&quot;filters&quot;&gt;Filters to apply.&lt;/param&gt;
    /// &lt;returns&gt;List for one page of data.&lt;/returns&gt;
    public IList&lt;Customer&gt; FindAllPaged(SelectRange range, SortInfo sort, FilterCriterionCollection filters)
    {
        // create the criteria using the filters, then set the range
        ICriteria criteria = CreateFilteredCriteria(filters)
            .SetFirstResult(range.Start)
            .SetMaxResults(range.Size);

        // only add the sort if one is specified
        if (!string.IsNullOrEmpty(sort.Field))
        {
            if (sort.Direction == Direction.Asc)
                criteria.AddOrder(Order.Asc(sort.Field));
            else
                criteria.AddOrder(Order.Desc(sort.Field));
        }

        return criteria.List&lt;Customer&gt;();
    }
}
</pre>
<p>The <code>CreateFilteredCriteria</code> method is doing most of the leg work. It takes creates an NHibernate criteria, then adds any filter criterions to it. It iterates the filters collection, checking their type and adding the appropriate NHibernate criterion. Simple!</p>
<h4>The example project</h4>
<p>I&#8217;ve attached a sample project that uses the grid to display a collection of customers that are paged and filtered. The example uses a SQLite database with NHibernate for data-access, I&#8217;ve done this to keep the extraneous code to a minimum.</p>
<h4>Downloads</h4>
<p>The DeleGrid is open-source under the <a href="http://en.wikipedia.org/wiki/BSD_license">new BSD License</a>; read the license for what you’re allowed to do.</p>
<p>You can download the source here: <a href="http://jagregory.googlecode.com/files/DeleGrid-1.1-source.zip">Download Source</a>.<br />
You can download the latest binary here: <a href="http://jagregory.googlecode.com/files/DeleGrid-1.1.zip">Download Binary</a>.<br />
You can download the example project here: <a href="http://jagregory.googlecode.com/files/DeleGridExample.zip">Download Example</a>.</p>
<p>The source is also accessible from Subversion at: <a href="http://jagregory.googlecode.com/svn/trunk/DeleGrid/">http://jagregory.googlecode.com/svn/trunk/DeleGrid/</a> (using user jagregory-read-only)</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/introducing-the-filterable-delegrid/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ObjectField &#8211; A GridView field</title>
		<link>http://jagregory.com/writings/objectfield/</link>
		<comments>http://jagregory.com/writings/objectfield/#comments</comments>
		<pubDate>Sun, 17 Feb 2008 22:24:57 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Hobby Projects]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/2008/02/17/objectfield/</guid>
		<description><![CDATA[
The version of the ObjectField that this post refers to is now out of date. Please go to the ObjectField 1.1 post for the latest version.

I encountered a problem while binding a complex object to a GridView, in that the BoundField doesn&#8217;t support specifying a nested value in it&#8217;s DataField property. So if you have [...]]]></description>
			<content:encoded><![CDATA[<p class="superseded">
The version of the ObjectField that this post refers to is now out of date. Please go to the <a href="http://blog.jagregory.com/2008/02/21/objectfield-11/">ObjectField 1.1</a> post for the latest version.
</p>
<p>I encountered a problem while binding a complex object to a GridView, in that the BoundField doesn&#8217;t support specifying a nested value in it&#8217;s DataField property. So if you have a list of Customer&#8217;s, and want to display the TelephoneNumber property from inside the customer&#8217;s ContactDetails property, you&#8217;re out of luck.</p>
<pre name="code" class="html">&lt;asp:BoundField DataField=&quot;ContactDetails.TelephoneNumber&quot; /&gt;</pre>
<p>The above would fall over with an exception along the lines of:<br />
<code>A field or property with the name 'ContactDetails.TelephoneNumber' was not found on the selected data source.</code></p>
<p>This is a mind-boggling flaw in the BoundField, with the main solution being to create a nested GridView, which is just overkill for most situations. This problem especially rears it&#8217;s ugly head if you&#8217;re using an ORM layer such as <a href="http://www.nhibernate.org/">NHibernate</a> or <a href="http://www.subsonicproject.com">SubSonic</a>.</p>
<p>So what have I done? I&#8217;ve just gone and created a solution to this problem.</p>
<p>Introducing the ObjectField, a GridView field that allows binding against hierarchical structured objects. In short, it takes a BoundField and splits it on full-stops (periods!) using each element to find an object.</p>
<pre name="code" class="html">&lt;jag:ObjectField DataField=&quot;ContactDetails.TelephoneNumber&quot; /&gt;</pre>
<p>The above is now possible! Huzzah.</p>
<h3>Extras</h3>
<p>There&#8217;s one extra thing you should know about. The field has a couple of additional properties that can be useful.</p>
<p>The first is <code>AllowNulls</code> which defaults to <code>true</code>, this will make the field return silently when a null is encountered anywhere along the object hierarchy; this can be useful if you know that there might be a null somewhere along the lines.</p>
<p>The second property is <code>NullValue</code>, which is displayed by the field when <code>AllowNulls</code> is <code>true</code> and a null is encountered. Setting this value allows you to give a user-friendly message if a value is null.</p>
<h3>Downloads</h3>
<p>The ObjectField is open-source under the <a href="http://en.wikipedia.org/wiki/BSD_licenses">new BSD License</a>; read the license for what you’re allowed to do.</p>
<p class="superseded">
The version of the ObjectField that this post refers to is now out of date. Please go to the <a href="http://blog.jagregory.com/2008/02/21/objectfield-11/">ObjectField 1.1</a> post for the latest version.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/objectfield/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>NHibernate and the SqlTypeException</title>
		<link>http://jagregory.com/writings/nhibernate-and-the-sqltypeexception/</link>
		<comments>http://jagregory.com/writings/nhibernate-and-the-sqltypeexception/#comments</comments>
		<pubDate>Tue, 18 Dec 2007 21:57:02 +0000</pubDate>
		<dc:creator>James Gregory</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://blog.jagregory.com/2007/12/18/nhibernate-and-the-sqltypeexception/</guid>
		<description><![CDATA[NHibernate is a wonderful piece of technology, I love it probably more than is reasonable for code. It does however, occasionally scare you with some seemingly odd behavior. I say seemingly, because every time I&#8217;ve had trouble it&#8217;s actually ended up being my own fault. This is one of those times.
Picture a simple page, with [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.nhibernate.org">NHibernate</a> is a wonderful piece of technology, I love it probably more than is reasonable for code. It does however, occasionally scare you with some seemingly odd behavior. I say seemingly, because every time I&#8217;ve had trouble it&#8217;s actually ended up being my own fault. <em>This is one of those times.</em></p>
<p>Picture a simple page, with a <a href="http://blog.jagregory.com/2007/12/09/delegrid/">DeleGrid</a> control, being bound using NHiberate. Baring in mind how the DeleGrid works, two queries were being executed, one to return the first page of data and another to get the total row-count for the grid. <em>These queries were identical apart from the paging in one, and the projection in the other.</em></p>
<p>Upon execution of the second query, NHibernate was throwing a <code>SqlTypeException</code> for a <code>SqlDateTime</code> overflow. <code>SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM</code>. This was pretty bizarre. Why on earth would the first query succeed (and bring back records, fully populated), but the same query again would die.</p>
<p>A good place to start for NHibernate debugging is always the logs, so I delved in. I discovered NHibernate was attempting to execute an update statement just before it tried the second query. It just kept getting stranger, why would a straightforward query cause an update?</p>
<p>I thought i&#8217;d investigate why the update statement was failing first, then I&#8217;d tackle the problem of why it was even updating at all. Looking at the query I identified the column that was causing the exception, it was (as expected) a <code>DateTime</code> column that was trying to be set to <code>DateTime.MinValue</code>. This exception is thrown because .Net and SQL Server have different ideas over what the minimum value for a <code>DateTime</code> should be.</p>
<p>Now, why would this column be being set at all? Well, it ends up that the column in the database was nullable, but the property in the object wasn&#8217;t. So because <code>DateTime</code> is a value type and cannot be set to <code>null</code>, NHibernate was populating it with the closest value to <code>null</code> as it could manage.</p>
<p>That was the key, as soon as I had that realisation, it was obvious what the problem was.</p>
<p>NHibernate knew that the database had a nullable column, but it had to manage with the non-nullable field on the object. When it came to run the second query, it noticed that the property wasn&#8217;t null as the mapping file said it should be, so it determined the value must have changed. It then attempted to persist those changes before executing the query!</p>
<h4>To break it down</h4>
<ol>
<li>Nullable column pulled into a non-nullable field forces NHibernate to create the smallest value it can.</li>
<li>NHibernate then checks for any changes, expecting a <code>null</code> on that field but finding a value.</li>
<li>Object now considered dirty because value has allegedly changed.</li>
<li>NHibernate performs an update before it pulls back the data agian.</li>
</ol>
<p>So the fix was simply to make the <code>DateTime</code> in the object a <code>DateTime?</code>, a nullable <code>DateTime</code>. That got rid of the false update, and fixed my queries. Simple when you know what the problem is.</p>
<p><strong>So the moral of the story is:</strong> Make sure everything is in sync &#8211; schema, mappings and POCOs.</p>
]]></content:encoded>
			<wfw:commentRss>http://jagregory.com/writings/nhibernate-and-the-sqltypeexception/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
