<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>dotNetChris @ Marisic.Net</title>
	<atom:link href="http://dotnetchris.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dotnetchris.wordpress.com</link>
	<description>C# ASP.Net Development Weblog</description>
	<lastBuildDate>Thu, 25 Jun 2009 14:10:31 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<image>
		<url>http://www.gravatar.com/blavatar/c64eff40b73ced69fd6116053c89c81e?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>dotNetChris @ Marisic.Net</title>
		<link>http://dotnetchris.wordpress.com</link>
	</image>
			<item>
		<title>It&#8217;s been a while!</title>
		<link>http://dotnetchris.wordpress.com/2009/06/25/its-been-a-while/</link>
		<comments>http://dotnetchris.wordpress.com/2009/06/25/its-been-a-while/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 14:10:31 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Off Topic]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=279</guid>
		<description><![CDATA[It&#8217;s definitely been a while since I updated my blog with a new post that&#8217;s going to change starting again today. While this one really won&#8217;t have any new content I just felt like adding some personal thoughts. After my last blog post my software development contract ended unexpectedly which left me with alot of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=279&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>It&#8217;s definitely been a while since I updated my blog with a new post that&#8217;s going to change starting again today. While this one really won&#8217;t have any new content I just felt like adding some personal thoughts. After my last blog post my software development contract ended unexpectedly which left me with alot of free time other than searching for a new contract to work on. My first thoughts were great, a vacation! Which I used to enjoy a few weeks of my time without having to do anything specific which I haven&#8217;t had in my life since probably high school during the summer.  After stepping back for a few weeks I did some casual development on StructuredWeb at home for a little while then started slacking on that. It really is hard to stay focused on the technology world when you&#8217;re not exposed to it every day at work especially since software development (especially when done well) isn&#8217;t easy and takes alot of will and drive to accomplish, well that ends today.</p>
<p>This Monday I started a new position at a small Insurance company / marketing firm to be their lead architect to drive their technology usage and provide them strategic applications far above their previous piecemeal approach with using some outside contracts for their website. I&#8217;m really looking forward to this because finally I don&#8217;t have to answer or justify using new technology or different technology (to an extent atleast) for solving software problems. Nothing has ever bothered me more in previous jobs at larger companies where most developers just choose mediocrity at best, or to be abysmal at worst and just don&#8217;t care to learn anything new as developers and to just apply bad practices to problems because that&#8217;s what they&#8217;re familiar with.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/279/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=279&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/06/25/its-been-a-while/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a generic Model-View-Presenter framework</title>
		<link>http://dotnetchris.wordpress.com/2009/02/16/creating-a-generic-model-view-presenter-framework/</link>
		<comments>http://dotnetchris.wordpress.com/2009/02/16/creating-a-generic-model-view-presenter-framework/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 03:54:31 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[StructuredWeb]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Model View Presenter]]></category>
		<category><![CDATA[MVP]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=268</guid>
		<description><![CDATA[With all of the current talk about ASP.NET MVC it seem dated to bring up the model view presenter architecture but I still believe it&#8217;s a very strong pattern in separating UI logic from application design. This post is meant to offer a successor to the Web Client Software Factory (WCSF) framework provided by Microsoft. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=268&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>With all of the current talk about ASP.NET MVC it seem dated to bring up the model view presenter architecture but I still believe it&#8217;s a very strong pattern in separating UI logic from application design. This post is meant to offer a successor to the Web Client Software Factory (WCSF) framework provided by Microsoft. In last usage of WCSF I encountered numerous errors stemming from ObjectBuilder during the dependency injection of WCSF which is what lead me down the road of creating UnityWeb which has evolved into StructuredWeb. The rest of this post will include no specific dependencies except 1 to <a href="http://dotnetchris.wordpress.com/structuredweb/">StructureMap </a>to handle the actual resolution of objects through dependency injection. This could be very easily replaced by Unity or any other inversion of control framework that supports the BuildUp() method. For a framework that does not support a BuildUp operation it will make things more complicated and that will need to be solved by your case basis.</p>
<p>Firstly, what is the model-view-presenter (MVP) pattern? The View is defined as an interface that the Presenter will use for getting and setting data to and from the Model. The View implementation will instantiate the Presenter object and provide a reference to itself (the formal constructor parameter is the View interface while the actual parameter is a concrete View class). When the event methods of the View are triggered, they will do nothing but invoke a method of the Presenter which has no parameters and no return value. The Presenter will then get data from the View, through the View interface variable that the Presenter stored when the constructor was called. The Presenter then invokes methods of the Model, and sets data from the Model into the View through the View interface.</p>
<p>From a layering point of view, the Presenter class might be considered as belonging to the application layer in a multilayered architectured object-oriented system with common layers but it can also be seen as a Presenter layer of its own between the Application layer and the User Interface layer. [source: <a href="http://en.wikipedia.org/wiki/Model_View_Presenter">Wikipedia</a>]</p>
<p>Now if you&#8217;re at all like me you will have almost no more of an idea what the MVP pattern is supposed to do after that explanation. To generalize on that statement it&#8217;s basically taking the interaction of the UI and the application logic which usually is coupled together and separating it into 3 areas.</p>
<p>The model &#8211; this is the application logic which will be housed in controller classes.</p>
<p>The view &#8211; which is an interface which abstracts the UI away, all data sent and retrieved from the UI is done through this interface</p>
<p>The presenter &#8211; this is a mediator that negotiates how the UI and application logic interact. The view is also a composition of this class.</p>
<p>Starting with the view:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> interface IView
{
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This is the most basic of the basic of interfaces, for my needs it&#8217;s purely a <a href="http://en.wikipedia.org/wiki/Marker_interface_pattern">marker interface</a>. If every single one of your pages shares a common property perhaps an event message collection this would be a good place to define a property for it.</p>
<p>The presenter class:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> abstract <span style="color:blue;">class</span> Presenter&lt;TView&gt; where TView : IView
{
    <span style="color:blue;">public</span> TView View { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    <span style="color:blue;">public</span> virtual <span style="color:blue;">void</span> OnViewInitialized()
    {
    }

    <span style="color:blue;">public</span> virtual <span style="color:blue;">void</span> OnViewLoaded()
    {
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>The OnViewInitialized method is to represent any operations you would execute in Page_Load if(Page.IsPostback == false) so only on the initial page load. The OnViewLoaded method represents all page loads whether or not they are post backs. Currently I have no global page operations since I have no global view properties. This class is also constrainted that</p>
<p>Next creating a view:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> interface IEmployeeView: IView
{
    IList&lt;Employee&gt; Employees { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    IList&lt;Employee&gt; EmployeesListDatasource { <span style="color:blue;">set</span>; }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>As you can see my view will have 2 properties one for getting or setting a collection and another for setting only the same type. The view also implements the marker interface IView.</p>
<p>Creating the presenter:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">class</span> EmployeePresenter : Presenter&lt;IEmployeeView&gt;
{
    <span style="color:blue;">private</span> readonly IEmployeeController _controller;

    <span style="color:blue;">public</span> EmployeePresenter(IEmployeeController controller)
    {
        _controller = controller;
    }

    <span style="color:blue;">public</span> override <span style="color:blue;">void</span> OnViewInitialized()
    {
        View.Employees = _controller.GetEmployees();
    }

    <span style="color:blue;">public</span> override <span style="color:blue;">void</span> OnViewLoaded()
    {
        View.EmployeesListDatasource = View.Employees;
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>I&#8217;m not going to go into the details of the IEmployeeController this is the &#8220;model&#8221; where actual application code is ran there is nothing special about this class or it&#8217;s interface and only contains logic specific to getting my set of employees. As you can see the EmployeePresenter implements Presenter. I overrided both of the methods provided by the Presenter base where the Initialize method gets list from the model and the loaded method binds the list to a datasource.</p>
<p>Now before I move onto implementing the IEmployeeView inside a page I&#8217;m going to create an abstract base page that will handle the dependency injection build up for my MVP framework.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> abstract <span style="color:blue;">class</span> ViewBasePage&lt;TPresenter, TView&gt; : Page
    where TPresenter : Presenter&lt;TView&gt;
    where TView : IView
{
    <span style="color:blue;">protected</span> TPresenter _presenter;

    <span style="color:blue;">public</span> TPresenter Presenter
    {
        <span style="color:blue;">set</span>
        {
            _presenter = value;
            _presenter.View = GetView();
        }
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Gets the view. This will get the page during the ASP.NET</span>
    <span style="color:green;">/// life cycle where the physical page inherits the view</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span style="color:blue;">private</span> <span style="color:blue;">static</span> TView GetView()
    {
        <span style="color:blue;">return</span> (TView) HttpContext.Current.Handler;
    }

    <span style="color:blue;">protected</span> override <span style="color:blue;">void</span> OnPreInit(EventArgs e)
    {
        ObjectFactory.BuildUp(<span style="color:blue;">this</span>);
        <span style="color:blue;">base</span>.OnPreInit(e);
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This class might look quite a bit strange, the majority of it is from the class definition it&#8217;s setup to only allow you to inherit it in a valid way such as: ViewBasePage&lt;EmployeePresenter,IEmployeeView&gt;. On the Presenter set method this is where the page actually becomes part of the composition of the Presenter (the description from Wikipedia said this).</p>
<p>The GetView method also probably looks strange what this is doing is getting the physical page that&#8217;s being instantiated by ASP.NET. The reason I&#8217;m doing this is it makes it easier to reference the page generically otherwise I would be required to do something smilar to</p>
<p>return (TView) (object) this</p>
<p>Which is borderline wrong since THIS technically refers to the ViewBasePage which does not implement the interface that TView consists of but at runtime eventually resolves correctly since a Page will implement the interface that makes up TView and not cause a runtime error.</p>
<p>This class overrides Page&#8217;s OnPreInit method to call ObjectFactory.BuildUp() which will cause all the dependency resolution to take place. In my specific usage of StructureMap I have it identify all Presenter properties as targets for dependency injection, in your case you may be required to use the [Setter] attribute from SturctureMap or the [Dependency] attribute from Unity or some other similar convention in other inversion of control frameworks.</p>
<p>Now finally onto the actual page.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> partial <span style="color:blue;">class</span> _Default :
    ViewBasePage&lt;EmployeePresenter, IEmployeeView&gt;, IEmployeeView
{
    <span style="color:blue;">protected</span> <span style="color:blue;">void</span> Page_Load(object sender, EventArgs e)
    {
        <span style="color:blue;">if</span> (!Page.IsPostBack)
        {
            _presenter.OnViewInitialized();
        }

        _presenter.OnViewLoaded();
        Page.DataBind();
    }

    #region Implementation of IEmployeeView

    IList&lt;Employee&gt; IEmployeeView.Employees
    {
        <span style="color:blue;">get</span> { <span style="color:blue;">return</span> ViewState["IEmployeeView.Employees"] as IList&lt;Employee&gt;; }
        <span style="color:blue;">set</span> { ViewState["IEmployeeView.Employees"] = value; }
    }

    IList&lt;Employee&gt; IEmployeeView.EmployeesListDatasource
    {
        <span style="color:blue;">set</span> { lstEmployees.DataSource = value; }
    }

    #endregion
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This class inherits the ViewBasePage class and implements the IEmployeeView. The _presenter field is in the ViewBasePage and contains the fully resolved dependency to EmployeePresenter. As I stated in the portion of the presenter code you can see where OnViewInitialized() and OnViewLoaded() are called inside the page life cycle.</p>
<p>Implementing the IEmployeeView you have the properties target actual controls on the page or the ViewState / QueryString etc that is available to the page. Now if you remember the code in my actual EmployeePresenter it should make sense why in ViewInitialized the Employees property is set by the controller and on the ViewLoaded the Employees property is assigned to the EmployeesListDatasource since it&#8217;s just refreshing the data source to the view state collection on subsequent page post backs.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f02%2f16%2fcreating-a-generic-model-view-presenter-framework%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f02%2f16%2fcreating-a-generic-model-view-presenter-framework%2f&amp;bgcolor=0066FF" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Creating-a-generic-Model-View-Presenter-framework-dotNetChris-Marisicnet"><img style="border:0;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F02%2F16%2Fcreating-a-generic-model-view-presenter-framework%2F" alt="Shout it" /></a></p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/268/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/268/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/268/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=268&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/02/16/creating-a-generic-model-view-presenter-framework/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f02%2f16%2fcreating-a-generic-model-view-presenter-framework%2f&#38;bgcolor=0066FF" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F02%2F16%2Fcreating-a-generic-model-view-presenter-framework%2F" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a generic validation framework</title>
		<link>http://dotnetchris.wordpress.com/2009/02/11/creating-a-generic-validation-framework/</link>
		<comments>http://dotnetchris.wordpress.com/2009/02/11/creating-a-generic-validation-framework/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 22:25:07 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[StructuredWeb]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=260</guid>
		<description><![CDATA[Recently in a few discussions of system architecture I have brought up adamant complaints about coupling validation logic to your domain objects. This weekend Thomas Mayfield contacted me on how I would go about implementing this in a domain driven designed system. Initially I got sidetracked over what tool I would use for my rules [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=260&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Recently in a few discussions of system architecture I have brought up adamant complaints about coupling validation logic to your domain objects. This weekend Thomas Mayfield contacted me on how I would go about implementing this in a domain driven designed system. Initially I got sidetracked over what tool I would use for my rules engine and I&#8217;ve still not concluded which would be best so I went about creating my Validation layer and decided to leave the specific details of creating validation logic for later.</p>
<p>As always I start with an interface. In this case it ends up being a very simple interface.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> interface IValidator&lt;T&gt;
{
    ValidationResult Validate(T obj);
    ValidationResult Validate(T obj, <span style="color:blue;">bool</span> suppressWarnings);
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Basically I want this service to take in an object and validate it, and then return to me whether it&#8217;s valid and any warnings or error messages associated with the validation. Which lead me to creating a ValidationResult class (in lieu of the similarly named class in the Enterprise Library validation block).</p>
<p>First I created a very simple ValidationMessage class:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> sealed <span style="color:blue;">class</span> ValidationMessage
{
    <span style="color:blue;">public</span> <span style="color:blue;">string</span> Message { <span style="color:blue;">get</span>; internal <span style="color:blue;">set</span>; }
    <span style="color:blue;">public</span> <span style="color:blue;">bool</span> Warning { <span style="color:blue;">get</span>; internal <span style="color:blue;">set</span>; }

    <span style="color:green;">//Only allow creation internally or by ValidationResult class.</span>
    internal ValidationMessage()
    {
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>The ValidationResult class is a little more complex:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> sealed <span style="color:blue;">class</span> ValidationResult
{
    <span style="color:blue;">private</span> <span style="color:blue;">bool</span> _dirty = <span style="color:blue;">true</span>;
    <span style="color:blue;">private</span> <span style="color:blue;">bool</span> _valid;

    <span style="color:blue;">public</span> <span style="color:blue;">bool</span> Valid
    {
        <span style="color:blue;">get</span>
        {
            <span style="color:green;">//theoretically O(n) time but in pratice will be constant time</span>
            <span style="color:green;">//Still, no need for multiple traversals, Traverse only if it's changed</span>
            <span style="color:blue;">if</span> (_dirty)
            {
                _valid = Messages.FirstOrDefault(msg =&gt; msg.Warning == <span style="color:blue;">false</span>) == <span style="color:blue;">null</span>;
                _dirty = <span style="color:blue;">false</span>;
            }

            <span style="color:blue;">return</span> _valid;
        }
    }

    <span style="color:blue;">public</span> ValidationResult()
    {
        Messages = <span style="color:blue;">new</span> List&lt;ValidationMessage&gt;();
    }

    <span style="color:blue;">public</span> IList&lt;ValidationMessage&gt; Messages { <span style="color:blue;">get</span>; internal <span style="color:blue;">set</span>; }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Adds the error. </span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="errorMessage"&gt;The error message.&lt;/param&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> AddError(<span style="color:blue;">string</span> errorMessage)
    {
        _dirty = <span style="color:blue;">true</span>;
        Messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = errorMessage});
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Adds the warning. </span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="warningMessage"&gt;The warning message.&lt;/param&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> AddWarning(<span style="color:blue;">string</span> warningMessage)
    {
        <span style="color:green;">//No need to mark collection dirty since warnings never generate validation changes</span>
        Messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = warningMessage, Warning = <span style="color:blue;">true</span>});
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Basically the only tricks to this class is that I only allow the creation of the internal list of ValidationMessages to be handled by the same assembly. I also appended factory methods to allow manual insertion of errors or warnings. The reason for this is in my workings with EntLib VAB was that the results were inflexible in letting me append some messages myself and then roll the results down to the screen. This resulted in me having to create marshaling  classes to just transfer the messages from the results to a collection that I could add more information to.</p>
<p>Implementing a concrete validator, the EmployeeValidator:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">class</span> EmployeeValidator : IValidator&lt;Employee&gt;
{
    #region Implementation of IValidation&lt;Employee&gt;

    <span style="color:blue;">public</span> ValidationResult Validate(Employee employee)
    {
        <span style="color:blue;">return</span> Validate(employee, <span style="color:blue;">false</span>);
    }

    <span style="color:blue;">public</span> ValidationResult Validate(Employee employee, <span style="color:blue;">bool</span> suppressWarnings)
    {
        var result = <span style="color:blue;">new</span> ValidationResult();

        <span style="color:green;">//This code here would be replaced with a validation rules engine later</span>

        <span style="color:blue;">if</span> (employee != <span style="color:blue;">null</span>)
        {
            <span style="color:blue;">if</span> (!suppressWarnings &amp;&amp; employee.HireDate &gt; DateTime.Now)
                result.Messages.Add(<span style="color:blue;">new</span> ValidationMessage {
                    Message = <span style="color:blue;">string</span>.Format("Employee hire date: {0} is <span style="color:blue;">set</span> <span style="color:blue;">in</span> the future.", employee.HireDate),
                    Warning = <span style="color:blue;">true</span>});

            <span style="color:blue;">if</span> (employee.Person != <span style="color:blue;">null</span>)
            {
                <span style="color:blue;">if</span> (<span style="color:blue;">string</span>.IsNullOrEmpty(employee.Person.FirstName))
                    result.Messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = "Employee FirstName is required."});
                <span style="color:blue;">if</span> (<span style="color:blue;">string</span>.IsNullOrEmpty(employee.Person.LastName))
                    result.Messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = "Employee LastName is required."});
            }
            <span style="color:blue;">else</span>
                result.Messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = "Employee person data is missing."});
        }
        <span style="color:blue;">else</span>
            result.Messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = "Employee data is missing."});

        <span style="color:blue;">return</span> result;
    }

    #endregion
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Nothing really complicated goes on here just simple very basic validation code that rolls in error messages if needed. This area here would be replaced by a ruleset engine later on, for myself atleast. Otherwise you could do any validation you wanted here.</p>
<p>Now to actually validate your objects I created a ValidationFactory method also simliar to the VAB.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">class</span> ValidationFactory
{
    <span style="color:blue;">public</span> <span style="color:blue;">static</span> ValidationResult Validate&lt;T&gt;(T obj)
    {
        <span style="color:blue;">try</span>
        {
            var validator = ObjectFactory.GetInstance&lt;IValidator&lt;T&gt;&gt;();
            <span style="color:blue;">return</span> validator.Validate(obj);
        }
        <span style="color:blue;">catch</span> (Exception ex)
        {
            var messages = <span style="color:blue;">new</span> List&lt;ValidationMessage&gt; {<span style="color:blue;">new</span> ValidationMessage {
                Message = <span style="color:blue;">string</span>.Format("Error validating {0}", obj)}};

            messages.AddRange(FlattenError(ex));

            var result = <span style="color:blue;">new</span> ValidationResult {Messages = messages};
            <span style="color:blue;">return</span> result;
        }
    }

    <span style="color:blue;">private</span> <span style="color:blue;">static</span> IEnumerable&lt;ValidationMessage&gt; FlattenError(Exception exception)
    {
        var messages = <span style="color:blue;">new</span> List&lt;ValidationMessage&gt;();
        var currentException = exception;

        do
        {
            messages.Add(<span style="color:blue;">new</span> ValidationMessage {Message = exception.Message});
            currentException = currentException.InnerException;
        } <span style="color:blue;">while</span> (currentException != <span style="color:blue;">null</span>);

        <span style="color:blue;">return</span> messages;
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Once again beauty comes with simplicity I take advantage of StructureMap to handle my dependency injection with the GetInstance method. Then just call Validate. I added a helper method that will allow me to roll out a complex exception message (most likely it&#8217;d only ever be you forgot to register a validator for some type) if any occur.</p>
<p>Registering this for StructureMap  is extremely simple inside you registry setup for SM you would just add</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">ForRequestedType&lt;IValidator&lt;Employee&gt;&gt;().TheDefaultIsConcreteType&lt;EmployeeValidator&gt;();
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>And then onto a quick usage example</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">[Test]
<span style="color:blue;">public</span> <span style="color:blue;">void</span> InvalidEmployeeTest()
{
    var employee = <span style="color:blue;">new</span> Employee {Person = <span style="color:blue;">new</span> Person {FirstName = <span style="color:blue;">string</span>.Empty, LastName = <span style="color:blue;">string</span>.Empty}};

    var results = ValidationFactory.Validate(employee);

    Assert.IsNotNull(results);
    Assert.IsFalse(results.Valid);
    Assert.IsTrue(results.Messages.Count &gt; 0);
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>At this point you have en entirely decoupled validation framework that will allow you to validate your objects with any kit, ruleset engine, or static validation you wish. Now if you wondered where I would put this in my architecture I would have it validate at the presenter level right after the screen scrape of data.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">bool</span> SaveEmployee()
{
    var employee = View.Employee;

    var results = ValidationFactory.Validate(employee);

    <span style="color:blue;">if</span> (results.Valid)
        _controller.SaveEmployee(employee);
    <span style="color:blue;">else</span>
        View.Errors = results.Messages;
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f02%2f11%2fcreating-a-generic-validation-framework%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f02%2f11%2fcreating-a-generic-validation-framework%2f&amp;bgcolor=0066FF" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Creating-a-generic-validation-framework"><img style="border:0;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F02%2F11%2Fcreating-a-generic-validation-framework%2F" alt="Shout it" /></a></p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/260/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=260&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/02/11/creating-a-generic-validation-framework/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f02%2f11%2fcreating-a-generic-validation-framework%2f&#38;bgcolor=0066FF" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F02%2F11%2Fcreating-a-generic-validation-framework%2F" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>20,000 views!</title>
		<link>http://dotnetchris.wordpress.com/2009/02/03/20000-views/</link>
		<comments>http://dotnetchris.wordpress.com/2009/02/03/20000-views/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 13:49:41 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Off Topic]]></category>
		<category><![CDATA[20000 views]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=254</guid>
		<description><![CDATA[Wow, I honestly feel pride. A year ago when I started my blog I never imagined this is where it would be at today. At first I started it to share the information I learned about the problems I faced with Oracle since I spent over 3 days trying to accomplish a simple task of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=254&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Wow, I honestly feel pride. A year ago when I started my blog I never imagined this is where it would be at today. At first I started it to share the information I learned about the problems I faced with Oracle since I spent over 3 days trying to accomplish a simple task of writing an xml string to oracle over 2,000 characters! When I initially wrote that post, my blog had the only conclusive answer that I could find as I had to spend lots of time searching both java and microsoft forums related to oracle to get any information.</p>
<p>Since then I&#8217;ve watched my blog grow from a handful of visitors and a few comments to 20,000 views and over 100 comments. I want to thank everyone of you that&#8217;s taken the time to read any of rantings or design ideas and I especially want to thank every person that has taken the time to offer input on anything I&#8217;ve wrote. See you all again at 50,000!</p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/254/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=254&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/02/03/20000-views/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>
	</item>
		<item>
		<title>StructuredWeb Alpha 1</title>
		<link>http://dotnetchris.wordpress.com/2009/02/03/structuredweb-alpha-1/</link>
		<comments>http://dotnetchris.wordpress.com/2009/02/03/structuredweb-alpha-1/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 05:14:34 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[StructuredWeb]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Fluent-Nhibernate]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Model View Presenter]]></category>
		<category><![CDATA[MVP]]></category>
		<category><![CDATA[nHibernate]]></category>
		<category><![CDATA[Object Orientated Design]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Practices]]></category>
		<category><![CDATA[Repository]]></category>
		<category><![CDATA[Seperation of Concerns]]></category>
		<category><![CDATA[StructuredMap]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=251</guid>
		<description><![CDATA[After my long road down the rabbit hole of object orientated design, inversion of control, NHibernate, Fluent NHibernate I&#8217;ve finally reached a point where I feel my codebase is stable enough to almost warrant my beta 1 release. I switched from Unity as my DI container to StructureMap and definitely feel this was a good [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=251&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>After my long road down the rabbit hole of object orientated design, inversion of control, NHibernate, Fluent NHibernate I&#8217;ve finally reached a point where I feel my codebase is stable enough to almost warrant my beta 1 release. I switched from Unity as my DI container to StructureMap and definitely feel this was a good call especially the timing of the 2.5.3 release of StructureMap where it natively includes the BuildUp method and natively includes the functionality I had to add with custom lifetime managers for wrapping my objects into the HttpContext and HtttpSession.</p>
<p>Just recently I published my implementation of Business Conversation per Transaction session management along with my repository pattern I followed for StructuredWeb. I still haven&#8217;t gotten my second level caching for NHibernate running yet but that will on slate for Beta 2.</p>
<p>See my <a href="http://dotnetchris.wordpress.com/structuredweb-installation/">StructuredWeb Installation</a> page for details for setting it up.</p>
<p>This still needs a little bit of work for me to qualify it as a beta but since I checked everything into Assembla I figured I&#8217;d announce it&#8217;s alpha release since the code is already available online.</p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/251/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=251&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/02/03/structuredweb-alpha-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a common generic and extensible NHiberate Repository</title>
		<link>http://dotnetchris.wordpress.com/2009/01/28/creating-a-common-generic-and-extensible-nhiberate-repository/</link>
		<comments>http://dotnetchris.wordpress.com/2009/01/28/creating-a-common-generic-and-extensible-nhiberate-repository/#comments</comments>
		<pubDate>Wed, 28 Jan 2009 19:22:48 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[StructuredWeb]]></category>
		<category><![CDATA[UnityWeb]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DAL]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Data provider]]></category>
		<category><![CDATA[Encapsulation]]></category>
		<category><![CDATA[IRepository]]></category>
		<category><![CDATA[nHibernate]]></category>
		<category><![CDATA[Object Orientated Design]]></category>
		<category><![CDATA[OOD]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=240</guid>
		<description><![CDATA[In my previous post Conversation Per Business Transaction using PostSharp and IoC I dealt with the session management aspect of NHiberate however by the end of my development of the business conversation aspect I realized that my current data provider scheme created a lot of duplicate code. As we all know any code that is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=240&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In my previous post <a href="http://dotnetchris.wordpress.com/2009/01/27/conversation-per-business-transaction-using-postsharp-and-ioc/">Conversation Per Business Transaction using PostSharp and IoC</a> I dealt with the session management aspect of NHiberate however by the end of my development of the business conversation aspect I realized that my current data provider scheme created a lot of duplicate code. As we all know any code that is duplicated becomes a nightmare to maintain so I went through and refactored first a truly generic repository.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> interface IRepository&lt;T&gt;
{
    ICriteria GetAll();
    T Get&lt;U&gt;(U id);
    <span style="color:blue;">void</span> Save(T obj);
    ICriteria GetRange(<span style="color:blue;">int</span> resultSet, <span style="color:blue;">int</span> rangeSize);
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This is a rather basic interface that will handle the most common operations to my data providers, currently it can handle getting all of the items in my database for a type, a page collection into the list of items in my database, get a specific item and save a new item (or update an existing item). The only minorly unsightly part is the Get&lt;U&gt; method this just allows passing any type of ID instead of declaring it as int statically.</p>
<p>On to implementing the interface:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">class</span> Repository&lt;T&gt; : IRepository&lt;T&gt;
{
    <span style="color:blue;">private</span> readonly IConversation _conversation;

    <span style="color:blue;">public</span> Repository(IConversation conversation)
    {
        _conversation = conversation;
    }

    #region IRepository&lt;T&gt; Members

    </span><span style="font-family:Courier New;color:black;font-size:small;">ICriteria</span><span style="font-family:Courier New;color:black;font-size:small;"> IRepository&lt;T&gt;.GetAll()
    {
        <span style="color:blue;">return</span> _conversation.Session.CreateCriteria(typeof (T))
            <span style="color:green;">//.SetCacheable(true)</span>
            <span style="color:green;">//.SetCacheMode(CacheMode.Normal)</span>
            ;
    }

    T IRepository&lt;T&gt;.Get&lt;U&gt;(U id)
    {
        <span style="color:blue;">return</span> _conversation.Session.Get&lt;T&gt;(id);
    }

    <span style="color:blue;">void</span> IRepository&lt;T&gt;.Save(T obj)
    {
        _conversation.Session.SaveOrUpdate(obj);
    }

    </span><span style="font-family:Courier New;color:black;font-size:small;">ICriteria</span><span style="font-family:Courier New;color:black;font-size:small;"> IRepository&lt;T&gt;.GetRange(<span style="color:blue;">int</span> resultSet, <span style="color:blue;">int</span> rangeSize)
    {
        <span style="color:blue;">return</span> _conversation.Session.CreateCriteria(typeof (T))
            <span style="color:green;">//.SetCacheable(true)</span>
            <span style="color:green;">//.SetCacheMode(CacheMode.Normal)</span>
            .SetFirstResult(resultSet*rangeSize)
            .SetMaxResults(rangeSize - 1)
            ;
    }

    #endregion
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p><a></a></p>
<p>This class contains rather basic interactions with NHiberate, if you&#8217;re not familiar with the CreateCriteria querying method in NHibernate take a look at <a href="http://www.hibernate.org/hib_docs/nhibernate/html/querycriteria.html">Chapter 12. Criteria Queries</a>. Other than that I can at an application level enable or disable output caching for my generic repository, currently I&#8217;m still working on getting my second level caching implementation working so right now I have it disabled as you can see it&#8217;s commented out.</p>
<p>By returning the ICriteria from the repository it allows us to pass on the full power of NHibernate and allow us to create further data provider specific queries.</p>
<p>Next I created an abstract base class for my actual data providers:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> abstract <span style="color:blue;">class</span> DataProviderBase&lt;T&gt;
{
    <span style="color:blue;">protected</span> readonly IConversation _conversation;
    <span style="color:blue;">protected</span> readonly IRepository&lt;T&gt; _repoistory;

    <span style="color:blue;">protected</span> DataProviderBase(IConversation conversation)
    {
        _conversation = conversation;
        _repository = <span style="color:blue;">new</span> Repository&lt;T&gt;(_conversation);
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This base class just holds the fields for the business conversation (or ISession) and my newly created generic repository. Now on to my true concrete implementation of my data provider:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">class</span> EmployeeDataProvider : DataProviderBase&lt;Employee&gt;, IEmployeeDataProvider
{
    [InjectionConstructor]
    <span style="color:blue;">public</span> EmployeeDataProvider(IConversation conversation) : <span style="color:blue;">base</span>(conversation)
    {
    }

    #region IEmployeeDataProvider Members

    IList&lt;Employee&gt; IEmployeeDataProvider.GetAll()
    {
        <span style="color:blue;">return</span> _repository.GetAll().List&lt;Employee&gt;();
    }

    IList&lt;Employee&gt; IEmployeeDataProvider.GetRange(<span style="color:blue;">int</span> resultSet, <span style="color:blue;">int</span> rangeSize)
    {
        <span style="color:blue;">return</span> _repository.GetRange(resultSet, rangeSize).List&lt;Employee&gt;();
    }

    Employee IEmployeeDataProvider.Get(<span style="color:blue;">int</span> employeeId)
    {
        <span style="color:blue;">return</span> _repository.Get(employeeId);
    }

    <span style="color:blue;">void</span> IEmployeeDataProvider.Save(Employee employee)
    {
        _repository.Save(employee);
    }

    IList&lt;Territory&gt; IEmployeeDataProvider.GetTerritories()
    {
        <span style="color:blue;">return</span> _conversation.Session.CreateCriteria(typeof (Territory)).List&lt;Territory&gt;();
    }

    #endregion
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>In this class we have the delegation of the IRepository (sitting in the abstract base) and we also have direct access to the NHibernate Session so we can add further methods of any kind. This also allows us the flexibility if you&#8217;d rather the EmployeeDataProvider had GetEmpoyees() instead of GetAll() it would allow that easily.</p>
<p>Since the repository itself is not exposed at the provider level this allows us to return the actual results in anyway we want. It allows us to further modify the basic queries by adding NHibernate where clauses to the Criteria if we so choose. Since the actual ICriteria won&#8217;t be exposed outside of the data provider we don&#8217;t need to worry about client interactions causing database usage. This would also allow us if we added NHibernate LINQ to not be concerned with returning the Queryable results for the same reason.</p>
<p>This pattern would also work directly with LINQ2SQL / LINQ2Entities / DLINQ by changing where the NHibernate session is dealt with and using your entity provider. I feel this is a perfect to the data access patern as it protects the code from becoming too unweilding by basing all communication directly through the ICriteria and giving our data providers concrete result lists.</p>
<p>Let me know what you think!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f01%2f28%2fcreating-a-common-generic-and-extensible-nhiberate-repository%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f01%2f28%2fcreating-a-common-generic-and-extensible-nhiberate-repository%2f&amp;bgcolor=0066FF" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Creating-a-common-generic-and-extensible-NHiberate-Repository"><img style="border:0;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F01%2F28%2Fcreating-a-common-generic-and-extensible-nhiberate-repository%2F" alt="Shout it" /></a></p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=240&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/01/28/creating-a-common-generic-and-extensible-nhiberate-repository/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f01%2f28%2fcreating-a-common-generic-and-extensible-nhiberate-repository%2f&#38;bgcolor=0066FF" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F01%2F28%2Fcreating-a-common-generic-and-extensible-nhiberate-repository%2F" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>Conversation Per Business Transaction using PostSharp and IoC</title>
		<link>http://dotnetchris.wordpress.com/2009/01/27/conversation-per-business-transaction-using-postsharp-and-ioc/</link>
		<comments>http://dotnetchris.wordpress.com/2009/01/27/conversation-per-business-transaction-using-postsharp-and-ioc/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 21:11:07 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[StructuredWeb]]></category>
		<category><![CDATA[UnityWeb]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Conversation Per Business Transaction]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[nHibernate]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[Session Management]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=230</guid>
		<description><![CDATA[Earlier this month I encountered the notion of the Conversation per Business transaction paradigm for NHibernate session management as the overrall successor to the session per request pattern. With my exploration on this topic I found it quite confusing to implement in the only existing examples of it. Which is why I wrote a simple [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=230&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Earlier this month I encountered the notion of the Conversation per Business transaction paradigm for NHibernate session management as the overrall successor to the session per request pattern. With my exploration on this topic I found it quite confusing to implement in the only existing examples of it. Which is why I wrote a simple version for myself leveraging inversion of control and PostSharp.</p>
<p>Firstly,  everything drives off an IConversation:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> interface IConversation
{
    <span style="color:blue;">void</span> Start();
    <span style="color:blue;">void</span> Pause();
    <span style="color:blue;">void</span> Resume();
    <span style="color:blue;">void</span> End();
    <span style="color:blue;">void</span> Abort();
    ISession Session { <span style="color:blue;">get</span>; }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>The conversation is a fairly simple idea, just as in a real life conversation you have a start to it, you can pause the conversation (which is how to commit the conversations), resume the conversation, end the conversation and abort the conversation. Imagine the scenario of a school class and students who have learning commited to their memory. A day could follow a similar context as this:</p>
<p>8:00 Class starts<br />
Math is taught, Science is taught<br />
12:00 Class is paused for recess (all information is committed)<br />
13:00 Class is resumed<br />
Creationism is taught, but realized to be made up and Class is aborted<br />
14:00 Class is started again<br />
More subjects are taught<br />
15:00 Class is ended and all information flushed to students long term memory.</p>
<p>This example is fairly contrived but if you replace students with the database and act of class being taught with the conversation it should be pretty clear a flow that could occur over a single session for a conversation.</p>
<p>Next is the actual implementation of the Conversation class.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">class</span> Conversation : IConversation, IDisposable
{
    <span style="color:blue;">private</span> readonly INHibernateSessionManager _sessionManager;

    <span style="color:blue;">public</span> ISession Session { <span style="color:blue;">private</span> <span style="color:blue;">set</span>; <span style="color:blue;">get</span>; }

    [InjectionConstructor]
    <span style="color:blue;">public</span> Conversation(INHibernateSessionManager sessionManager)
    {
        _sessionManager = sessionManager;
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Starts this instance.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> Start()
    {
        <span style="color:blue;">if</span> (Session != <span style="color:blue;">null</span> &amp;&amp; (Session.IsOpen || Session.IsConnected))
        {
            Abort();
        }
        Session = _sessionManager.GetSession(FlushMode.Never);
        Resume();
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Pauses this instance.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> Pause()
    {
        Commit(Session);

    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Resumes this instance.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> Resume()
    {
        <span style="color:blue;">if</span> (Session == <span style="color:blue;">null</span>)
            Start();

        <span style="color:blue;">if</span> (Session == <span style="color:blue;">null</span>)
            throw <span style="color:blue;">new</span> AccessViolationException("Session could not be created");

        <span style="color:blue;">if</span> (!Session.IsConnected)
        {
            Session.Reconnect();
        }
        Session.BeginTransaction();
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Ends this instance.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> End()
    {
        <span style="color:blue;">if</span> (Session == <span style="color:blue;">null</span> || !Session.IsOpen) <span style="color:blue;">return</span>;

        FlushAndCommit(Session);
        Session.Close();
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Aborts this instance.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">void</span> Abort()
    {
        <span style="color:blue;">if</span> (Session == <span style="color:blue;">null</span> || !Session.IsOpen) <span style="color:blue;">return</span>;

        <span style="color:blue;">if</span> (Session.Transaction != <span style="color:blue;">null</span> &amp;&amp; Session.Transaction.IsActive)
        {
            Session.Transaction.Rollback();
        }
        Session.Close();
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Commits the specified session.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="session"&gt;The session.&lt;/param&gt;</span>
    <span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> Commit(ISession session)
    {
        <span style="color:blue;">if</span> (session.Transaction != <span style="color:blue;">null</span> &amp;&amp; session.Transaction.IsActive)
        {
            session.Transaction.Commit();
        }
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Flushes the and commit.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="session"&gt;The session.&lt;/param&gt;</span>
    <span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> FlushAndCommit(ISession session)
    {
        <span style="color:blue;">if</span> (session.Transaction == <span style="color:blue;">null</span> || !session.Transaction.IsActive) <span style="color:blue;">return</span>;

        session.Flush();
        session.Transaction.Commit();
    }

    #region Implementation of IDisposable

    <span style="color:blue;">public</span> <span style="color:blue;">void</span> Dispose()
    {
        End();
    }

    #endregion
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This class is a little bit long but nothing is that complex and I think every method is very straight forward. I&#8217;m going to skip over a few things that are not needed for understanding what this class does. The INHibernateSessionManager is an interface to a class that is a basically a wrapper to NHibernate&#8217;s ISessionFactory. For all intensive purposes this class could be ISessionFactory instead and the implementation wouldn&#8217;t change other than it would be session = Factory.OpenSession(); session.FlushMode = FlushMode.Never;</p>
<p>The InjectionConstructor attribute is a Microsoft Unity (<a href="http://en.wikipedia.org/wiki/Inversion_of_control">Inversion of Control</a> framework) specific convention that informs Unity to inject the NHibernate SessionFactory dependency into a Conversation anytime it is created. Unity will store a singleton copy of the SessionFactory for the life of the application.</p>
<p>Next up is the DataProvider class that will actually use the Conversation to talk to the database physically.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:blue;">public</span> <span style="color:blue;">class</span> EmployeeDataProvider : IEmployeeDataProvider
{
    <span style="color:blue;">private</span> readonly IConversation _conversation;

    [InjectionConstructor]
    <span style="color:blue;">public</span> EmployeeDataProvider(IConversation conversation)
    {
        _conversation = conversation;
    }

    IList&lt;Employee&gt; IEmployeeDataProvider.GetEmployees()
    {
        <span style="color:blue;">return</span> _conversation.Session.CreateCriteria(typeof (Employee)).List&lt;Employee&gt;();
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>This is a very basic method that is used with NHiberate, it&#8217;s the syntax to get a list of objects from the database. I have some other methods in my provider but the code is less important now onto calling the provider.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">[Test]
[BusinessConversation]
<span style="color:blue;">public</span> <span style="color:blue;">void</span> BusinessConversationTest()
{
    <span style="color:blue;">const</span> <span style="color:blue;">int</span> id = 9;
    var employee = _provider.GetEmployee(id);
    Assert.IsNotNull(employee);

    var employees = _provider.GetEmployees();
    Assert.IsTrue(employees.Count &gt; 0);

    var territories = _provider.GetTerritories();
    Assert.IsTrue(territories.Count &gt; 0);
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>In the setup call for this test Unity will resolve the _provider and assign it a Conversation which has the SessionFactory in it for opening the session. The same session is used for each of the calls to the database and committed as a single transaction when the method exits. This is done automagically by <a href="http://www.postsharp.org/">PostSharp</a>.</p>
<p>PostSharp is an aspect orientated programming framework that allows you to create attributes can trigger methods before entering a method with the attribute and after exiting. The code for the BusinesConversation attribute is</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">[Serializable]
<span style="color:blue;">public</span> sealed <span style="color:blue;">class</span> BusinessConversation : OnMethodBoundaryAspect
{
    <span style="color:blue;">public</span> override <span style="color:blue;">void</span> OnEntry(MethodExecutionEventArgs eventArgs)
    {
        var container = HttpContext.Current != <span style="color:blue;">null</span> ?
            HttpContext.Current.Application.GetContainer() : UnityTestContainer.Instance;
        var conversation = container.Resolve&lt;IConversation&gt;();
        conversation.Resume();
    }

    <span style="color:blue;">public</span> override <span style="color:blue;">void</span> OnExit(MethodExecutionEventArgs eventArgs)
    {
        var container = HttpContext.Current != <span style="color:blue;">null</span> ?
            HttpContext.Current.Application.GetContainer() : UnityTestContainer.Instance;
        var conversation = container.Resolve&lt;IConversation&gt;();
        conversation.Pause();
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Now this has some Unity specific code in it where it calls to the container to resolve the Conversation but the important part is that OnEntry to a method with the BusinessConversation attribute the conversation is resumed. This will either resume an existing conversation that&#8217;s stored in the session or it will create a new one. When it exits the method the conversation is paused which commits the transaction to the database.</p>
<p>The other code where it does resolution checking on HttpContext or reads from my UntityTestContainer does not really make me happy and eventually will be refactored to be cleaner in one way or another. But this code would be specific to how you interact with your container that would store the Conversations.</p>
<p>The only other issue I have with any of this is exposing the Session from the Conversation, I couldn&#8217;t figure out a simplier way for allowing my data providers to actually interact with the session to physically hit the database otherwise. I considered instead of a Conversation containing a session to actually make it implement ISession and assign it to itself during the creation but that didn&#8217;t sound right to me even more so.</p>
<p>I&#8217;d be grateful for any feedback on my implementation here: good, bad or indifferent. I feel I&#8217;ve finally put together a clean simple to understand post on how to correctly manage NHibernate&#8217;s session that doesn&#8217;t require implementing the UnitOfWork pattern and leverages dependency injection to keep the code seperated and decoupled as much as possible. The full source to my project as always can be found on my <a href="http://dotnetchris.wordpress.com/assembla/">Assembla page</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f01%2f27%2fconversation-per-business-transaction-using-postsharp-and-ioc%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f01%2f27%2fconversation-per-business-transaction-using-postsharp-and-ioc%2f&amp;bgcolor=0066FF" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Conversation-Per-Business-Transaction-using-PostSharp-and-IoC-%C2%AB-dotNetChris-MarisicNet"><img style="border:0;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F01%2F27%2Fconversation-per-business-transaction-using-postsharp-and-ioc%2F" alt="Shout it" /></a></p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/230/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/230/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/230/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=230&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/01/27/conversation-per-business-transaction-using-postsharp-and-ioc/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdotnetchris.wordpress.com%2f2009%2f01%2f27%2fconversation-per-business-transaction-using-postsharp-and-ioc%2f&#38;bgcolor=0066FF" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>

		<media:content url="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdotnetchris.wordpress.com%2F2009%2F01%2F27%2Fconversation-per-business-transaction-using-postsharp-and-ioc%2F" medium="image">
			<media:title type="html">Shout it</media:title>
		</media:content>
	</item>
		<item>
		<title>Working with DataTables/Datarows</title>
		<link>http://dotnetchris.wordpress.com/2009/01/16/working-with-datatablesdatarows/</link>
		<comments>http://dotnetchris.wordpress.com/2009/01/16/working-with-datatablesdatarows/#comments</comments>
		<pubDate>Fri, 16 Jan 2009 18:21:20 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Casting]]></category>
		<category><![CDATA[ChangeType]]></category>
		<category><![CDATA[Checking]]></category>
		<category><![CDATA[Conversion]]></category>
		<category><![CDATA[Data Reading]]></category>
		<category><![CDATA[DataRow]]></category>
		<category><![CDATA[DataTable]]></category>
		<category><![CDATA[DBNull]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=204</guid>
		<description><![CDATA[Sadly the project I am on at work is all circa 2005 standards where everything is DataTables and Data Adapters etc. These classes are an incredibly annoying &#8220;feature&#8221; to work with and are just brutal since it&#8217;s impossible to ever have a good domain design with them. But I wrote this class to make life [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=204&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Sadly the project I am on at work is all circa 2005 standards where everything is DataTables and Data Adapters etc. These classes are an incredibly annoying &#8220;feature&#8221; to work with and are just brutal since it&#8217;s impossible to ever have a good domain design with them. But I wrote this class to make life easier to deal with them. It uses .net 3.5 extension methods but with a few minor changes it will run on .net 2.0. Some of the basis of this code for the ChangeType method came from <a href="http://www.monstersgotmy.net/post/QueryString-Candy-Could-Rot-Your-Teeth.aspx">QueryString Candy &#8211; Could Rot Your Teeth</a> however I&#8217;ve added my own touches to it.</p>
<p>Here&#8217;s my extension method class:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:green;">///&lt;summary&gt;</span>
<span style="color:green;">/// Extension methods for manipulating DataRows</span>
<span style="color:green;">///&lt;/summary&gt;</span>
<span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">class</span> DataRowUserExtensions
{
    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Determines whether [is empty string] [the specified data row].</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="dataRow"&gt;The data row.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;param name="key"&gt;The key.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;returns&gt;</span>
    <span style="color:green;">///   &lt;c&gt;true&lt;/c&gt; if [is empty string] [the specified data row]; otherwise, including DBNull, &lt;c&gt;false&lt;/c&gt;.</span>
    <span style="color:green;">/// &lt;/returns&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> IsEmptyString(<span style="color:blue;">this</span> DataRow dataRow, <span style="color:blue;">string</span> key)
    {
        <span style="color:blue;">if</span> (dataRow.Table.Columns.Contains(key))
            <span style="color:blue;">return</span> !dataRow.IsNull(key) &amp;&amp; dataRow[key].ToString() == <span style="color:blue;">string</span>.Empty;

        throw <span style="color:blue;">new</span> ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Determines whether the specified data row is null.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="dataRow"&gt;The data row.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;param name="key"&gt;The key.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;returns&gt;</span>
    <span style="color:green;">///   &lt;c&gt;true&lt;/c&gt; if the specified data row is null; otherwise, &lt;c&gt;false&lt;/c&gt;.</span>
    <span style="color:green;">/// &lt;/returns&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> IsNull(<span style="color:blue;">this</span> DataRow dataRow, <span style="color:blue;">string</span> key)
    {
        <span style="color:blue;">if</span> (dataRow.Table.Columns.Contains(key))
            <span style="color:blue;">return</span> dataRow[key] == <span style="color:blue;">null</span> || dataRow[key] == DBNull.Value;

        throw <span style="color:blue;">new</span> ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Determines whether [is null or empty string] [the specified data row].</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;param name="dataRow"&gt;The data row.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;param name="key"&gt;The key.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;returns&gt;</span>
    <span style="color:green;">///   &lt;c&gt;true&lt;/c&gt; if [is null or empty string] [the specified data row]; otherwise, &lt;c&gt;false&lt;/c&gt;.</span>
    <span style="color:green;">/// &lt;/returns&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> IsNullOrEmptyString(<span style="color:blue;">this</span> DataRow dataRow, <span style="color:blue;">string</span> key)
    {
        <span style="color:blue;">if</span> (dataRow.Table.Columns.Contains(key))
            <span style="color:blue;">return</span> dataRow.IsNull(key) &amp;&amp; dataRow.IsEmptyString(key);

        throw <span style="color:blue;">new</span> ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Gets the specified data row.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;</span>
    <span style="color:green;">/// &lt;param name="dataRow"&gt;The data row.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;param name="key"&gt;The key.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span style="color:blue;">public</span> <span style="color:blue;">static</span> T Get&lt;T&gt;(<span style="color:blue;">this</span> DataRow dataRow, <span style="color:blue;">string</span> key)
    {
        <span style="color:blue;">if</span> (dataRow.Table.Columns.Contains(key))
        {
            <span style="color:green;">// If we're trying to convert an empty string to string return the string instead</span>
            <span style="color:green;">// default(string) which is null, otherwise return null if dataRow IsNullOrEmptyString</span>
            <span style="color:green;">// else convert</span>
            <span style="color:blue;">return</span> typeof (T) == typeof (<span style="color:blue;">string</span>) &amp;&amp; dataRow.IsEmptyString(key)
                ? (T) dataRow[key] : (dataRow.IsNullOrEmptyString(key)
                ? <span style="color:blue;">default</span>(T) : (T) ChangeTypeTo&lt;T&gt;(dataRow[key]));
        }

        throw <span style="color:blue;">new</span> ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    <span style="color:green;">/// &lt;summary&gt;</span>
    <span style="color:green;">/// Changes the type to.</span>
    <span style="color:green;">/// &lt;/summary&gt;</span>
    <span style="color:green;">/// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;</span>
    <span style="color:green;">/// &lt;param name="value"&gt;The value.&lt;/param&gt;</span>
    <span style="color:green;">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span style="color:blue;">private</span> <span style="color:blue;">static</span> object ChangeTypeTo&lt;T&gt;(<span style="color:blue;">this</span> object value)
    {
        <span style="color:blue;">if</span> (value == <span style="color:blue;">null</span>)
            <span style="color:blue;">return</span> <span style="color:blue;">null</span>;

        Type underlyingType = typeof (T);
        <span style="color:blue;">if</span> (underlyingType == <span style="color:blue;">null</span>)
            throw <span style="color:blue;">new</span> ArgumentNullException("value");

        <span style="color:blue;">if</span> (underlyingType.IsGenericType &amp;&amp; underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable&lt;&gt;)))
        {
            var converter = <span style="color:blue;">new</span> NullableConverter(underlyingType);
            underlyingType = converter.UnderlyingType;
        }

        <span style="color:green;">// Guid convert</span>
        <span style="color:blue;">if</span> (underlyingType == typeof (Guid))
        {
            <span style="color:blue;">return</span> <span style="color:blue;">new</span> Guid(value.ToString());
        }

        <span style="color:green;">// Check for straight conversion or value.ToString conversion</span>
        var objType = value.GetType();

        <span style="color:green;">// If this is false, lets hope value.ToString can convert otherwise exception</span>
        <span style="color:blue;">bool</span> objTypeAssignable2typeT = underlyingType.IsAssignableFrom(objType);

        <span style="color:green;">// Do conversion</span>
        <span style="color:blue;">return</span> objTypeAssignable2typeT ? Convert.ChangeType(value, underlyingType)
                                                        : Convert.ChangeType(value.ToString(), underlyingType);
    }
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Usage example:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">ds.Tables[0].Rows[0].Get&lt;DateTime?&gt;("SomeDate")
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Basically what is going first it checks to make sure that &#8220;SomeDate&#8221; is an actual column inside the DataRow, then it checks to make sure dr["SomeDate"] isn&#8217;t null, DBNull or an empty string.</p>
<p>Inside of the ChangeType method it will then resolve whether &lt;T&gt; is an object or a nullable object. If it&#8217;s a nullable object it will find the actual object type.</p>
<p>Next we do an outside check to see if it&#8217;s a Guid (since Convert.ChangeType can&#8217;t handle guids) and if it is to return the guid or it will bubble up an exception of underlyingType == typeof(Guid) and value is not a valid guid.</p>
<p>After that the actual conversion occurs first it checks if the type of value is Assignable To underlyingtype, if it is then it will do the Convert.ChangeType. If it&#8217;s not assignable we&#8217;re going to hope the string representation of value can be converted to type T otherwise it will fail. This second case is useful if you want to get the string representation of a number or date. As with the previous example:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">ds.Tables[0].Rows[0].Get&lt;string&gt;("SomeDate")
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>Will return the string value of the SomeDate value instead of raising an exception if we didn&#8217;t have the second condition of the return statement there.</p>
<p>Hope this helps some of you out as much as it does me!</p>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/204/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=204&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/01/16/working-with-datatablesdatarows/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>
	</item>
		<item>
		<title>Method to determine if data range contains a leap year</title>
		<link>http://dotnetchris.wordpress.com/2009/01/14/method-to-determine-if-data-range-contains-a-leap-year/</link>
		<comments>http://dotnetchris.wordpress.com/2009/01/14/method-to-determine-if-data-range-contains-a-leap-year/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 19:17:57 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Leap Year]]></category>
		<category><![CDATA[Method]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=163</guid>
		<description><![CDATA[Update 1/14/2008: I pulled a Microsoft zune! My leap check was actually off by 1. Corrected algorithm
As I was going through some of code I previously worked on today I came across this method I wrote a while ago. I&#8217;m not too sure  if it will help anyone else but I figured I&#8217;d throw it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=163&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Update 1/14/2008: I pulled a Microsoft zune! My leap check was actually off by 1. Corrected algorithm</p>
<p>As I was going through some of code I previously worked on today I came across this method I wrote a while ago. I&#8217;m not too sure  if it will help anyone else but I figured I&#8217;d throw it up here. Basically I had a need to figure out if a date entered was inside a period of time in the future (in my case specifically 2.5 years and 3.0 years in the future). My original plan was to just check if number of days fit in between 365*2.5  and 365*3 but I realized as rare of a possiblity as it was a potential leap year could have foiled my plans.</p>
<p>So basically I wrote this method for me to be able to calculate if I need to add another day to my range to make sure they weren&#8217;t short changed a day because leap year occurred.</p>
<p>I&#8217;d love to hear your opinions on this code if there is anything you&#8217;d do differently.</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;"><span style="color:green;">/// &lt;summary&gt;</span>
<span style="color:green;">/// Determines if the DateRange contains a leap year.</span>
<span style="color:green;">/// &lt;/summary&gt;</span>
<span style="color:green;">/// &lt;param name="startDate"&gt;The start date.&lt;/param&gt;</span>
<span style="color:green;">/// &lt;param name="endDate"&gt;The end date.&lt;/param&gt;</span>
<span style="color:green;">/// &lt;returns&gt;&lt;/returns&gt;</span>
<span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> DateRangeContainsLeapYear(DateTime startDate, DateTime endDate)
{
  <span style="color:blue;">if</span> (startDate &gt; endDate)
    <span style="color:blue;">throw new InvalidDataException</span>("startDate must be less than or equal to endDate.");

  <span style="color:green;">//Bounds check Feb will exist either in start of the first time span date</span>
  <span style="color:green;">//or at the end of the last date potentially</span>
  <span style="color:blue;">if</span> (startDate.Month &lt; 3 &amp;&amp; DateTime.IsLeapYear(startDate.Year))
    <span style="color:blue;">return</span> <span style="color:blue;">true</span>;
  <span style="color:blue;">if</span> ((endDate.Month &gt; 3 || (endDate.Month == 2 &amp;&amp; endDate.Day == 29))
&amp;&amp; DateTime.IsLeapYear(endDate.Year))
    <span style="color:blue;">return</span> <span style="color:blue;">true</span>;

  <span style="color:green;">//Start year can't be leap year otherwise we're done</span>
  <span style="color:blue;">int</span> startYear = startDate.Year + 1;

<span style="color:green;">//Upper bounds will be handled by i &lt; endYear</span>
  <span style="color:blue;">int</span> endYear = endDate.Year;

  <span style="color:blue;">for</span> (<span style="color:blue;">int</span> year = startYear; year &lt; endYear; year++)
  {
    <span style="color:blue;">if</span>(!DateTime.IsLeapYear(year)) continue;
    <span style="color:blue;">return</span> <span style="color:blue;">true</span>;
  }

  <span style="color:blue;">return</span> <span style="color:blue;">false</span>;
}
</span></pre>
</td>
</tr>
</tbody>
</table>
<p><code>BloggingContext.ApplicationInstance.CompleteRequest();</code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=163&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/01/14/method-to-determine-if-data-range-contains-a-leap-year/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>
	</item>
		<item>
		<title>Adding Inflector to UnityWeb</title>
		<link>http://dotnetchris.wordpress.com/2009/01/13/adding-inflector-to-unityweb/</link>
		<comments>http://dotnetchris.wordpress.com/2009/01/13/adding-inflector-to-unityweb/#comments</comments>
		<pubDate>Tue, 13 Jan 2009 20:20:53 +0000</pubDate>
		<dc:creator>dotnetchris</dc:creator>
				<category><![CDATA[UnityWeb]]></category>
		<category><![CDATA[Fleunt Nhibernate]]></category>
		<category><![CDATA[Inflector]]></category>
		<category><![CDATA[Pluralize]]></category>
		<category><![CDATA[Pluralizer]]></category>

		<guid isPermaLink="false">http://dotnetchris.wordpress.com/?p=197</guid>
		<description><![CDATA[Today as I was browsing the Fluent NHibernate discussion boards I was reading the post regarding features that the creators of the S#arp Architecture were interested in seeing.
One of the things that was pointed out was that FH doesn&#8217;t include a pluralizer which can make convention mapping problem matic.
Take my current AutoPersistanceModel




var persistenceModel = AutoPersistenceModel.MapEntitiesFromAssemblyOf&#60;Employee&#62;()
.WithConvention(c [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=197&subd=dotnetchris&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Today as I was browsing the <a href="http://groups.google.com/group/fluent-nhibernate">Fluent NHibernate</a> discussion boards I was reading the post regarding features that the creators of the S#arp Architecture were interested in seeing.</p>
<p>One of the things that was pointed out was that FH doesn&#8217;t include a pluralizer which can make convention mapping problem matic.</p>
<p>Take my current AutoPersistanceModel</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">var persistenceModel = AutoPersistenceModel.MapEntitiesFromAssemblyOf&lt;Employee&gt;()
.WithConvention(c =&gt; c.DefaultLazyLoad = <span style="color:blue;">false</span>)
.WithConvention(convention =&gt; <span style="background-color:lightgreen;">  convention.GetTableName = type =&gt; type.Name + "s"</span>)
.WithConvention(convention =&gt; convention.GetPrimaryKeyNameFromType = type =&gt; type.Name + "ID")
.WithConvention(convention =&gt; convention.GetForeignKeyName = prop =&gt; prop.Name + "ID")
.WithConvention(convention=&gt;convention.DefaultCache = cache =&gt; cache.AsReadWrite())
.WithConvention(c =&gt; c.OneToManyConvention = m =&gt;
                                                 {
                                                     m.Cascade.All();
                                                     m.LazyLoad();
                                                 })
.ForTypesThatDeriveFrom&lt;Category&gt;(autoMap =&gt;
                                      {
                                          <span style="background-color:lightgreen;">  autoMap.WithTable("Categories");</span>
                                          autoMap.Map(p =&gt; p.Name, "CategoryName");
                                      })
.ForTypesThatDeriveFrom&lt;Territory&gt;(autoMap =&gt;
                                       {
                                           <span style="background-color:lightgreen;">  autoMap.WithTable("Territories");</span>
                                           autoMap.Map(p =&gt; p.Description, "TerritoryDescription");
                                           autoMap.Map(p =&gt; p.Region,
 "RegionID").CustomTypeIs(typeof (Region));
                                       })
;
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>In more than 1 senario I need to force the autoMap to use the correct spelling of a table name instead of just being able to append S on it. With Inflector I can get a much cleaner map and only to have:</p>
<table border="1" cellpadding="16" bgcolor="white">
<tbody>
<tr>
<td>
<pre><span style="font-family:Courier New;color:black;font-size:small;">var persistenceModel = AutoPersistenceModel.MapEntitiesFromAssemblyOf&lt;Employee&gt;()
.WithConvention(c =&gt; c.DefaultLazyLoad = <span style="color:blue;">false</span>)
.WithConvention(convention =&gt; <span style="background-color:lightgreen;">  convention.GetTableName = type =&gt; Inflector.Pluralize(type.Name))</span>
.WithConvention(convention =&gt; convention.GetPrimaryKeyNameFromType = type =&gt; type.Name + "ID")
.WithConvention(convention =&gt; convention.GetForeignKeyName = prop =&gt; prop.Name + "ID")
.WithConvention(convention=&gt;convention.DefaultCache = cache =&gt; cache.AsReadWrite())
.WithConvention(c =&gt; c.OneToManyConvention = m =&gt;
                                                 {
                                                     m.Cascade.All();
                                                     m.LazyLoad();
                                                 })
.ForTypesThatDeriveFrom&lt;Category&gt;(autoMap =&gt;
                                      {
                                          autoMap.Map(p =&gt; p.Name, "CategoryName");
                                      })
.ForTypesThatDeriveFrom&lt;Territory&gt;(autoMap =&gt;
                                       {
                                           autoMap.Map(p =&gt; p.Description, "TerritoryDescription");
                                           autoMap.Map(p =&gt; p.Region,
 "RegionID").CustomTypeIs(typeof (Region));
                                       })
;
</span></pre>
</td>
</tr>
</tbody>
</table>
<p>You can download Inflector and it&#8217;s source over at Andrew Peter&#8217;s blog <a href="http://andrewpeters.net/inflectornet/">Inflector.NET</a>.</p>
<p>On a further note I believe I&#8217;ve learned how to remove the need to have the specific mappings for my enum properties, Name property and Description property which will significantly reduce the code noise of the auto mapping which will show up soon in another blog bost.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetchris.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetchris.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetchris.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetchris.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetchris.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetchris.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetchris.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetchris.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetchris.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetchris.wordpress.com/197/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetchris.wordpress.com&blog=3411356&post=197&subd=dotnetchris&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetchris.wordpress.com/2009/01/13/adding-inflector-to-unityweb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f0e7c2d0d5d83c928cfcfce66928160e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetchris</media:title>
		</media:content>
	</item>
	</channel>
</rss>