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

<channel>
	<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Jason Grundy</title>
	<atom:link href="http://elegantcode.com/author/jgrundy/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>File uploads and MVC Controllers</title>
		<link>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=file-uploads-and-mvc-controllers</link>
		<comments>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 16:08:12 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/</guid>
		<description><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What [...]]]></description>
			<content:encoded><![CDATA[Last week I had to implement some functionality to support uploading images to an MVC 2 application and then subsequently display them. Naturally there are a mountain of blog posts on this topic but I was unable to find anything comprehensive that covered everything that I needed on both the client and server side. What follows is my attempt to fill that hole.

My constraints were:
<ol>
	<li>I did not have an HTML form (the application I was working with is very “AJAX heavy”).</li>
	<li>I needed to pass parameters in addition to the file (the ID of the entity that I want to associate the file with).</li>
</ol>
I used the <a href="http://lagoscript.org/jquery/upload?locale=en">jQuery.upload plugin</a> too assist me with both of these. Obviously that means I am also using jQuery.

Let’s look at the code. Here’s the Content from my View:
<div class="csharpcode">
<pre class="alt">Select File to Upload: <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">id</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="kwrd">/&gt;</span></pre>
<pre><span class="kwrd">&lt;</span><span class="html">img</span> <span class="attr">id</span><span class="kwrd">="fileView"</span> <span class="kwrd">/&gt;</span></pre>
<pre class="alt"></pre>
<pre><span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">    $(document).ready(<span class="kwrd">function</span> () {</pre>
<pre>        $(<span class="str">'#file'</span>).change(<span class="kwrd">function</span> () {</pre>
<pre class="alt">            <span class="kwrd">var</span> data = { ID: <span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span> };</pre>
<pre>            $(<span class="kwrd">this</span>).upload(</pre>
<pre class="alt">                <span class="str">"FileUpload/AttachFileToEntity"</span>,</pre>
<pre>                data,</pre>
<pre class="alt">                <span class="kwrd">function</span> () {</pre>
<pre>                    $(<span class="str">"#fileView"</span>).attr(<span class="str">"src"</span>, <span class="str">"FileUpload/GetFileDataFromEntity/"</span> + data.ID);</pre>
<pre class="alt">                }</pre>
<pre>            );</pre>
<pre class="alt">        });</pre>
<pre>    });</pre>
<pre class="alt"><span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->I am simply attaching an change event handler the the &lt;input type=”file” /&gt; control. The event handler does two things:
<ol>
	<li>Uploads the selected file</li>
	<li>Displays it. I am assuming that you are uploading an image (but not verifying this)</li>
</ol>
Note that the name attribute of the input control must be set and it must match the name of the HttpPostedFileBase parameter in the AttachFileToEntity Controller Action. Speaking of the Controller here it is:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> FileUploadController : Controller</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">readonly</span> EntityRepository _entityRepository = <span class="kwrd">new</span> EntityRepository();</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> ActionResult Get()</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> View();</pre>
<pre>    }</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> ActionResult AttachFileToEntity(Guid ID, HttpPostedFileBase file)</pre>
<pre class="alt">    {</pre>
<pre>        var entity = _entityRepository.Get(ID);</pre>
<pre class="alt"></pre>
<pre>        entity.FileData = GetFileData(file);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> Content(<span class="str">"File saved"</span>);</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">byte</span>[] GetFileData(HttpPostedFileBase file)</pre>
<pre>    {</pre>
<pre class="alt">        var length = file.ContentLength;</pre>
<pre>        var fileContent = <span class="kwrd">new</span> <span class="kwrd">byte</span>[length];</pre>
<pre class="alt"></pre>
<pre>        file.InputStream.Read(fileContent, 0, length);</pre>
<pre class="alt"></pre>
<pre>        <span class="kwrd">return</span> fileContent;</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> FileResult GetFileDataFromEntity(Guid ID)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">return</span> File(_entityRepository.Get(ID).FileData, <span class="str">"image"</span>);</pre>
<pre>    }</pre>
<pre class="alt">}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->The imaginatively named Entity could not be simpler:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> Entity</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">public</span> Guid ID { get; set; }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">byte</span>[] FileData { get; set; }</pre>
<pre>}</pre>
</div>
<!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->In a production scenario you are using probably using an O/RM such as NHibernate. In this case you will want to deviate from what I have above and store the uploaded file in a different entity. This is to avoid having to load the binary data for the file each time you access the entity. Note that NHibernate 3 supports (to a limited degree) <a href="http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx">lazy loading properties</a>. However even if you are utilizing this feature you still want to make sure that the binary data is stored in a different table in the underlying RDBMS so that any full table scans (for example if you are performing some type of aggregation) don’t end up reading mountains of irrelevant data.

