<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Adventures in Enterprise Software Development</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/nkpatterson/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/nkpatterson/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 03:51:53 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Managing Developer VMs in Azure with a Chocolatey Twist</title>
      <link>https://docs.microsoft.com/archive/blogs/nkpatterson/managing-developer-vms-in-azure-with-a-chocolatey-twist</link>
      <pubDate>Mon, 26 Jan 2015 06:07:00 GMT</pubDate>
      <dc:creator><![CDATA[nick.patterson]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nkpatterson/2015/01/26/managing-developer-vms-in-azure-with-a-chocolatey-twist/</guid>
      <description><![CDATA[Overview
Imagine you're in charge of managing your development team's workstation infrastructure....]]></description>
      <content:encoded><![CDATA[<h1>Overview</h1>
<p>Imagine you're in charge of managing your development team's workstation infrastructure. Let's say you have 20 developers and they all have their own physical workstation. Those workstations might have started life from a common sys-prepped image with a standard set of developer-related tools installed on them (Visual Studio, SQL Server, Fiddler, etc.). Oftentimes, there will also be a Software or Tools file share somewhere out on the network where the devs can manually install whatever else they need. But, over time, new software and tools are released and your devs want to use them. Your baseline workstation image is out-of-date the day after you build it and it's tedious and time-consuming to maintain. Keeping up the Software share with the latest/greatest toolset is a full-time job by itself. On top of that, your team is growing fast and it's getting really expensive to procure new workstations so your CTO is moving your development to the cloud. Well, it's your lucky day my friend because the cloud affords us many opportunities that we didn't have before. The combination of 3 cool technologies- <strong>Azure PowerShell</strong>, <strong>Windows PowerShell Desired State Configuration (DSC)</strong> and <strong>Chocolatey</strong>- will make managing your development environment in the cloud&nbsp;trivial.&nbsp;</p>
<p>If you're not already familiar, Chocolatey is a machine package manager, similar to apt-get, but built for Windows. This enables you to install many common dev/test/ops tools with a simple command. Need Visual Studio 2013 Ultimate? Simple:</p>
<pre class="scroll"><code class="csharp">PS: \&gt; choco install visualstudio2013ultimate</code></pre>
<p>BAM! Done. Say goodbye to that pesky Software share that you have to maintain. But what about the common list of software you need installed on all the new VMs? And what if I want to push new tools out to my existing VMs? That's where Azure PowerShell and DSC comes in. Azure PowerShell is a set of cmdlets designed to make scripting out your cloud environment dead simple while DSC is a technology that is used to automatically configure a machine with a desired state (think Windows Roles/Features, directory structures, security settings, etc.)</p>
<p>In this post, I will show you how to use these three technologies together to make your life easy.</p>
<h2>Install the latest Azure PowerShell SDK</h2>
<p>First things first. If you haven't already installed or used Azure PowerShell before, follow these steps to get started: <a title="How to install and configure Azure PowerShell" href="https://azure.microsoft.com/en-us/documentation/articles/install-configure-powershell/">How to install and configure Azure PowerShell</a>. These tools are AMAZING, very simple to use and absolutely essential when talking about automating/standardizing your cloud environment.</p>
<h2>Download and install the cChoco DSC Resource</h2>
<p>The real magic of this particular scenario is how we can extend DSC to include Chocolatey natively in the process. I (foolishly) started writing my own custom DSC resource to wrap Chocolatey but when I ran into several issues, I Googled it with Bing and quickly realized that, like every other "original" idea I've ever had, someone from the community had already beat me to it :) <a title="cChoco" href="https://github.com/PowerShellOrg/cChoco">cChoco</a> is one of several projects hosted up on GitHub in the <a title="PowerShell.org repository" href="https://github.com/PowerShellOrg">PowerShell.org repository</a> and it makes using Chocolatey with DSC a breeze. Here's how to download and install:</p>
<ol>
<li>Download cChoco from the following location:&nbsp;<a href="https://github.com/PowerShellOrg/cChoco">https://github.com/PowerShellOrg/cChoco</a>&nbsp;</li>
<li>Extract the downloaded zip to the following path on your workstation:&nbsp;<span>C:\Program Files\WindowsPowerShell\Modules</span></li>
</ol>
<div>That's it! You will then be able to import and leverage cChoco from your custom DSC configuration file which you'll now create.</div>
<h2>Create your custom DSC configuration file with Chocolatey packages</h2>
<p>There are several out of the box DSC resources that you can take advantage of. For example, you could use the WindowsFeature resource to install IIS on all of your development workstations. Here is a list of all of the <a href="https://technet.microsoft.com/en-us/library/dn249921.aspx">built-in DSC resources</a>. For this example, however, we'll just stick to using Chocolatey to install some common dev tools. Here's what our DSC file looks like:</p>
<p><a href="https://gist.github.com/nkpatterson/ec1cd1c17ae27b11944a" target="_blank">https://gist.github.com/nkpatterson/ec1cd1c17ae27b11944a</a></p>
<p>This looks like a pretty typical DSC file. The cChocoInstaller performs the initial installation of Chocolatey on the machine (if it's not already there). The 3 cChocoPackageInstaller sections specify which packages to install. You have the complete list of <a href="https://chocolatey.org/packages">Chocolatey packages</a> at your fingertips but in this case I'm just installing Google Chrome, Fiddler and Visual Studio 2013 Ultimate. The Name attribute in the DSC file corresponds to the package name. Remember where you save your DSC file, you will be referencing it in the next step.</p>
<h2>Use the DSC PowerShell cmdlets to publish your package</h2>
<p>Once you've got your DSC file just the way you like it, you will need to package it up and push it to the cloud so it can be referenced while Azure is configuring your VMs. This is made easy with the <a href="https://msdn.microsoft.com/en-us/library/azure/dn832940.aspx">Publish-AzureVMDSCConfiguration</a> cmdlet. &nbsp;You just need to obtain a reference to your Azure storage account, point it at your DSC file and the command does the rest.</p>
<p><a href="https://gist.github.com/nkpatterson/5d532bd6fe9bed02a9ed#file-publish-ps1" target="_blank">https://gist.github.com/nkpatterson/5d532bd6fe9bed02a9ed#file-publish-ps1</a></p>
<p>Now, if you go to the Azure Portal and browse to your storage account and click over to the Containers tab, you will see your DSC file sitting up in the cloud ready for the next step.</p>
<h2>Provision a new Developer VM using your new DSC package</h2>
<p>Using the <a href="https://msdn.microsoft.com/en-us/library/azure/dn832942.aspx">Set-AzureVMDSCExtension</a> cmdlet, we can create new virtual machines with our DSC package. I went ahead and wrote a simple script that encapsulates all of the necessary steps, taking in a few parameters such as your storage account name, the local path to the DSC file, the desired names of the virtual machines, etc. to make provisioning one or more VMs really easy.</p>
<p><a href="https://gist.github.com/nkpatterson/ce00ede9a03777aa1578#file-provision-ps1" target="_blank">https://gist.github.com/nkpatterson/ce00ede9a03777aa1578#file-provision-ps1</a></p>
<p>With this script in hand, you can easily create 3 new developer VMs in a matter of minutes:</p>
<pre class="scroll"><code class="csharp">PS: \&gt;.\Provision.ps1 -StorageAccountName "MyAccountName" -DscConfigurationPath "DSC.ps1" -DscConfigurationName "DevWorkstation" `<br /> <br /> -ServiceName "DevWorkstations" -VmNames @("devvm01", "devvm02", "devvm03") -AdminUsername "Admin" -AdminPassword "SomethingMoreSecureThanThis"<br /> </code></pre>
<p><span><span><span>A few things like the VM image and size are hard-coded in there but hopefully you get the point. After the script runs, you'll see this in the management portal:</span></span></span></p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/49/36/3833.VMs%20Starting.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-49-36/3833.VMs-Starting.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/49/36/3833.VMs%20Starting.png" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-49-36/3833.VMs-Starting.png" alt="" border="0" /></a></p>
<p><span><span><span>And once the VMs are started and running, you can log in using the credentials you entered and verify that the software you had specified in your Chocolatey DSC file are, in fact, there. Cool!</span></span></span></p>
<p><span><span><span><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/49/36/1205.Installed%20Software.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-49-36/1205.Installed-Software.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/49/36/1205.Installed%20Software.png" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-49-36/1205.Installed-Software.png" alt="" border="0" /></a><br /></span></span></span></p>
<h2>Update an existing Developer VM with new Chocolatey packages</h2>
<p>This is all well and good and helpful in getting your development environment stood up quickly. The REAL power, however, comes when you want to make a change to your workstation baseline. For example, what if after provisioning 20 of these developer VMs I want to install an awesome new tool that I found on all of them? If you were using a custom VM image, you would need to download the image VHD, start it up, install the new software, sysprep it and then upload it back into Azure, yada yada. This only covers new VMs going forward and does nothing for you regarding the 20 VMs you already have. You would have to manually install the software on each of those. With DSC and Chocolatey, this tedious maintenance scenario becomes a simple matter of updating your DSC file with the new Chocolatey packages you wish to install and leveraging the same PowerShell cmdlets we were using to provision new VMs to update the existing ones.&nbsp;Here's a script I threw together to do just that:</p>
<p><a href="https://gist.github.com/nkpatterson/2292baa29bcf0820a8a7#file-updatevms-ps1" target="_blank">https://gist.github.com/nkpatterson/2292baa29bcf0820a8a7#file-updatevms-ps1</a></p>
<p>After adding the cool new package to our local DSC file you can call the Provision.ps1 script again with just the minimal parameters to get the DSC file uploaded to storage.</p>
<pre class="scroll"><code class="csharp">PS: \&gt;.\Provision.ps1 -StorageAccountName "MyAccountName" -DscConfigurationPath ".\DSC.ps1"</code></pre>
<p>That will overwrite the existing DSC file in your storage container and make it ready for the next call to UpdateVMs.ps1:</p>
<pre class="scroll"><code class="csharp">PS: \&gt;.\UpdateVMs.ps1 -StorageAccountName "MyAccountName" -DscConfigurationFileName "DSC.ps1.zip" -DscConfigurationName "DevWorkstation" -ServiceName "DevWorkstations" -VmNames @("devvm01", "devvm02", "devvm03")</code></pre>
<p>And in just a few minutes, all of your VMs will be updated with the new software!</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/58/87/39/Scripts.zip" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-58-87-39/Scripts.zip">Scripts.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>A Re-Usable NHibernate Paging Extension Method</title>
      <link>https://docs.microsoft.com/archive/blogs/nkpatterson/a-re-usable-nhibernate-paging-extension-method</link>
      <pubDate>Fri, 29 Jun 2012 10:44:04 GMT</pubDate>
      <dc:creator><![CDATA[nick.patterson]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nkpatterson/2012/06/29/a-re-usable-nhibernate-paging-extension-method/</guid>
      <description><![CDATA[Every developer knows that they should always try to avoid returning an unbounded result set from...]]></description>
      <content:encoded><![CDATA[<p>Every developer knows that they should always try to avoid returning an <a href="https://nhprof.com/Learn/Alerts/UnboundedResultSet">unbounded result set</a> from the database, right?&nbsp; Of course they do.&nbsp; The obvious solution to this problem is to page through the results in smaller chunks that the database (and most likely the end-user) can handle efficiently.&nbsp; I didn&rsquo;t want to have to reinvent the wheel for every query I wrote so I wrapped the necessary NHibernate logic up in a nice, tidy extension method.</p>
<p><strong>Side note</strong>: <a href="https://nhprof.com/">NHibernate Profiler</a> is an indispensible tool for optimizing your NHibernate code.&nbsp; I couldn&rsquo;t live without it, nor would I want to.&nbsp; And no I don&rsquo;t receive kickbacks from Ayende.</p>
<p>Of course, in order to make this truly useful, I needed a custom collection that could keep track of the various paging settings like the current page index, the total number of records in the database, how many records are returned for each page, etc.&nbsp; For this, I blatantly <span style="text-decoration: line-through;">stole</span> borrowed the <a href="https://blog.wekeroad.com/blog/aspnet-mvc-pagedlistt/">PagedList&lt;T&gt; code</a> from <a href="https://blog.wekeroad.com/">Rob Conery</a> and <a href="https://weblogs.asp.net/scottgu/">ScottGu</a>.&nbsp; I also later found a <a href="https://github.com/TroyGoode/PagedList">great project</a> on github by <a href="https://www.squaredroot.com/">Troy Goode</a> that is basically the same but with some supporting unit tests and optimizations.&nbsp; Either way, here is teh codez that I use.</p>
<p><strong>PagedList.cs &ndash; </strong>contains an interface and a default implementation of a generic PagedList&lt;T&gt;.&nbsp; It also has a helper extension method so you can quickly turn any IEnumberable&lt;T&gt; into a PagedList&lt;T&gt;.</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ce3f0e9f-c1f5-469a-ba14-59506f33d24e" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>PagedList.cs</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 500px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">interface</span> <span style="color: #2b91af;" color="#2b91af">IPagedList</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">long</span> TotalCount { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">int</span> TotalPages { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">int</span> PageIndex { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">int</span> PageSize { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">int</span> FirstItem { <span style="color: #0000ff;" color="#0000ff">get</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">int</span> LastItem { <span style="color: #0000ff;" color="#0000ff">get</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">bool</span> HasPreviousPage { <span style="color: #0000ff;" color="#0000ff">get</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">bool</span> HasNextPage { <span style="color: #0000ff;" color="#0000ff">get</span>; }</li>
<li>}</li>
<li>&nbsp;</li>
<li>[<span style="color: #2b91af;" color="#2b91af">Serializable</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">PagedList</span>&lt;T&gt; : IPagedList</li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #2b91af;" color="#2b91af">List</span>&lt;T&gt; Items { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">private</span> <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> TotalPages { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">long</span> TotalCount { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> PageIndex { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> PageSize { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> PagedList()</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Items = <span style="color: #0000ff;" color="#0000ff">new</span> <span style="color: #2b91af;" color="#2b91af">List</span>&lt;T&gt;();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> PagedList(<span style="color: #2b91af;" color="#2b91af">IEnumerable</span>&lt;T&gt; source, <span style="color: #0000ff;" color="#0000ff">long</span> totalCount, <span style="color: #0000ff;" color="#0000ff">int</span> pageIndex, <span style="color: #0000ff;" color="#0000ff">int</span> pageSize)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PageSize = pageSize;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PageIndex = pageIndex;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TotalCount = totalCount;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TotalPages = (<span style="color: #0000ff;" color="#0000ff">int</span>)(TotalCount / pageSize);</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">if</span> (TotalCount % pageSize &gt; 0)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TotalPages++;</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Items = <span style="color: #0000ff;" color="#0000ff">new</span> <span style="color: #2b91af;" color="#2b91af">List</span>&lt;T&gt;(source);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">bool</span> HasPreviousPage</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">get</span> { <span style="color: #0000ff;" color="#0000ff">return</span> (PageIndex &gt; 0); }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">bool</span> HasNextPage</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">get</span> { <span style="color: #0000ff;" color="#0000ff">return</span> PageIndex &lt; TotalPages - 1; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> FirstItem</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">get</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">return</span> (PageIndex * PageSize) + 1;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> LastItem</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">get</span> { <span style="color: #0000ff;" color="#0000ff">return</span> FirstItem + PageSize - 1; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>}</li>
<li>&nbsp;</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">static</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">Pagination</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">static</span> PagedList&lt;T&gt; ToPagedList&lt;T&gt;(<span style="color: #0000ff;" color="#0000ff">this</span> <span style="color: #2b91af;" color="#2b91af">IEnumerable</span>&lt;T&gt; source, <span style="color: #0000ff;" color="#0000ff">int</span> totalCount, <span style="color: #0000ff;" color="#0000ff">int</span> pageIndex, <span style="color: #0000ff;" color="#0000ff">int</span> pageSize)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">return</span> <span style="color: #0000ff;" color="#0000ff">new</span> PagedList&lt;T&gt;(source, totalCount, pageIndex, pageSize);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>}</li>
</ol></div>
</div>
</div>
<p><strong>NHibernateExtensions.cs</strong> &ndash; this is where the NHibernate goodness comes in.&nbsp; This warrants a little explanation but take a look first and see if you can see what&rsquo;s going on.</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:920140f3-cdcd-4208-b420-51c1172b98fd" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>NHibernateExtensions.cs</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">static</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">NHibernateExtensions</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">static</span> PagedList&lt;T&gt; PagedList&lt;T&gt;(<span style="color: #0000ff;" color="#0000ff">this</span> ICriteria criteria, ISession session, <span style="color: #0000ff;" color="#0000ff">int</span> pageIndex, <span style="color: #0000ff;" color="#0000ff">int</span> pageSize) <span style="color: #0000ff;" color="#0000ff">where</span> T: <span style="color: #0000ff;" color="#0000ff">class</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">if</span> (pageIndex &lt; 0)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pageIndex = 0;</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> countCrit = (ICriteria)criteria.Clone();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;countCrit.ClearOrders(); <span style="color: #008000;" color="#008000">// so we don't have missing group by exceptions</span></li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> results = session.CreateMultiCriteria()</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Add&lt;<span style="color: #0000ff;" color="#0000ff">long</span>&gt;(countCrit.SetProjection(Projections.RowCountInt64()))</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Add&lt;T&gt;(criteria.SetFirstResult(pageIndex * pageSize).SetMaxResults(pageSize))</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.List();</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> totalCount = ((<span style="color: #2b91af;" color="#2b91af">IList</span>&lt;<span style="color: #0000ff;" color="#0000ff">long</span>&gt;)results[0])[0];</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">return</span> <span style="color: #0000ff;" color="#0000ff">new</span> PagedList&lt;T&gt;((<span style="color: #2b91af;" color="#2b91af">IList</span>&lt;T&gt;)results[1], totalCount, pageIndex, pageSize);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>First of all, this method is an extension of NHibernate&rsquo;s ICriteria class so it obviously requires you to be using NHibernate&rsquo;s Criteria API.&nbsp; This type of thing would be much more difficult using the HQL syntax.</p>
<p>Essentially what we want to do is leverage NHibernate&rsquo;s multi-criteria feature to send two different SQL statements to the server at the same time.&nbsp; One to retrieve the total record count of the query and two to get the actual results of that query, limited to the page size and page index that we specify.&nbsp; That&rsquo;s why we Clone the original criteria that is passed into the method.&nbsp; This will be what is used to get the total record count for the query.&nbsp; We call the ClearOrders method on this instance of the ICriteria because: 1) we don&rsquo;t care about how the query is ordered if we&rsquo;re just getting the total row count; and 2) the order statements can cause problems if there are groupings in the criteria. Trust me on this.</p>
<p>We then create the multi-criteria object on line 11 and add the total row count criteria that we cloned and the original criteria passed in but we use the SetFirstResult and SetMaxResults methods to limit the number of records returned.</p>
<p>Finally, we retrieve the values from the two result sets.&nbsp; The first being the total row count.&nbsp; The second, the actual results of the query and return the results using our fancy new PagedList&lt;T&gt; class.</p>
<p>The usage of this extension method couldn&rsquo;t be simpler.</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:2974884e-6544-4950-965f-a868d7de0d69" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>Code Snippet</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> PagedList&lt;Order&gt; GetCompletedOrders(<span style="color: #0000ff;" color="#0000ff">int</span> pageIndex, <span style="color: #0000ff;" color="#0000ff">int</span> pageSize)</li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008000;" color="#008000">// _currentSession is an instance of ISession, instantiation not shown</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">return</span> _currentSession.CreateCriteria&lt;Order&gt;()</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Add(Expression.Eq(<span style="color: #a31515;" color="#a31515">"Status"</span>, (<span style="color: #0000ff;" color="#0000ff">int</span>)OrderStatus.Complete))</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.AddOrder(Order.Desc(<span style="color: #a31515;" color="#a31515">"OrderCompletedDate"</span>))</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.PagedList&lt;Order&gt;(_currentSession, pageIndex, pageSize);</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>As a bonus, I&rsquo;m going to post some code that I use in my ASP.NET MVC projects that allows you generate a Pager control complete with customizable, CSS classes, next/previous text customizations, AJAX support, etc. from our PagedList&lt;T&gt; class in ONE LINE OF CODE.&nbsp; Stay tuned&hellip;</p>
<p><strong>Update:</strong> here&rsquo;s the post on those <a href="https://nkpatterson.blogspot.com/2010/12/aspnet-mvc-pager.html">ASP.NET MVC Pager</a> helper classes I mentioned.</p>]]></content:encoded>
    </item>
    <item>
      <title>Multiple AND/OR Statements with NHibernate</title>
      <link>https://docs.microsoft.com/archive/blogs/nkpatterson/multiple-andor-statements-with-nhibernate</link>
      <pubDate>Fri, 29 Jun 2012 10:42:44 GMT</pubDate>
      <dc:creator><![CDATA[nick.patterson]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nkpatterson/2012/06/29/multiple-andor-statements-with-nhibernate/</guid>
      <description><![CDATA[I&rsquo;m sure you&rsquo;ve encountered the scenario where you need to add multiple AND or OR...]]></description>
      <content:encoded><![CDATA[<p>I&rsquo;m sure you&rsquo;ve encountered the scenario where you need to add multiple AND or OR statements to an NHibernate query.&nbsp; The string parsing and manipulation required to do it in HQL would be enough to send you straight to programmer hell.&nbsp; So it turns out the easiest (in my opinion) option is to use the good ol&rsquo; Criteria API.&nbsp; But it&rsquo;s not as obvious as it first seems.&nbsp; In order to accomplish the task, you actually need to use a pair of constructs that may be new to you: Conjunction which represents a grouping of AND statements (A <strong>and</strong> B <strong>and</strong> C&hellip;); and Disjunction, a grouping of OR statements (A <strong>or</strong> B <strong>or</strong> C&hellip;).&nbsp; Here&rsquo;s an admittedly contrived example of how you could query for Persons by FirstName that are not archived (IsArchived), ordering by FirstName:</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ab7c826b-df3b-4a82-a454-1529f4f46722" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>Contrived Disjunction Example</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">string</span>[] namesToCheck = { <span style="color: #a31515;" color="#a31515">"Nick"</span>, <span style="color: #a31515;" color="#a31515">"Dave"</span>, <span style="color: #a31515;" color="#a31515">"Bryan"</span>, <span style="color: #a31515;" color="#a31515">"James"</span> };</li>
<li><span style="color: #0000ff;" color="#0000ff">using</span> (<span style="color: #2b91af;" color="#2b91af">ISession</span> session = SessionManager.CreateSession())</li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> criteria = session.CreateCriteria&lt;<span style="color: #2b91af;" color="#2b91af">Person</span>&gt;();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> disjunction = <span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Disjunction();</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;criteria.Add(<span style="color: #2b91af;" color="#2b91af">Expression</span>.Eq(<span style="color: #a31515;" color="#a31515">"IsArchived"</span>, <span style="color: #0000ff;" color="#0000ff">false</span>));</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">foreach</span> (<span style="color: #0000ff;" color="#0000ff">var</span> name <span style="color: #0000ff;" color="#0000ff">in</span> namesToCheck)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;disjunction.Add(<span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Eq(<span style="color: #a31515;" color="#a31515">"FirstName"</span>, name));</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;criteria.Add(disjunction);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;criteria.AddOrder(<span style="color: #2b91af;" color="#2b91af">Order</span>.Asc(<span style="color: #a31515;" color="#a31515">"FirstName"</span>));</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">return</span> criteria.List&lt;<span style="color: #2b91af;" color="#2b91af">Person</span>&gt;();</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>This would generate something similar to the following SQL-statement:</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:fb72fc45-2fd8-466b-ba00-1e7788f85987" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>Disjunction SQL Results</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">SELECT</span> <span style="color: #808080;" color="#808080">*</span> <span style="color: #0000ff;" color="#0000ff">FROM</span> <span style="color: #008080;" color="#008080">Person</span></li>
<li><span style="color: #0000ff;" color="#0000ff">WHERE</span> <span style="color: #008080;" color="#008080">IsArchived</span> <span style="color: #808080;" color="#808080">=</span> 0 <span style="color: #808080;" color="#808080">AND</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #808080;" color="#808080">(</span><span style="color: #008080;" color="#008080">FirstName</span> <span style="color: #808080;" color="#808080">=</span> <span style="color: #008080;" color="#008080">"Nick"</span> <span style="color: #808080;" color="#808080">OR</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008080;" color="#008080">FirstName</span> <span style="color: #808080;" color="#808080">=</span> <span style="color: #008080;" color="#008080">"Dave"</span> <span style="color: #808080;" color="#808080">OR</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008080;" color="#008080">FirstName</span> <span style="color: #808080;" color="#808080">=</span> <span style="color: #008080;" color="#008080">"Bryan"</span> <span style="color: #808080;" color="#808080">OR</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008080;" color="#008080">FirstName</span> <span style="color: #808080;" color="#808080">=</span> <span style="color: #008080;" color="#008080">"James"</span><span style="color: #808080;" color="#808080">)</span></li>
<li><span style="color: #0000ff;" color="#0000ff">ORDER</span> <span style="color: #0000ff;" color="#0000ff">BY</span> <span style="color: #008080;" color="#008080">FirstName</span></li>
</ol></div>
</div>
</div>
<p>If you needed ANDs instead of ORs you would use Conjunction instead of Disjunction.</p>
<p>A more powerful example would be if you needed multiple sets of statements.&nbsp; Consider the following scenario:</p>
<blockquote>
<p>Select all Persons where IsArchived is false and the FirstName is &ldquo;Nick&rdquo;, or all Persons where IsArchived is true and the FirstName is &ldquo;Bryan&rdquo;</p>
</blockquote>
<p>Here&rsquo;s how you would do it using Conjunctions and Disjunctions:</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:dcf14af9-cbdc-4162-b6ae-aaa09bc5cd99" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>Less Contrived Example</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 500px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">using</span> (<span style="color: #2b91af;" color="#2b91af">ISession</span> session = SessionManager.CreateSession())</li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> criteria = session.CreateCriteria&lt;<span style="color: #2b91af;" color="#2b91af">Person</span>&gt;()</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.AddOrder(<span style="color: #2b91af;" color="#2b91af">Order</span>.Asc(<span style="color: #a31515;" color="#a31515">"FirstName"</span>));</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008000;" color="#008000">// IsArchived is FALSE and FirstName = "Nick"</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> conjunction1 = <span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Conjunction();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;conjunction1.Add(<span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Eq(<span style="color: #a31515;" color="#a31515">"IsArchived"</span>, <span style="color: #0000ff;" color="#0000ff">false</span>));</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;conjunction1.Add(<span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Eq(<span style="color: #a31515;" color="#a31515">"FirstName"</span>, <span style="color: #a31515;" color="#a31515">"Nick"</span>));</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008000;" color="#008000">// IsArchived is TRUE and FirstName = "Bryan"</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> conjunction2 = <span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Conjunction();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;conjunction2.Add(<span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Eq(<span style="color: #a31515;" color="#a31515">"IsArchived"</span>, <span style="color: #0000ff;" color="#0000ff">true</span>));</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;conjunction2.Add(<span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Eq(<span style="color: #a31515;" color="#a31515">"FirstName"</span>, <span style="color: #a31515;" color="#a31515">"Bryan"</span>));</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #008000;" color="#008000">// This combines the two statements into an OR</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">var</span> disjunction = <span style="color: #2b91af;" color="#2b91af">Restrictions</span>.Disjunction();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;disjunction.Add(conjunction1);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;disjunction.Add(conjunction2);</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;criteria.Add(disjunction);</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #0000ff;" color="#0000ff">return</span> criteria.List&lt;<span style="color: #2b91af;" color="#2b91af">Person</span>&gt;();</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>Which would produce the following:</p>
<div class="wlWriterEditableSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:68de3cfd-de2b-47b7-929f-acec1c74e7cc" style="margin: 0px; padding: 0px; float: none; display: inline;">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>SQL Results</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">SELECT</span> <span style="color: #808080;" color="#808080">*</span> <span style="color: #0000ff;" color="#0000ff">FROM</span> <span style="color: #008080;" color="#008080">Person</span></li>
<li><span style="color: #0000ff;" color="#0000ff">WHERE</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #808080;" color="#808080">(</span><span style="color: #008080;" color="#008080">IsArchived</span> <span style="color: #808080;" color="#808080">=</span> 0 <span style="color: #808080;" color="#808080">AND</span> <span style="color: #008080;" color="#008080">FirstName</span> <span style="color: #808080;" color="#808080">=</span> <span style="color: #008080;" color="#008080">"Nick"</span><span style="color: #808080;" color="#808080">)</span> <span style="color: #808080;" color="#808080">OR</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #808080;" color="#808080">(</span><span style="color: #008080;" color="#008080">IsArchived</span> <span style="color: #808080;" color="#808080">=</span> 1 <span style="color: #808080;" color="#808080">AND</span> <span style="color: #008080;" color="#008080">FirstName</span> <span style="color: #808080;" color="#808080">=</span> <span style="color: #008080;" color="#008080">"Bryan"</span><span style="color: #808080;" color="#808080">)</span></li>
<li><span style="color: #0000ff;" color="#0000ff">ORDER</span> <span style="color: #0000ff;" color="#0000ff">BY</span> <span style="color: #008080;" color="#008080">FirstName</span></li>
</ol></div>
</div>
</div>]]></content:encoded>
    </item>
    <item>
      <title>Integrating StructureMap, Unit of Work and WCF</title>
      <link>https://docs.microsoft.com/archive/blogs/nkpatterson/integrating-structuremap-unit-of-work-and-wcf</link>
      <pubDate>Sat, 19 Nov 2011 07:30:00 GMT</pubDate>
      <dc:creator><![CDATA[nick.patterson]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nkpatterson/2011/11/19/integrating-structuremap-unit-of-work-and-wcf/</guid>
      <description><![CDATA[When I initially set off on using StructureMap as my IoC of choice on a recent ASP.NET MVC/WCF...]]></description>
      <content:encoded><![CDATA[<p>When I initially set off on using <a href="https://structuremap.net/structuremap/index.html">StructureMap</a> as my IoC of choice on a recent ASP.NET MVC/WCF project, I didn&rsquo;t realize how deep the rabbit hole actually was.&nbsp; Oh, the MVC part was easy.&nbsp; StructureMap integration in an MVC application has been demonstrated a thousand times over and is made even easier with the latest release of ASP.NET MVC 3 and NuGet.&nbsp; Getting StructureMap to serve up objects in a WCF application, now THAT&rsquo;S a horse of a different color.</p>
<h2>Standing on Someone Else&rsquo;s Shoulders</h2>
<p>Two blog posts helped me tremendously when attempting this:</p>
<ul>
<li><a href="https://www.lostechies.com/blogs/jimmy_bogard/default.aspx" target="_blank">Jimmy Bogard&rsquo;s</a> <a href="https://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/29/integrating-structuremap-with-wcf.aspx" target="_blank">Integrating StructureMap with WCF</a> &ndash; lays the ground work for using a custom ServiceHostFactory in order to add customizations at WCF&rsquo;s extension points.</li>
<li><a href="https://andreasohlund.blogspot.com/" target="_blank">Andreas &Ouml;hlund's</a> <a href="https://andreasohlund.blogspot.com/2009/04/unitofwork-in-wcf-using-structuremap.html" target="_blank">UnitOfWork in WCF using StructureMap</a> &ndash; takes Jimmy&rsquo;s post and builds on it using the Unit of Work pattern to automatically initialize, commit or rollback transactions (in my case, NHibernate session transactions) automatically in the WCF pipeline.</li>
</ul>
<p>I highly recommend reading both posts first, in that order.</p>
<h2>Service Request/Response</h2>
<p>Before going any further, I need to take a moment to define the pattern I was using on the project for calling the WCF service layer.&nbsp; For each service operation I defined two data contracts: <em>[OperationName]Request</em>; and <em>[OperationName]Response</em>.&nbsp; Both of these classes are decorated with the <em>DataContract </em>attribute and encapsulated the parameters in both the request and response to the service.&nbsp; This allows the values that are passed into and returned from the service to change without breaking the service contract.&nbsp; Much more flexible, IMHO.&nbsp; Here&rsquo;s an example.</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f4fe3bc0-a3d1-45b1-b53f-06a5d5b12a48" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>IInventoryService</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 500px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li>[<span style="color: #2b91af;" color="#2b91af">ServiceContract</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">interface</span> <span style="color: #2b91af;" color="#2b91af">IInventoryService</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;" color="#2b91af">OperationContract</span>]</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #2b91af;" color="#2b91af">CreateProductResponse</span> CreateProduct(<span style="color: #2b91af;" color="#2b91af">CreateProductRequest</span> request);</li>
<li>}</li>
</ol></div>
</div>
</div>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:7cfe3ed7-fc27-4606-afd1-70f54ac6c60d" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>CreateProductRequest</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li>[<span style="color: #2b91af;" color="#2b91af">DataContract</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">CreateProductRequest</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;" color="#2b91af">DataMember</span>]</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">string</span> Name { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;" color="#2b91af">DataMember</span>]</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">decimal</span> Price { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:8b9f08d7-5546-4573-bef4-4cde98ffd032" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>CreateProductResponse</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li>[<span style="color: #2b91af;" color="#2b91af">DataContract</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">CreateProductResponse</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;" color="#2b91af">DataMember</span>]</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> NewProductId { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<h2>Taking it a Step Further</h2>
<p>Andreas&rsquo; example would rollback the transaction if an unhandled exception was thrown in the WCF application.&nbsp; This is all well and good but I didn&rsquo;t like the idea of throwing exceptions from my service layer.&nbsp; I thought a much cleaner approach would be to return one or more <em>OperationResult</em> objects in the service response object if a problem occurred.&nbsp; An <em>OperationResult</em> would basically just consist of a Key/Message pair that identifies exactly what or where something went wrong (in the Key) as well as details of the error (in the Message).&nbsp; In most cases, this could represent validation errors bubbled up from the domain model.&nbsp; The Key would be the property name that was invalid and the Message would contain, well, the error message of the validation error (e.g., &ldquo;Email address is in the wrong format&rdquo;).&nbsp; But this could also include other, more generic, errors as well.</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:2c7c2cf1-030c-4900-ae63-a9e7c3beab92" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>OperationResult</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li>[<span style="color: #2b91af;" color="#2b91af">Serializable</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">OperationResult</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">string</span> Key { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">string</span> Message { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>I decided to create a base class that contained a collection of <em>OperationResult</em> objects so that I wouldn&rsquo;t have to reinvent the wheel for every Response object I created.&nbsp; It looks like this:</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:56eb2ec4-6488-4546-a1fa-f7b990bba6d4" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>OperationResultResponse</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">interface</span> <span style="color: #2b91af;" color="#2b91af">IOperationResultResponse</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">void</span> AddResult(<span style="color: #0000ff;" color="#0000ff">string</span> key, <span style="color: #0000ff;" color="#0000ff">string</span> message);</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #2b91af;" color="#2b91af">IList</span>&lt;<span style="color: #2b91af;" color="#2b91af">OperationResult</span>&gt; Results { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>}</li>
<li></li>
<li>[<span style="color: #2b91af;" color="#2b91af">DataContract</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">OperationResultResponse</span> : <span style="color: #2b91af;" color="#2b91af">IOperationResultResponse</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">private</span> <span style="color: #0000ff;" color="#0000ff">void</span> initResults()</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">this</span>.Results = <span style="color: #0000ff;" color="#0000ff">new</span> <span style="color: #2b91af;" color="#2b91af">List</span>&lt;<span style="color: #2b91af;" color="#2b91af">OperationResult</span>&gt;();</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #2b91af;" color="#2b91af">IList</span>&lt;<span style="color: #2b91af;" color="#2b91af">OperationResult</span>&gt; Results { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">void</span> AddResult(<span style="color: #0000ff;" color="#0000ff">string</span> key, <span style="color: #0000ff;" color="#0000ff">string</span> message)</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">if</span> (<span style="color: #0000ff;" color="#0000ff">this</span>.Results == <span style="color: #0000ff;" color="#0000ff">null</span>)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; initResults();</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">this</span>.Results.Add(<span style="color: #0000ff;" color="#0000ff">new</span> <span style="color: #2b91af;" color="#2b91af">OperationResult</span> { Key = key, Message = message });</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> OperationResultResponse()</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; initResults();</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>And then, for all (or some, if not applicable) of your response simply inherit from the <em>OperationResultResponse</em> base class.</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:4df4c54d-a5ba-4b6c-b7ba-1139bf8512b9" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>Inherit from response base</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li>[<span style="color: #2b91af;" color="#2b91af">DataContract</span>]</li>
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">CreateProductResponse</span> : <span style="color: #2b91af;" color="#2b91af">OperationResultResponse</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;" color="#2b91af">DataMember</span>]</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">int</span> NewProductId { <span style="color: #0000ff;" color="#0000ff">get</span>; <span style="color: #0000ff;" color="#0000ff">set</span>; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<h2>Where the Magic Happens</h2>
<p>OK, that was a lot of lead up to the big reveal.&nbsp; How do we take this service request/response object model and use it to rollback our Unit of Work (and consequently our NHibernate session transaction)?&nbsp; I got one, err, two, ish words for you: <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iparameterinspector.aspx" target="_blank"><em>IParameterInspector</em></a>.&nbsp; This is another one of WCF&rsquo;s many extensibility points and, like <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.idispatchmessageinspector.aspx" target="_blank"><em>IDispatchMessageInspector</em></a>, it allows you to perform work when a request is received and before a response is sent.&nbsp; In our case, we want to perform the following steps before each response is sent:</p>
<ol>
<li>Get a reference to the Unit of Work for the current request</li>
<li>Check the response object type and see if it implements <em>IOperationResultResponse</em></li>
<li>If the response object DOES implement <em>IOperationResultResponse</em>, interrogate the Results property to see if there are any errors contained therein</li>
<li>If there ARE errors in the Results property, rollback the Unit of Work by calling <em>Rollback()</em></li>
<li>If none of the above applies, call <em>Commit()</em> and <em>Dispose()</em> on the UoW before sending the response on its way</li>
</ol>
<p>Here&rsquo;s what our <em>IParameterInspector</em> implementation looks like:</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:16c3d135-3db5-409f-bd58-12d9c67c2d5c" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>Custom IParameterInspector</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">OperationResultParameterInspector</span> : <span style="color: #2b91af;" color="#2b91af">IParameterInspector</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">private</span> <span style="color: #2b91af;" color="#2b91af">IContainer</span> _container;</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> OperationResultParameterInspector(<span style="color: #2b91af;" color="#2b91af">IContainer</span> container)</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _container = container;</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">void</span> AfterCall(<span style="color: #0000ff;" color="#0000ff">string</span> operationName, <span style="color: #0000ff;" color="#0000ff">object</span>[] outputs, <span style="color: #0000ff;" color="#0000ff">object</span> returnValue, <span style="color: #0000ff;" color="#0000ff">object</span> correlationState)</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Step 1: Get UoW</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">var</span> uow = _container.GetInstance&lt;<span style="color: #2b91af;" color="#2b91af">IUnitOfWork</span>&gt;();</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Step 2: Check for IOperationResult</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">var</span> opResultResponse = returnValue <span style="color: #0000ff;" color="#0000ff">as</span> <span style="color: #2b91af;" color="#2b91af">IOperationResultResponse</span>;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">if</span> (opResultResponse != <span style="color: #0000ff;" color="#0000ff">null</span>)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Step 3: Interrogate Results for errors</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">if</span> (opResultResponse.Results.Count &gt; 0)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Step 4: Rollback our UoW before sending response</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uow.Rollback();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">else</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Step 5: If we're still here, commit and dispose</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uow.Commit();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uow.Dispose();</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">object</span> BeforeCall(<span style="color: #0000ff;" color="#0000ff">string</span> operationName, <span style="color: #0000ff;" color="#0000ff">object</span>[] inputs)</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// No implementation</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">return</span> <span style="color: #0000ff;" color="#0000ff">null</span>;</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<h2>Why We Can&rsquo;t Use <em>BeforeSendReply</em></h2>
<p>We&rsquo;re still going to reuse the Andreas&rsquo; <em>UnitOfWorkMessageInspector</em> to create and initialize the Unit of Work in the <em>AfterReceiveRequest </em>but instead of committing and disposing of the UoW in the <em>BeforeSendReply </em>method, we&rsquo;re going to rely on our parameter inspector&rsquo;s <a href="https://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iparameterinspector.aftercall.aspx" target="_blank"><em>AfterCall</em></a><em> </em>method to do the work.&nbsp; The reason we&rsquo;re not performing the above logic in the <em>BeforeSendReply </em>method of IDispatchMessageInspector is because <em>BeforeSendReply </em>happens AFTER the response has been serialized into a <em>Message </em>object, making it much more difficult to interrogate the values.&nbsp; Believe me, I tried.&nbsp; <em>AfterCall </em>of <em>IParameterInspector </em>is invoked BEFORE the return value has been serialized into a Message object so you can easily just cast the return value to our <em>IOperationResultResponse </em>interface.&nbsp;</p>
<h2>Wiring It All Up</h2>
<p>Wiring up our IParameterInspector is just like wiring up the <em>IDispatchMessageInspectors</em>, <em>IErrorHandlers</em>, etc.&nbsp; Iterate through each <em>EndPoint</em>, get the list of <em>IParameterInspectors&nbsp; </em>(you may have more than one!) from StructureMap and append them to each <em>DispatchOperation</em>.&nbsp; Here&rsquo;s what our updated <em>StructureMapServiceBehavior</em> class looks like.&nbsp; I&rsquo;ve omitted the other details for brevity.</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:bf53c621-900a-43e0-af53-5b0f2c36767c" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>StructureMapServiceBehavior</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">StructureMapServiceBehavior</span> : <span style="color: #2b91af;" color="#2b91af">IServiceBehavior</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">private</span> <span style="color: #2b91af;" color="#2b91af">IContainer</span> _container;</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> StructureMapServiceBehavior(<span style="color: #2b91af;" color="#2b91af">IContainer</span> container)</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _container = container;</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">void</span> Validate(<span style="color: #2b91af;" color="#2b91af">ServiceDescription</span> serviceDescription,</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af;" color="#2b91af">ServiceHostBase</span> serviceHostBase) { <span style="color: #008000;" color="#008000">/* No implementation */</span> }</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">void</span> AddBindingParameters(<span style="color: #2b91af;" color="#2b91af">ServiceDescription</span> serviceDescription,</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af;" color="#2b91af">ServiceHostBase</span> serviceHostBase, <span style="color: #2b91af;" color="#2b91af">Collection</span>&lt;<span style="color: #2b91af;" color="#2b91af">ServiceEndpoint</span>&gt; endpoints,</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af;" color="#2b91af">BindingParameterCollection</span> bindingParameters) { <span style="color: #008000;" color="#008000">/* No implementation */</span> }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">void</span> ApplyDispatchBehavior(<span style="color: #2b91af;" color="#2b91af">ServiceDescription</span> serviceDescription, <span style="color: #2b91af;" color="#2b91af">ServiceHostBase</span> serviceHostBase)</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">foreach</span> (<span style="color: #2b91af;" color="#2b91af">ChannelDispatcherBase</span> cdb <span style="color: #0000ff;" color="#0000ff">in</span> serviceHostBase.ChannelDispatchers)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">var</span> cd = cdb <span style="color: #0000ff;" color="#0000ff">as</span> <span style="color: #2b91af;" color="#2b91af">ChannelDispatcher</span>;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">if</span> (cd != <span style="color: #0000ff;" color="#0000ff">null</span>)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">foreach</span> (<span style="color: #2b91af;" color="#2b91af">EndpointDispatcher</span> ed <span style="color: #0000ff;" color="#0000ff">in</span> cd.Endpoints)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Not shown: Add InstanceContextInitializers, IDispatchMessageInspectors, ICallContextInitializers, etc.</span></li>
<li></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">foreach</span> (<span style="color: #2b91af;" color="#2b91af">DispatchOperation</span> op <span style="color: #0000ff;" color="#0000ff">in</span> ed.DispatchRuntime.Operations)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Add custom IParameterInspectors</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">foreach</span> (<span style="color: #0000ff;" color="#0000ff">var</span> pi <span style="color: #0000ff;" color="#0000ff">in</span> _container.GetAllInstances&lt;<span style="color: #2b91af;" color="#2b91af">IParameterInspector</span>&gt;())</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; op.ParameterInspectors.Add(pi);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Not shown: Add IErrorHandlers</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>And of course, we add the mapping between <em>IParameterInspector</em> and our custom <em>OperationResultParameterInspector</em> in the traditional StructureMap way:</p>
<div style="margin: 0px; padding: 0px; float: none; display: inline;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:b60b4151-d95a-4fa4-9365-de15215f26e2" class="wlWriterEditableSmartContent">
<div style="border: 1px solid #000080; color: black; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background: #000080; padding: 2px 5px; color: white; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold;">
<p>ServicesRegistry</p>
</div>
<div style="background: #dddddd; overflow: auto; max-height: 400px;"><ol style="background: #ffffff; margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px; white-space: nowrap;">
<li><span style="color: #0000ff;" color="#0000ff">public</span> <span style="color: #0000ff;" color="#0000ff">class</span> <span style="color: #2b91af;" color="#2b91af">ServicesRegistry</span> : StructureMap.Configuration.DSL.<span style="color: #2b91af;" color="#2b91af">Registry</span></li>
<li>{</li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: #0000ff;" color="#0000ff">public</span> ServicesRegistry()</li>
<li>&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000;" color="#008000">// Not shown: wiring up all other WCF extensions</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; For&lt;<span style="color: #2b91af;" color="#2b91af">IParameterInspector</span>&gt;().Add&lt;<span style="color: #2b91af;" color="#2b91af">OperationResultParameterInspector</span>&gt;();</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<h2>Conclusion</h2>
<p>This really turned into an exercise in learning the various WCF extension points, what you can and cannot do at each, etc.&nbsp; We&rsquo;ve learned though that the best place for inspecting the actual service response objects before they&rsquo;re sent across the wire is in the <em>AfterCall</em> method of the <em>IParameterInspector </em>interface.</p>]]></content:encoded>
    </item>
  </channel>
</rss>