The one thing that you are missing is the Repository. Rather than introduce the complexity of data access I am simply using a static Dictionary to store the data:
<div class="csharpcode">
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> EntityRepository</pre>
<pre>{</pre>
<pre class="alt">    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> IDictionary&lt;Guid, Entity&gt; _entities = <span class="kwrd">new</span> Dictionary&lt;Guid, Entity&gt;</pre>
<pre>    {</pre>
<pre class="alt">        { <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>), <span class="kwrd">new</span> Entity { ID = <span class="kwrd">new</span> Guid(<span class="str">"b53dd6b4-f24c-4450-bf6a-246e5835a125"</span>) }}</pre>
<pre>    };</pre>
<pre class="alt"></pre>
<pre>    <span class="kwrd">public</span> Entity Get(Guid ID)</pre>
<pre class="alt">    {</pre>
<pre>        <span class="kwrd">return</span> _entities[ID];</pre>
<pre class="alt">    }</pre>
<pre></pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">void</span> Save(Entity entity)</pre>
<pre>    {</pre>
<pre class="alt">        <span class="kwrd">if</span> (entity.ID == Guid.Empty) entity.ID = Guid.NewGuid();</pre>
<pre></pre>
<pre class="alt">        <span class="kwrd">if</span> (_entities.ContainsKey(entity.ID)) _entities[entity.ID] = entity;</pre>
<pre>        <span class="kwrd">else</span> _entities.Add(entity.ID, entity);</pre>
<pre class="alt">    }</pre>
<pre>}</pre>
<pre></pre>
</div>
That’s everything you need. Hope that you find this useful.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/27/file-uploads-and-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate, HttpModules, ASP.NET JSON Web Services and Database Transactions</title>
		<link>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions</link>
		<comments>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:08:03 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/</guid>
		<description><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play: An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor ) NHibernate The use [...]]]></description>
			<content:encoded><![CDATA[First of all sorry for the frankly appalling title which is actually longer than some of my posts. In order to explain let’s start with a problem definition. These are the elements that were in play:
<ol>
	<li>An ASP.NET 3.5 Web Forms based website (although #3 below is really the key factor )</li>
	<li>NHibernate</li>
	<li>The use of an HttpModule to implement the <a href="https://www.hibernate.org/43.html">Open Session in View</a> pattern and provide a Unit of Work implementation (one ISession per HTTP request)</li>
	<li>ASP.NET web services returning JSON (might well be a problem if the result was XML as well)</li>
</ol>
In an “old fashioned” Web Forms scenario everything works perfectly. If some unexpected event occurs during a postback then an Exception is thrown and it bubbles up to the HttpModule which rolls back the transaction.

However with a JSON web service (we’re not using WCF so we just have an System.Web.Services.WebService flagged with a ScriptService attribute) when an unexpected event occurs the magic of the framework catches it and the ScriptMethod simply returns the Exception converted to JSON. This was being correctly handled in our UI but because an Exception is not thrown so the HttpModule thinks that everything is OK and incorrectly commits our transaction. And because processing didn’t necessarily finish and our data could therefore get into an inconsistent state (which is even worse than a plain wrong state).

In order to work around this feature I hooked into the EndRequest event in the HttpModule and check the StatusCode of the Repsonse. Here’s the method that I created:
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAjaxError()
{
  <span class="kwrd">return</span> HttpContext.Current.Response.StatusCode == 500 &amp;&amp; HttpContext.Current.Request.RawUrl.Contains(<span class="str">".asmx"</span>);
}</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

Obviously if an error is detected I can take the appropriate action. So if you’re using the above combination of technologies be careful because what you think is happening and what is happening might be two entirely different things.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/03/18/nhibernate-httpmodules-asp-net-json-web-services-and-database-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running ASP.NET applications from a remote share</title>
		<link>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-asp-net-applications-from-a-remote-share</link>
		<comments>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 23:10:09 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/</guid>
		<description><![CDATA[This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not [...]]]></description>
			<content:encoded><![CDATA[<p>This is as much a reminder to myself for the future as anything. But I am going to start with a boast - I have a swanky new PC! I am trying to do everything in VMs (I know that a lot of people have tried this and failed but I am nothing if not altruistic). I want to keep all of my source in one place and share it between the VMs. However even though I could open the Solution in Visual Studio when I went to run it I would encounter the following error:</p>  <p>&#160;</p>  <div style="background-color: #f8f8f8">   <h3 style="color: red">Server Error in '/' Application.      <hr size="1" width="100%" /></h3>    <h4 style="color: maroon"><i>Security Exception</i></h4>   <b>Description: </b>The application attempted to perform an operation not allowed by the security policy.&#160; To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.     <br /><b>Exception Details: </b>System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.     <br /><b>Source Error:</b>     <p style="background-color: #ffffcc"><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code></p>    <p><b>Stack Trace:</b></p>    <p><code></code></p>    <pre style="background-color: #ffffcc">[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
   System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) +42
   System.Web.UI.Util.GetTypeFromAssemblies(ICollection assemblies, String typeName, Boolean ignoreCase) +145
   System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) +73
   System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) +111
   System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) +279</pre>

  <hr size="1" width="100%" /><b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 </div>

<p>&#160;</p>

<p>I knew that some sort of trust issue was the problem and after some Googling I came across <a href="http://support.microsoft.com/?id=320268">this article</a> that explained this problem and more importantly provided a solution. The pertinent command to execute was:</p>

<pre>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url &quot;file:////\computername\sharename\*&quot; FullTrust -exclusive on</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/running-asp-net-applications-from-a-remote-share/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Why Future&lt;T&gt; should be in your future</title>
		<link>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-futuret-should-be-in-your-future</link>
		<comments>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:50:24 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/</guid>
		<description><![CDATA[Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature [...]]]></description>
			<content:encoded><![CDATA[<p>Even though NHibernate 3.0 is on the way I am going to highlight a feature that was introduced in v2.1 but that relatively few people seem to be using (at least in the code bases I have seen recently). Former ECer Davy Brion, as always, does an excellent job of demonstrating usage of the feature <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">here</a> so I am not going to rehash that. What I am going to focus on here if the why.</p>  <p>Building a UI can be a very database intensive operation in terms of the number of separate calls required. And for each one of those calls the time taken to actually execute the query can be a small compared to the duration of the roundtrip to request and fetch the data. The obvious solution is some type of batching and with Future&lt;T&gt; this happens automagically without any change to the consuming logic (for databases that support it). Let me restate that, you get a huge performance benefit with only a simple change to your query methods in the Repository. So why aren’t you using it?</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/16/why-futuret-should-be-in-your-future/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using the jQuery UI Datepicker with ASP.NET MVC 2 Templates</title>
		<link>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates</link>
		<comments>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:25:10 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/</guid>
		<description><![CDATA[Brad Wilson has recently completed a blog series about Templates in MVC 2. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the [...]]]></description>
			<content:encoded><![CDATA[Brad Wilson has recently completed a blog series about <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html">Templates in MVC 2</a>. I really like this feature as it provides me with the ability to quickly generate screens, even if eventually I might have to go back and rework them. Basically I want to have my cake and eat it – I want the initial productivity of a scaffolding based approach but the flexibility to customize look and feel when required.

By default an text box is generated for DateTime fields. What I wanted to do was hook this up to the excellent Datepicker widget from <a href="http://jqueryui.com/demos/datepicker/">jQuery UI</a>. Here’s how I achieved this:
<ol>
	<li>Add the following 3 references to the Master Page:

&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</a>&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"</a>&gt;&lt;/script&gt;
&lt;link href="<a href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css&quot;">http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/overcast/jquery-ui.css"</a> type="text/css" rel="Stylesheet" class="ui-theme" /&gt;

I am referencing jQUery and jQUery UI from the Google CDN (great for getting started quickly as well as for production scenarios). I am also linking to one of the <a href="http://jqueryui.com/themeroller/">default themes</a> which goes nicely with the default MVC stylesheet.</li>
	<li>Add the following Javascript to the Master Page:&lt;script type="text/javascript"&gt;
$(function () {
$(".date-edit-box").datepicker();
});
&lt;/script&gt;

Here I am simply looking for a specific class and attaching a Datepicker widget to it. I am aware that this is not the most efficient approach as the code might run unnecessarily but it’s perfect for a demo.</li>
	<li>Ensure that the correct class is rendered by the Template. Apparently you can currently only override the default templates for individual Controllers. Therefore create a Views/{ControllerName}/EditorTemplates folder and within it create a file called DateTime.ascx which should contain:</li>
&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;

&lt;%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date-edit-box" }) %&gt;
	<li>You’ll probably want to use the DIsplayFormatAttribute on the DateTime fields in the View Model to ensure that the time is not also output (don’t forget to set the ApplyFormatInEditMode property to true if you do this).</li>
</ol>
That’s it. You should now see Datepickers for the appropriate fields that were rendered using the Html.EditorForModel() extension method.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/13/using-the-jquery-ui-datepicker-with-asp-net-mvc-2-templates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>NHibernate 3.0 QueryOver</title>
		<link>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nhibernate-3-0-queryover</link>
		<comments>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 19:23:53 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/</guid>
		<description><![CDATA[One of the personal reasons that I had for co-founding Guild 3 was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in Avoiding (Or Recovering From) Burnout. For me the age old adage of “a change is as good as a rest” [...]]]></description>
			<content:encoded><![CDATA[One of the personal reasons that I had for co-founding <a href="http://guild3.com">Guild 3</a> was for me to re-discover my passion for software. I was suffering from something similar to what Davy Brion (quite bravely) outlined in <a href="http://davybrion.com/blog/2009/09/avoiding-or-recovering-from-burnout/">Avoiding (Or Recovering From) Burnout</a>. For me the age old adage of “a change is as good as a rest” has proven to be an extremely successful strategy.

One of the things that I had stopped doing was keeping an eye on various OSS projects to see what was on the horizon. Yesterday I (finally!) started to experiment with NHibernate 3.0. The first thing that caught my eye was <a href="http://fabiomaulo.blogspot.com/2009/06/criteria-on-nh300.html">QueryOver</a>. As Fabio explained there are a <a href="http://fabiomaulo.blogspot.com/2009/09/nhibernate-queries.html">lot of different ways of executing queries in NH</a>. Certainly in the pre-LINQ days ICriteria was the predominantly recommended option because it has elements of type safety to it and its fluent-ish API broke everything down into small pieces and avoided string concatenation hell.

QueryOver is fluent a layer on top of ICriteria. It looks very LINQesque but it’s a very different animal, not least of all because there are some concepts in ICriteria that do not have a LINQ equivalent (caching etc.). In the short to medium term I suspect that it will become my de facto approach for NHibernate queries (I’ve used NHibernate LINQ and it’s great for simple queries but I’ve experienced significant issues with more complicated ones).

What I haven’t figured out yet is how, if at all, this will affect my data access testing strategy. Historically I’ve favored smoke tests that have really been doing little more than verifying that a given ICriteria query was semantically valid. Typically I only resorted to actually worrying about the results in specific cases (mainly due to the burden of maintaining test data for each possible scenario). Then again this sounds like a topic for another post doesn’t it…]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/12/nhibernate-3-0-queryover/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using serialized JSON to move complex data to and from the browser</title>
		<link>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-serialized-json-to-move-complex-data-to-and-from-the-browser</link>
		<comments>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/</guid>
		<description><![CDATA[Jarod and I have both been working on a FubuMVC application for one of our Guild 3 clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a> and I have both been working on a <a href="http://code.google.com/p/fubumvc/">FubuMVC</a> application for one of our <a href="http://guild3.com">Guild 3</a> clients. It’s been great to have the opportunity to work with a different MVC framework and hopefully we’ll comment on what we did and didn’t like about Fubu in a follow up post. I should note at this point that the technique outlined below is not limited to Fubu, in fact it would also work with ASP.NET MVC or even Web Forms.</p>  <p>On one of the Views I had to move a collection of complex data from the client to the server. By complex I mean more than just a single property. An example of this might be editable rows in a table (yes I know that there are other ways to solve this problem such as using AJAX but please stick with me). In addition I didn’t like the fact that there was a duplication of the presentation logic – server side binding during the initial rendering and client side binding if data was changed. I’ve seen a lot of bugs in the past with this approach when someone makes server or client side changes but forgets about the other piece.</p>  <p>I decided to used JSON as a common currency for this part of the UI. I removed the server side binding. Then on the server side I created a Display Model (a View Model for a subset of the View) to represent the data that I needed to display and edit. I can serialize this to JSON (new JavaScriptSerializer().Serialize(myDisplayModel)). I can subsequently access the JSON via an AJAX request or I can stuff it into the DOM if I am sensitive about the number of calls being made (which I was here). On the client side I used a <a href="http://code.google.com/p/jquery-json/">JQuery plugin</a> ($.evalJSON(myJsonString)) to convert the JSON into a form that is easily consumable in Javascript. I could therefore use the same code to initially populate the UI and deal with any edits.</p>  <p>When an edit was made I simply update the UI and store the new JSON in the DOM ($.toJSON(myJSonObject)). When the form was submitted back to the server I can easily deserialize the JSON (new JavaScriptSerializer().Deserialize&lt;myDisplayModel&gt;(myJsonString);) and then manipulate it as I see fit.</p>  <p>What is nice about this technique is it allows both the client and the server to work with the same Display Model. It also resulted in nice clean “object.Property” Javascript.</p>  <p>As always any feedback or alternative approaches would be greatly appreciated.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/06/using-serialized-json-to-move-complex-data-to-and-from-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Form &#8211; Storm &#8211; Norm &#8211; Perform</title>
		<link>http://elegantcode.com/2009/11/02/form-storm-norm-perform/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=form-storm-norm-perform</link>
		<comments>http://elegantcode.com/2009/11/02/form-storm-norm-perform/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:49:45 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/02/form-storm-norm-perform/</guid>
		<description><![CDATA[As you probably know by now three Elegant Coders (Jarod, David and myself) have recently formed Guild 3 Software. One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are Integrity, Craftsmanship, Agility and Community. However we had not worked together [...]]]></description>
			<content:encoded><![CDATA[<p>As you <a href="http://elegantcode.com/2009/10/20/introducing-guild-3-software/">probably know by now</a> three Elegant Coders (<a href="http://elegantcode.com/author/ferguson/feed/">Jarod</a>, <a href="http://feeds2.feedburner.com/DStarr">David</a> and myself) have recently formed <a href="http://www.guild3.com/">Guild 3 Software</a>.</p>  <p>One of the reasons that we were keen to work together is that we have a lot of shared values, not least of which are <a href="http://guild3.com/founding-values">Integrity, Craftsmanship, Agility and Community</a>. However we had not worked together before. And despite our ideological common ground there are always challenges with any new team. One method of visualizing the stages that you typically go through in this scenario is a model known as <a href="http://en.wikipedia.org/wiki/Forming-storming-norming-performing">Form – Storm – Norm – Perform</a>.</p>  <p>I’m not going to explain the concept as the referenced Wikipedia article does an excellent job of that. However I do want to emphasize that any subsequent changes in the team or the context within which it operates take everyone back to the beginning of the process. Of course if the change is small then the duration of the cycle will often be commensurately short. Understanding the process that we were going through and its psychological ramifications has certainly enabled us to be successful. I hope that it helps you too.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/02/form-storm-norm-perform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I know because I can read</title>
		<link>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-know-because-i-can-read</link>
		<comments>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 15:16:16 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/06/04/i-know-because-i-can-read/</guid>
		<description><![CDATA[Jason: There’s an issue with your stupid threading code. (Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it [...]]]></description>
			<content:encoded><![CDATA[<p>Jason: There’s an issue with your stupid threading code.</p>  <p>(Don’t jump all over me for not fixing the problem myself or the way that I brought up the fact that there was one. We have an excellent working relationship that allows for this type of interaction / humor. And we benefit a lot from it as when the other party can’t be offended you get to the point quickly, agree a solution and move on).</p>  <p>Priyesh (incredulously): How can you be sure that it’s a threading issue?</p>  <p>Jason: Because the error message is “System.Threading.ThreadAbortException: Thread was being aborted”</p>  <p>Priyesh: Ah, you’re probably right then.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/06/04/i-know-because-i-can-read/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Priyesh&#8217;s Law of Excessive Separation</title>
		<link>http://elegantcode.com/2009/05/15/priyeshs-law-of-excessive-separation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=priyeshs-law-of-excessive-separation</link>
		<comments>http://elegantcode.com/2009/05/15/priyeshs-law-of-excessive-separation/#comments</comments>
		<pubDate>Fri, 15 May 2009 17:18:02 +0000</pubDate>
		<dc:creator>Jason Grundy</dc:creator>
				<category><![CDATA[Esoterica]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/05/15/priyeshs-law-of-excessive-separation/</guid>
		<description><![CDATA[I just finished a discussion with about the structure of a particular class with one of my coworkers. One part of the conversation that I found extremely amusing went like this: Jason: I would argue that the logic that acts upon the collection your iterating over should be moved to a separate method. There’s even [...]]]></description>
			<content:encoded><![CDATA[<p>I just finished a discussion with about the structure of a particular class with one of my coworkers. One part of the conversation that I found extremely amusing went like this:</p>  <blockquote>   <p>Jason: I would argue that the logic that acts upon the collection your iterating over should be moved to a separate method. There’s even a fancy name for this although I can’t remember what it’s called.</p>    <p>Priyesh: I believe that’s called the Law of Excessive Separation!</p> </blockquote>  <p>You’d never guess that Priyesh has a heavy C background!</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/05/15/priyeshs-law-of-excessive-separation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

