<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Martijn Boland</title>
	
	<link>http://blogs.taiga.nl/martijn</link>
	<description>New adventures in .NET</description>
	<lastBuildDate>Tue, 24 Apr 2012 08:35:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/martijnboland" /><feedburner:info uri="martijnboland" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>MvcPaging 2.0</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/N2AhyP_1XFE/</link>
		<comments>http://blogs.taiga.nl/martijn/2012/04/23/mvcpaging-2-0/#comments</comments>
		<pubDate>Mon, 23 Apr 2012 20:06:47 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/?p=246</guid>
		<description><![CDATA[&#160; Last week, a new version of the MvcPaging library has been released. This time there are some breaking changes and that’s why the major version number is increased. What’s new: Simplified API with reduced number of Html.Pager overloads; DisplayTemplate option and PaginationModel; Configurable number of pages. Simplified API There have been some requests for <a href="http://blogs.taiga.nl/martijn/2012/04/23/mvcpaging-2-0/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2012/04/image2.png" width="399" height="39" /></p>
<p>Last week, a new version of the <a href="http://github.com/martijnboland/mvcpaging">MvcPaging</a> library has <a href="http://nuget.org/packages/MvcPaging">been released</a>. This time there are some breaking changes and that’s why the major version number is increased. </p>
<p>What’s new:</p>
<ul>
<li><font color="#111111">Simplified API with reduced number of Html.Pager overloads;</font></li>
<li><font color="#111111">DisplayTemplate option and PaginationModel;</font></li>
<li><font color="#111111">Configurable number of pages.</font></li>
</ul>
<h3>Simplified API</h3>
<p>There have been some requests for extra configuration options, but I didn’t want to add more overloads to the Html.Pager helper. Instead, the number of overloads is reduced drastically:</p>
<pre class="brush: csharp;">Html.Pager(int pageSize, int currentPage, int totalItemCount)</pre>
<p>and</p>
<pre class="brush: csharp;">Html.Pager(int pageSize, int currentPage, int totalItemCount, AjaxOptions ajaxOptions)</pre>
<p>We now only have a method with the <em>required</em> parameters and one overload for Ajax scenarios. Also, the Ajax.Pager helper is removed. Note that this is a breaking change, so if you were using the Ajax.Pager helper, you now have to use the Html.Pager with the AjaxOptions overload.</p>
<p>Non-required configuration options are added via the Options() method. This interface also replaces the overloads in the previous version where you could set route values or controller actions. This is the second breaking change. You can now only set these values via the Options method.</p>
<pre class="brush: csharp;">Html.Pager(pageSize, pageNumber, totalItemCount).Options(o =&gt; o
    .Action(&quot;action&quot;)
    .AddRouteValue(&quot;q&quot;, mySearchQuery)
)</pre>
<p><font color="#444444">Below are all options:</font></p>
<ul>
<li><strong>Action</strong>(string action)
<p>Sets an alternative action for the pager that is different from the current action.</li>
<li><strong>AddRouteValue</strong>(string name, object value)
<p>Adds a single route value parameter that is added to page url&#8217;s.</li>
<li><strong>RouteValues</strong>(object routeValues)
<p> Adds route value parameters that are added to the page url&#8217;s.</li>
<li><strong>RouteValues</strong>(RouteValueDictionary routeValues)
<p> Adds route value parameters that are added to the page url&#8217;s.</li>
<li><strong>DisplayTemplate</strong>(string displayTemplate)
<p> When set, the internal HTML rendering is bypassed and a DisplayTemplate view with the given name is rendered instead. Note that the DisplayTemplate must have a model of type PaginationModel.</li>
<li><strong>MaxNrOfPages</strong>(int maxNrOfPages)
<p> Sets the maximum number of pages to show.</li>
</ul>
<h3>DisplayTemplate option</h3>
<p>A few people have been asking for configurable rendering, especially since <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> has become popular. <a href="https://github.com/cvrajeesh">Rajeesh CV</a> submitted a pull request that introduced a view model for the Pager, the PaginationModel. This view model made it very easy to create an option where you can specify a DisplayTemplate that is used for the actual rendering. It works like any other ASP.NET MVC DisplayTemplate and requires a model of PaginationModel. As a bonus, the PaginationModel makes unit testing a lot easier.</p>
<p>The <a href="https://github.com/martijnboland/MvcPaging/tree/master/src/MvcPaging.Demo">MvcPaging.Demo</a> project has an example <a href="https://github.com/martijnboland/MvcPaging/tree/master/src/MvcPaging.Demo/Views/Shared/DisplayTemplates">DisplayTemplate</a> that renders Html that is compatible with Twitter Bootstrap:</p>
<pre class="brush: csharp;">Html.Pager(pageSize, pageNumber, totalItemCount).Options(o =&gt; o
    .DisplayTemplate(&quot;BootstrapPagination&quot;)
    .MaxNrOfPages(14))</pre>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2012/04/image3.png" width="522" height="339" /></p>
<h3>Configurable number of pages</h3>
<p>As you can see in&#160; the screenshot above, the pager can now be configured to show more or less than 10 pages via the MaxNrOfPages() option.</p>
<p>I’d like to thank <a href="https://github.com/cvrajeesh">Rajeesh CV</a>, <a href="https://github.com/jbucht01">jbucht01</a> for the contributions and ideas. For more information, visit the <a href="http://github.com/martijnboland/mvcpaging">GitHub project page</a>, or install the Pager in your own projects with <a href="http://nuget.org/packages/MvcPaging">NuGet</a>.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=N2AhyP_1XFE:KliC-l1Ngcc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=N2AhyP_1XFE:KliC-l1Ngcc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=N2AhyP_1XFE:KliC-l1Ngcc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=N2AhyP_1XFE:KliC-l1Ngcc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/N2AhyP_1XFE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2012/04/23/mvcpaging-2-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2012/04/23/mvcpaging-2-0/</feedburner:origLink></item>
		<item>
		<title>Introducing Actya – a .NET CMS that doesn’t get in your way</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/U9eZdmvzi6I/</link>
		<comments>http://blogs.taiga.nl/martijn/2012/01/23/introducing-actya/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 11:42:00 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[Actya]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[CMS]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[RavenDB]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/?p=227</guid>
		<description><![CDATA[Actya is a simple open source ASP.NET MVC Content Management System (CMS). Why on earth would we need another CMS? Quite often, a CMS is chosen as application framework for custom application development because you’ll get a lot for free: navigation, security and content management (obviously). Custom applications are then developed as modules that run <a href="http://blogs.taiga.nl/martijn/2012/01/23/introducing-actya/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://actya.codeplex.com">Actya</a> is a simple open source ASP.NET MVC Content Management System (CMS).</p>
<h2>Why on earth would we need another CMS?</h2>
<p>Quite often, a CMS is chosen as application framework for custom application development because you’ll get a lot for free: navigation, security and content management (obviously). Custom applications are then developed as modules that run within the context of the CMS. <a href="http://cuyahoga-project.org">Cuyahoga</a>, the CMS I’ve started  8 years ago works exactly like this.</p>
<p>Rob Conery <a href="http://wekeroad.com/2011/12/06/nuget-and-orchard/">describes an issue with this solution</a>:</p>
<blockquote><p>I’ve deployed Big CMS’s before as a solution for clients and every single time we decided to move away. They’re great for getting off the ground – but after a while there’s jus too much friction.</p></blockquote>
<p>And that’s probably what many of us experience: a CMS gets in the way when your main focus is the custom application. This is the single main reason to create Actya: <strong>a CMS that doesn’t get in your way when doing custom development.</strong></p>
<h2><span style="color: #111111;">CMS as add-on</span></h2>
<p>Actya can act as an add-on library for your application. While developing your custom application in Visual Studio, you can add it with <a href="http://nuget.org/packages/actya">NuGet</a> just like any other library. The first time you run your application after adding Actya, an installer kicks in to ask you where you want to have your CMS data stored, what theme you want to use and which account is the CMS administrator. No further configuration required <strong>and nothing has to change in your custom application.</strong></p>
<p>The video below shows this scenario with <a href="https://github.com/nuget/nugetgallery">NuGetGallery</a> as the ‘custom’ application:</p>
<div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:336ff211-5b84-4b16-a7bf-1637ab8400da" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<div><object width="448" height="252" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://www.youtube.com/v/AnwwcO26zuU?hl=en&amp;hd=1" /><embed width="448" height="252" type="application/x-shockwave-flash" src="http://www.youtube.com/v/AnwwcO26zuU?hl=en&amp;hd=1" /></object></div>
</div>
<p>Even though Actya is mainly designed to act as an add-on CMS, you can also use it as a simple regular CMS. Download it at from <a href="http://actya.codeplex.com/releases/">CodePlex downloads page</a>, point an IIS 7+ web site or application to the extracted files, open de site in your browser and the installation starts automatically.</p>
<p>After installation, you can access Actya’s admin pages at <a href="http://my-host-or-application/cmsadmin">http://<em>my-host-or-application</em>/<strong>cmsadmin</strong>.</a></p>
<h2>RavenDB document database</h2>
<p>Here’s the other reason for creating Actya: schema-less <a href="http://en.wikipedia.org/wiki/NoSQL">NoSQL</a> databases are considered to be ideal for CMS applications because you can put any type of content in it without having to alter a database schema or have some kind of monstrous <a href="http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model">Entity-Attribute-Value</a> model. I wanted to experience if that claim is true.</p>
<p>Actya uses the .NET NoSQL database <a href="http://ravendb.net">RavenDB</a> and it really makes development easier. Not only due to the flexibility of the schema-less design but also to the absence of a mapping layer. Wonderful! A cool feature of RavenDB is the embedded mode where you don’t need a database server at all. Actya uses this mode by default (the data goes in App_Data), but can also connect to an existing RavenDB server.</p>
<h2></h2>
<h2></h2>
<h2>Requirements</h2>
<ul>
<li><span style="color: #111111;">ASP.NET 4.0</span></li>
<li><span style="color: #111111;">Full-Trust environment</span></li>
</ul>
<h2>Wanted: Feedback</h2>
<p>I’ve released the first alpha version to see if anybody finds this CMS useful. Your feedback will have a have a lot of weight in determining future development. If you have any, please go to <a href="http://actya.codeplex.com/discussions">http://actya.codeplex.com/discussions</a> and open a discussion with ‘User Feedback’ as topic.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=U9eZdmvzi6I:zMF_OhSw7bk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=U9eZdmvzi6I:zMF_OhSw7bk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=U9eZdmvzi6I:zMF_OhSw7bk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=U9eZdmvzi6I:zMF_OhSw7bk:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/U9eZdmvzi6I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2012/01/23/introducing-actya/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2012/01/23/introducing-actya/</feedburner:origLink></item>
		<item>
		<title>Entity Framework 4 tips for NHibernate users</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/clJWysL8_jk/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/12/15/entity-framework-4-tips-for-nhibernate-users/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 09:25:25 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[O/R mapping]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/?p=212</guid>
		<description><![CDATA[The last few weeks, I have worked on a project that uses Entity Framework 4 Code First (let’s call it EF from now). Normally, I use NHibernate for my OR-mapping needs and although EF works almost the same conceptually, there are differences. This post is about some of the issues that an NHibernate user can <a href="http://blogs.taiga.nl/martijn/2011/12/15/entity-framework-4-tips-for-nhibernate-users/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The last few weeks, I have worked on a project that uses <a href="http://msdn.microsoft.com/en-us/data/aa937723">Entity Framework 4 Code First</a> (let’s call it EF from now). Normally, I use <a href="http://nhforge.org/">NHibernate</a> for my OR-mapping needs and although EF works almost the same conceptually, there are differences. This post is about some of the issues that an NHibernate user can expect when working with EF. </p>
<h3>Many to one associations and introduce a foreign key property</h3>
<p>Let’s say it bluntly: EF supports <a href="http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx">Foreign Key associations</a>&#160; (foreign key id’s in your entities, besides many to one associations)&#160; and you better use them, or you’ll experience a lot of pain. I started to model my entities with ‘proper’ object references but ran into 2 problems:</p>
<ul>
<li>Filtering in collection properties causes select n+1 issues. So forget:      <br /> 
<pre class="brush: csharp;">Order.OrderLines.Where(ol =&gt; ol.Product.Id == productId)</pre>
<p>but do: </p>
<p></p>
<pre class="brush: csharp;">Order.OrderLines.Where(ol =&gt; ol.ProductId == productId)</pre>
<p>to filter a collection property because the first will load all product instances; </li>
<li>When you override Equals() and GetHashCode()in your entities to use only the ID for object equality, you can assign an empty object with only the ID set as reference property in NHibernate but EF doesn’t fall for this trick. This is can be very useful, for example when setting references from a dropdownlist where you only have an ID of the referenced object. </li>
</ul>
<p>It seems that EF just doesn’t leverage proxies like NHibernate does so it needs to have the actual object instance to do things instead of just the proxy.<br />
  <br />The good thing however is that when you’re having both a foreign key ID property and an object reference in EF, these are synced automatically and only one column will be generated in the database and the only real issue is a little pollution of your entity.</p>
<h3>Object reference not set to an instance of an object</h3>
<p>So you’ve created a nice object graph and saved it in the database. Then after fetching the object graph back, some of the referenced objects are null even when the ID’s of the references are nicely sitting there in the database. WTF???<br />
  <br />Well, EF doesn’t automatically load a referenced object unless it’s marked as virtual (lazy) or loaded explicitly via Include(). If you forget both, you’ll end up with the NullReferenceExceptions.</p>
<h3>No Dictionary collection mapping</h3>
<p>This is something not many people complain about, but I really miss the option to map dictionaries like Map in NHibernate. Also, NHibernate’s List mappings are not supported. </p>
<h3>Cascade is a big black box</h3>
<p>EF doesn’t have a way to specify how changes in your entity are cascaded into related entities. I’m not sure if this is a good or a bad thing. On one hand I miss having control over this, but on the other hand EF seemed to do well without setting anything.<br />
  <br />Out of the box, EF code first generates CASCADE&#160; DELETE database constraints on required associations but when your model gets only a little bit complex, you’ll get errors like “Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths”. Fortunately, you can turn this off in your DbContext:</p>
<pre class="brush: csharp;">protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Remove cascade delete convention because it causes trouble when generating the DB.
    modelBuilder.Conventions.Remove&lt;OneToManyCascadeDeleteConvention&gt;();

    base.OnModelCreating(modelBuilder);
}</pre>
<h3>Explicitly set state when attaching objects to the DbContext</h3>
<p>In NHibernate you can simply update an object that isn’t associated with a Session via Session.Update(). EF can do the same via Attach() but you must not forget to explicitly set the object state to modified, otherwise no updates occur:</p>
<pre class="brush: csharp;">dbContext.Customers.Attach(customer);
dbContext.Entry(customer).State = EntityState.Modified;
dbContext.SaveChanges();</pre>
<h3>More?</h3>
<p>Please leave a comment if you want to share your own experiences.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=clJWysL8_jk:-Z2vyb7Ejh8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=clJWysL8_jk:-Z2vyb7Ejh8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=clJWysL8_jk:-Z2vyb7Ejh8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=clJWysL8_jk:-Z2vyb7Ejh8:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/clJWysL8_jk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/12/15/entity-framework-4-tips-for-nhibernate-users/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/12/15/entity-framework-4-tips-for-nhibernate-users/</feedburner:origLink></item>
		<item>
		<title>MvcPaging 1.0.2</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/IO9i_u6KfLQ/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/12/07/mvcpaging-1-0-2/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 21:57:46 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[Paging]]></category>
		<category><![CDATA[Razor]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/2011/12/07/mvcpaging-1-0-2/</guid>
		<description><![CDATA[A new version of the MvcPaging component is available via NuGet with the following changes: Added ItemStart and ItemEnd properties to IPagedList (Displaying items {ItemStart} &#8211; {ItemEnd}). Non-canonical url&#8217;s for page 1 (https://github.com/martijnboland/MvcPaging/issues/2). So the core library hasn’t changed much, and in all honesty, I think it’s pretty much done. Please leave a reply if <a href="http://blogs.taiga.nl/martijn/2011/12/07/mvcpaging-1-0-2/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A new version of the <a href="https://github.com/martijnboland/mvcpaging">MvcPaging</a> component is available via <a href="https://nuget.org/packages/MvcPaging">NuGet</a> with the following changes:</p>
<ul>
<li>Added ItemStart and ItemEnd properties to IPagedList (Displaying items {ItemStart} &#8211; {ItemEnd}). </li>
<li>Non-canonical url&#8217;s for page 1 (<a href="https://github.com/martijnboland/MvcPaging/issues/2">https://github.com/martijnboland/MvcPaging/issues/2</a>).</li>
</ul>
<p>So the core library hasn’t changed much, and in all honesty, I think it’s pretty much done. Please leave a reply if you think otherwise.</p>
<p>What did change substantially is the sample application. It was still very much ASP.NET 1.0 with WebForms views. This is now a proper ASP.NET MVC 3 application with Razor views and the default ASP.NET MVC 4.0 template for look &amp; feel.</p>
<p>&#160;<a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/12/Screenshot.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Screenshot" border="0" alt="Screenshot" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/12/Screenshot_thumb.png" width="640" height="400" /></a></p>
<p>The sample application can be found at <a href="https://github.com/martijnboland/mvcpaging">GitHub</a>. </p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=IO9i_u6KfLQ:SIT3MXymgTg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=IO9i_u6KfLQ:SIT3MXymgTg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=IO9i_u6KfLQ:SIT3MXymgTg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=IO9i_u6KfLQ:SIT3MXymgTg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/IO9i_u6KfLQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/12/07/mvcpaging-1-0-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/12/07/mvcpaging-1-0-2/</feedburner:origLink></item>
		<item>
		<title>Custom Model Binders and Request Validation</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/zcJh-4O1IvU/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/#comments</comments>
		<pubDate>Thu, 29 Sep 2011 11:15:21 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/</guid>
		<description><![CDATA[In ASP.NET MVC you can create your own model binders to control the way that models are constructed from an HTTP request. For example, if you don’t want any whitespace characters in your model, you can create a custom model binder that trims all whitespace characters when constructing&#160; a model object. You only have to <a href="http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In ASP.NET MVC you can create your own model binders to control the way that models are constructed from an HTTP request. For example, if you don’t want any whitespace characters in your model, you can create a custom model binder that trims all whitespace characters when constructing&#160; a model object. You only have to implement the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imodelbinder.aspx">IModelBinder</a> interface and its BindModel method in a class and register it during application startup.</p>
<h3>Getting the value from the HTTP request</h3>
<p>There are many examples online of how to build a custom model binder. In all these examples you can find a common way of getting a value from the HTTP request:</p>
<pre class="brush: csharp;">public class MyModelBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != null)
        {
            var theValue = valueProviderResult.AttemptedValue;

            // etc...
        }
    }
}</pre>
<p>The code above works nicely and you get protection for potential dangerous request values out of the box. Now let’s assume that we <em>want </em>some potential dangerous values like HTML or XML tags in our model. The recommended way is to add an [AllowHtml] attribute to the model property that may contain HTML and no validation happens for that property. Alternatively, it’s possible to add an [ValidateInput(false)] attribute to the controller action that accepts the model with HTML content, but this turns off validation for<em> </em>all model properties. </p>
<h3>A potentially dangerous Request.Form value was detected from the client</h3>
<p>Wait a minute! Didn’t we just explicitly say to allow those dangerous values? What’s happening?</p>
<p>It appears that a call to bindingContext.ValueProvider.GetValue() in the code above <em>always</em> validates the data, regardless any attributes. Digging into the ASP.NET MVC sources revealed that the DefaultModelBinder first checks&#160; if request validation is required and then calls the bindingContext.UnvalidatedValueProvider.GetValue() method with a parameter that indicates if validation is required or not. </p>
<p>Unfortunately we can’t use any of the framework code because it’s sealed, private or whatever to protect ignorant devs from doing dangerous stuff, but&#160; it’s not too difficult to create a working custom model binder that respects the AllowHtml and ValidateInput attributes:</p>
<pre class="brush: csharp;">public class MyModelBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // First check if request validation is required
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest &amp;&amp; bindingContext.ModelMetadata.RequestValidationEnabled;

        // Get value
        var valueProviderResult = bindingContext.GetValueFromValueProvider(shouldPerformRequestValidation);
        if (valueProviderResult != null)
        {
            var theValue = valueProviderResult.AttemptedValue;

            // etc...
        }
    }
}</pre>
<p>The other required piece is a way to retrieve an unvalidated value. In this example we use an extension method for the ModelBindingContext class:</p>
<pre class="brush: csharp;">public static ValueProviderResult GetValueFromValueProvider(this ModelBindingContext bindingContext, bool performRequestValidation)
{
    var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;
    return (unvalidatedValueProvider != null)
               ? unvalidatedValueProvider.GetValue(bindingContext.ModelName, !performRequestValidation)
               : bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
}</pre>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=zcJh-4O1IvU:LrXBfqqRnNI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=zcJh-4O1IvU:LrXBfqqRnNI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=zcJh-4O1IvU:LrXBfqqRnNI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=zcJh-4O1IvU:LrXBfqqRnNI:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/zcJh-4O1IvU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/</feedburner:origLink></item>
		<item>
		<title>Loosely coupled events in .NET (and harvesting Open Source projects)</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/AnJLKcBGXbw/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/07/28/loosely-coupled-events-in-net-and-harvesting-open-source-projects/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 12:15:39 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/?p=188</guid>
		<description><![CDATA[This post is about how Open Source projects can be very beneficial in creating the best solution for your own development challenges. A little while ago, I needed something to handle events in a loosely coupled manner due to a plugin-like architecture. Since I’m not the first person on earth who needs this, I went <a href="http://blogs.taiga.nl/martijn/2011/07/28/loosely-coupled-events-in-net-and-harvesting-open-source-projects/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This post is about how Open Source projects can be very beneficial in creating the best solution for your own development challenges.</p>
<p>A little while ago, I needed something to handle events in a loosely coupled manner due to a plugin-like architecture. Since I’m not the first person on earth who needs this, I went out looking for what’s available in .NET land and ended up with the <a href="http://devlicio.us/blogs/rob_eisenberg/archive/2011/05/30/caliburn-micro-soup-to-nuts-part-8-the-eventaggregator.aspx">EventAggregator from Caliburn Micro</a>:</p>
<h3>1. <a href="http://caliburnmicro.codeplex.com/">Caliburn Micro</a> (EventAggregator)</h3>
<p>The nicest thing is that it allows subscribers to handle multiple events by just implementing an interface:</p>
<pre class="brush: csharp;">public interface IHandle&lt;TMessage&gt; : IHandle
{
    void Handle(TMessage message);
}  

public class MySubscriber : IHandle&lt;SomeMessage&gt;, IHandle&lt;OtherMessage&gt;
{
    public void Handle(SomeMessage message){
        // do something with the message
    }

    public void Handle(OtherMessage message){
        // do something with the other message
    }
}</pre>
<p>Note that you can use ANY object as message. I like that! </p>
<p>Unfortunately, the application I’m working on is an ASP.NET MVC web application where the EventAggregator is more suitable for stateful environments like Silverlight or WPF. For example, I had to make the EventAggregator a Singleton to make sure that subscribers with different lifestyles (per web request, singleton, ASP.NET provider) could be called properly. Another issue was that I couldn’t find a nice way to instantiate all subscribers in the application.</p>
<h3>2. <a href="http://www.funnelweblog.com/">FunnelWeb</a> (EventPublisher)</h3>
<p>While browsing the <a href="http://www.funnelweblog.com/">Funnelweb</a> source code, I stumbled upon an interesting <a href="https://bitbucket.org/FunnelWeb/release/src/c2b5b210ac2a/src/FunnelWeb/Eventing/INotifier.cs">EventPublisher</a> class, <a href="http://www.funnelweblog.com/extensibility-and-events">the EventAggregator of Funnelweb</a>. This class takes a constructor dependency on a list of objects that implement IEventListener. So no subscribing here. The advantage of this is that an IoC container can take care of all subscriber creation and you don’t have to worry anymore if all subscribers are instantiated and are subscribed. When an event is published, the EventPublisher just goes through the list of IEventListener subscribers and calls their Handle() method. A small drawback is that the subscribers have to find out if they can handle the published event themselves. All events are published to all subscribers whatever type of event.</p>
<h3>3. Mix and Match and add a little sauce</h3>
<p>I really like the approach that is&#160; taken in Funnelweb so I’ve taken that as the base for my solution and added the parameterized event listeners of Caliburn Micro.</p>
<p>The event listener interface:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Event listener marker interface (for IoC convenience).
/// &lt;/summary&gt;
public interface IEventListener
{}

/// &lt;summary&gt;
/// Event listener interface that is parameterized with the type of the payload (event data)
/// &lt;/summary&gt;
/// &lt;typeparam name=&quot;TPayload&quot;&gt;The type of the event data&lt;/typeparam&gt;
public interface IEventListener&lt;in TPayload&gt; : IEventListener where TPayload: class
{
    /// &lt;summary&gt;
    /// Handle the published event with the given payload as event data.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;payload&quot;&gt;The event data&lt;/param&gt;
    void Handle(TPayload payload);
}</pre>
<p>An event listener implementation:</p>
<pre class="brush: csharp;">public class MyEventListenerClass: IEventListener&lt;Foo&gt;, IEventListener&lt;Bar&gt;
{
    // Snip initialization and other code.

    public void Handle(FooEvent payload)
    {
        // Do things with Foo event data
    }

    public void Handle(BarEvent payload)
    {
        // Do things with Bar event data
    }
}</pre>
<p>The event publisher interface:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Publishes events to listeners.
/// &lt;/summary&gt;
public interface IEventPublisher
{
    /// &lt;summary&gt;
    /// Publish an event with the given payload. This can be a specifically designed
    /// event class, but this is not required. We just don't allow primitives.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;TPayload&quot;&gt;The type of the event data&lt;/typeparam&gt;
    /// &lt;param name=&quot;payload&quot;&gt;The event data&lt;/param&gt;
    void Publish&lt;TPayload&gt;(TPayload payload) where TPayload : class;
}</pre>
<p>The event publisher implementation:</p>
<pre class="brush: csharp;">public class EventPublisher : IEventPublisher
{
    private readonly IEnumerable&lt;EventListener&gt; _listeners;

    public EventPublisher(IEnumerable&lt;IEventListener&gt; listeners)
    {
        _listeners = listeners;
    }

    public void Publish&lt;TPayload&gt;(TPayload payload) where TPayload : class
    {
        var handlersForPayload = _listeners.OfType&lt;IEventListener&lt;TPayload&gt;&gt;();
        foreach (var handler in handlersForPayload)
        {
            handler.Handle(payload);
        }
    }
}</pre>
<p>By creating a generic Publish&lt;TPayload&gt; method we are able to publish the event only to listeners that implement IEventListener&lt;TPayload&gt; .</p>
<h3>4. Use it!</h3>
<p>To be honest, you pretty much need an IoC container to use the full power of this EventPublisher, and to be more specific: an IoC container that can inject the IEnumerable&lt;EventListener&gt; parameter in the constructor of the EventPublisher, but I think most modern IoC containers can do that (Castle Windsor, Autofac, StructureMap). In the example below, we’re using <a href="http://code.google.com/p/autofac/">Autofac</a>.</p>
<p>Let’s say we have an application service IMyService and a plugin IPlugin, implemented by MyService and MyPlugin. MyService publishes an event with the type of MyEvent and MyPlugin handles that event. IMyService is being used in an ASP.NET MVC controller.</p>
<p>Event, Service and Plugin:</p>
<pre class="brush: csharp;">public class MyEvent
{
    public string Message { get; set; }
}

public interface IMyService
{
    void DoSomething();
}

pubic class MyService : IMyService
{
    private IEventPublisher _eventPublisher;

    public MyService(IEventPublisher eventPublisher)
    {
        _eventPublisher = eventPublisher;
    }

    public void DoSomething()
    {
        // Do things
        ...

        // Notify with MyEvent as event data
        _eventPublisher.Publish(new MyEvent { Message = &quot;Something is done&quot; });
    }
}

public interface IPlugin
{
    ...
}

public class MyPlugin : IPlugin, IEventListener&lt;MyEvent&gt;
{
    public void Handle(MyEvent myEvent)
    {
        var publisherMessage = myEvent.Message;
        // Do things with the event data.
        ...
    }
}</pre>
<p>Wire things together in the IoC container (Autofac):</p>
<pre class="brush: csharp;">var builder = new ContainerBuilder();

// IEventPublisher
builder.RegisterType&lt;EventPublisher&gt;().As&lt;IEventPublisher&gt;().InstancePerLifetimeScope();

// Services. Name has to end with &quot;Service&quot; by convention.
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    .Where(t =&gt; t.Name.EndsWith(&quot;Service&quot;))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

// Plugins. Name has to end with &quot;Plugin&quot; by convention.
foreach (var assembly in pluginAssemblies)
{
    builder.RegisterAssemblyTypes(pluginAssemblies)
        .Where(t =&gt; t.Name.EndsWith(&quot;Plugin&quot;))
        .AsImplementedInterfaces()
        .SingleInstance();
}

var container = builder.Build();DependencyResolver.SetResolver(new AutofacDependencyResolver(container));</pre>
<p>Note that the plugins (our IEventListener) can have a different lifestyle (Singleton) than the IEventPublisher (Instance per HTTP request). This should be fine as long as the IEventListeners live longer or have the same lifestyle&#160; as the IEventPublisher.</p>
<p>Finally the ASP.NET MVC controller:</p>
<pre class="brush: csharp;">public class MyController : Controller
{
    private IMyService _myService;

    public MyController(IMyService myService)
    {
        _myService = myService;
    }

    public ActionResult DoSomething()
    {
        // This call will automagically call MyPlugin.Handle
        _myService.DoSomething();
        return View();
    }
}</pre>
<p>That’s it! Thank you both Caliburn Micro and Funnelweb! I’m pretty happy with this solution and use it for multiple scenario’s:</p>
<ul>
<li>Plugins that need to respond on events of the core system;</li>
<li>Separation of concerns in Application Services: I often have an Application Service that needs to do a little more than it was originally designed for, for example post-processing of an order. Now I only need to publish an event with the order as data and the appropriate application services pick it up and perform the post-processing;</li>
<li>Dirty things with custom ASP.NET providers. Just implement one or more IEventListener&lt;T&gt; interfaces and register the provider <em>instance</em> in the IoC container with the interfaces it implements.</li>
</ul>
<p>Just one thing that worries me a little is the dependency of the EventPublisher to <em>all </em>classes that implement IEventListener&lt;T&gt; . These can potentially grow into a huge list and I don’t know what overhead that creates. I already experimented with a IEnumerable&lt;Lazy&lt;IEventListener&gt;&gt; parameter in the constructor of the EventPublisher so object creation is delayed until the moment we actually publish something and that seems to work fine with Autofac.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=AnJLKcBGXbw:lp79bMve13M:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=AnJLKcBGXbw:lp79bMve13M:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=AnJLKcBGXbw:lp79bMve13M:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=AnJLKcBGXbw:lp79bMve13M:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/AnJLKcBGXbw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/07/28/loosely-coupled-events-in-net-and-harvesting-open-source-projects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/07/28/loosely-coupled-events-in-net-and-harvesting-open-source-projects/</feedburner:origLink></item>
		<item>
		<title>NuGet package for MVC pager</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/fmNHA6ezyAg/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/05/12/nuget-package-for-mvc-pager/#comments</comments>
		<pubDate>Thu, 12 May 2011 15:15:35 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/2011/05/12/nuget-package-for-mvc-pager/</guid>
		<description><![CDATA[It’s now possible to add the MVC pager to your own project with NuGet. Or from Visual Studio with ‘Manage NuGet Packages&#8230;’ and then search for ‘MvcPaging’. After installing, you can immediately use the Pager HtmlHelper in your views: et voilà! We also have include the IPagedList for your convenience: For more info, check out <a href="http://blogs.taiga.nl/martijn/2011/05/12/nuget-package-for-mvc-pager/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It’s now possible to add the <a href="https://github.com/martijnboland/MvcPaging">MVC pager</a> to your own project with <a href="http://nuget.org/">NuGet</a>.</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image4.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image_thumb4.png" alt="image" width="600" height="77" border="0" /></a></p>
<p>Or from Visual Studio with ‘Manage NuGet Packages&#8230;’ and then search for ‘MvcPaging’.</p>
<p>After installing, you can immediately use the Pager HtmlHelper in your views:</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image5.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image_thumb5.png" alt="image" width="600" height="187" border="0" /></a></p>
<p>et voilà!</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image6.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image_thumb6.png" alt="image" width="600" height="392" border="0" /></a></p>
<p>We also have include the IPagedList for your convenience:</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image7.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/image_thumb7.png" alt="image" width="600" height="331" border="0" /></a></p>
<p>For more info, check out <a href="http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/">the original blogpost</a> that started it or the <a href="https://github.com/martijnboland/MvcPaging">github project page</a>.</p>
<p>Enjoy!</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=fmNHA6ezyAg:rs1_BgZdnqY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=fmNHA6ezyAg:rs1_BgZdnqY:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=fmNHA6ezyAg:rs1_BgZdnqY:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=fmNHA6ezyAg:rs1_BgZdnqY:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/fmNHA6ezyAg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/05/12/nuget-package-for-mvc-pager/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/05/12/nuget-package-for-mvc-pager/</feedburner:origLink></item>
		<item>
		<title>Keep your users informed with ASP.NET MVC</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/3psKtxtBcYM/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/05/03/keep-your-users-informed-with-asp-net-mvc/#comments</comments>
		<pubDate>Tue, 03 May 2011 14:09:50 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[Notification]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/?p=161</guid>
		<description><![CDATA[In almost every application, feedback from the application to the user via notification messages is required. For some strange reason, we don’t have a standard way in .NET web applications for dealing with this kind of messages and I find myself hacking some half-baked solutions over and over again. Starting from today, this must end! <a href="http://blogs.taiga.nl/martijn/2011/05/03/keep-your-users-informed-with-asp-net-mvc/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In almost every application, feedback from the application to the user via notification messages is required. </p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/success.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="success" border="0" alt="success" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/success_thumb.png" width="513" height="52" /></a></p>
<p>For some strange reason, we don’t have a standard way in .NET web applications for dealing with this kind of messages and I find myself hacking some half-baked solutions over and over again. Starting from today, this must end! In this post we’re going to find a solution for ASP.NET MVC 3.</p>
<h3>One single way to display messages</h3>
<p>This is the one and only requirement: </p>
<blockquote><p>In every scenario I want to be able to call ShowMessage() from my controller action and the message appears on the screen.</p>
</blockquote>
<h3>ShowMessage extension method</h3>
<p>To have a ShowMessage method in every controller action, we could implement it in a base controller class or create an extension method. Let’s try an extension method:</p>
<pre class="brush: csharp;">public static void ShowMessage(this Controller controller, MessageType messageType, string message, bool showAfterRedirect = false)
{
    var messageTypeKey = messageType.ToString();
    if (showAfterRedirect)
    {
        controller.TempData[messageTypeKey] = message;
    }
    else
    {
        controller.ViewData[messageTypeKey] = message;
    }
}</pre>
<p>All this method does is take a message type enum (Success, Warning or Error) and a message and store it in either ViewData or TempData, depending on the flag ‘showAfterRedirect’. TempData is for <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get">Post-Redirect-Get</a> situations.</p>
<p>We can now call ShowMessage(). With this solution it’s only possible to store one type of message per request, but that should be enough (even more than one message is already troublesome).</p>
<h3>RenderMessages HTML Helper</h3>
<p>Creating messages is one thing, but what about displaying them? It’s also easy. Enter the RenderMessages() HTML helper:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Render all messages that have been set during execution of the controller action.
/// &lt;/summary&gt;
/// &lt;param name=&quot;htmlHelper&quot;&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static HtmlString RenderMessages(this HtmlHelper htmlHelper)
{
    var messages = String.Empty;
    foreach (var messageType in Enum.GetNames(typeof(MessageType)))
    {
        var message = htmlHelper.ViewContext.ViewData.ContainsKey(messageType)
                        ? htmlHelper.ViewContext.ViewData[messageType]
                        : htmlHelper.ViewContext.TempData.ContainsKey(messageType)
                            ? htmlHelper.ViewContext.TempData[messageType]
                            : null;
        if (message != null)
        {
            var messageBoxBuilder = new TagBuilder(&quot;div&quot;);
            messageBoxBuilder.AddCssClass(String.Format(&quot;messagebox {0}&quot;, messageType.ToLowerInvariant()));
            messageBoxBuilder.SetInnerText(message.ToString());
            messages += messageBoxBuilder.ToString();
        }
    }
    return MvcHtmlString.Create(messages);
}</pre>
<p>It iterates through all possible message types, tries to find a message in either ViewData or TempData and creates a div with the message in it.<br />
  <br />Put the helper in the Layout page, add some css classes (.messagebox, .succes, .warning and .error) and we’re all set.</p>
<h3>What about AJAX?</h3>
<p>Now this is getting tricky. In our AJAX actions, we can still call ShowMessage(), but how should the message be displayed if we only return some JSON data or a partial view? One solution would be to wrap all AJAX results in a special JSON view result with the notification messages and the original result embedded. Drawback is that we have quite some work to do on the client-side to handle all this.</p>
<h3>HTTP headers to the rescue</h3>
<p>I discovered a very nice solution on StackOverflow: <a href="http://stackoverflow.com/questions/366311/how-do-you-handle-rails-flash-with-ajax-requests">use custom HTTP headers to store a message</a>. With the help of a global action filter we can check if there are messages in the ViewData dictionary and when the request was an AJAX request, copy the messages to a custom HTTP header.</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// If we're dealing with ajax requests, any message that is in the view data goes to
/// the http header.
/// &lt;/summary&gt;
public class AjaxMessagesFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            var viewData = filterContext.Controller.ViewData;
            var response = filterContext.HttpContext.Response;

            foreach (var messageType in Enum.GetNames(typeof(MessageType)))
            {
                var message = viewData.ContainsKey(messageType)
                                ? viewData[messageType]
                                : null;
                if (message != null) // We store only one message in the http header. First message that comes wins.
                {
                    response.AddHeader(&quot;X-Message-Type&quot;, messageType);
                    response.AddHeader(&quot;X-Message&quot;, message.ToString());
                    return;
                }
            }
        }
    }
}</pre>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/x-message.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="x-message" border="0" alt="x-message" src="http://blogs.taiga.nl/martijn/wp-content/uploads/2011/05/x-message_thumb.png" width="704" height="304" /></a></p>
<p>Finally the message in the HTTP headers are displayed with a little bit of jQuery:</p>
<pre class="brush: js;">$(document).ready(function () {
    handleAjaxMessages();
});

function handleAjaxMessages() {
    $(document).ajaxSuccess(function (event, request) {
        checkAndHandleMessageFromHeader(request);
    }).ajaxError(function (event, request) {
        displayMessage(request.responseText, &quot;error&quot;);
    });
}

function checkAndHandleMessageFromHeader(request) {
    var msg = request.getResponseHeader('X-Message');
    if (msg) {
        displayMessage(msg, request.getResponseHeader('X-Message-Type'));
    }
}

function displayMessage(message, messageType) {
    $(&quot;#messagewrapper&quot;).html('&lt;div class=&quot;messagebox ' + messageType.toLowerCase() + '&quot;&gt;&lt;/div&gt;');
    $(&quot;#messagewrapper .messagebox&quot;).text(message);
}</pre>
<h3>Demo</h3>
<p>For a closer look <a href="http://demo.taiga.nl/notification/" target="_blank">check out the live demo</a> or download the VS2010 solution from <a href="https://github.com/martijnboland/MvcNotification">GitHub</a>.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=3psKtxtBcYM:8pXZc0o3jDI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=3psKtxtBcYM:8pXZc0o3jDI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=3psKtxtBcYM:8pXZc0o3jDI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=3psKtxtBcYM:8pXZc0o3jDI:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/3psKtxtBcYM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/05/03/keep-your-users-informed-with-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/05/03/keep-your-users-informed-with-asp-net-mvc/</feedburner:origLink></item>
		<item>
		<title>Developers are afraid to choose a different presentation technology</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/cM7PZkSBbBk/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/04/07/developers-are-afraid-to-choose-a-different-presentation-technology/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 19:13:10 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/2011/04/07/developers-are-afraid-to-choose-a-different-presentation-technology/</guid>
		<description><![CDATA[Paul Stovell wrote a very interesting post about choosing when to use HTML, Silverlight or WPF. In the comments, I noticed something that keeps coming back: WPF/Silverlight devs bashing HTML/Javascript as inferior and vice versa. I’ve heard these discussions a lot and in most cases, people’s preferences are based on the technology that they are <a href="http://blogs.taiga.nl/martijn/2011/04/07/developers-are-afraid-to-choose-a-different-presentation-technology/"> read more <span class="meta-nav">&#187;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.paulstovell.com">Paul Stovell</a> wrote <a href="http://www.paulstovell.com/presentation-technologies">a very interesting post</a> about choosing when to use HTML, Silverlight or WPF. In the comments, I noticed something that keeps coming back: WPF/Silverlight devs bashing HTML/Javascript as inferior and vice versa. </p>
<p>I’ve heard these discussions a lot and in most cases, people’s preferences are based on the technology that they are most proficient in and not based on facts. The only fact here is that it’s awkward to leave your comfort zone and learn something that is totally different conceptually (stateful vs. stateless).</p>
<p>So when you ask a developer which presentation technology to choose, you should also weigh his background.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=cM7PZkSBbBk:84f_wbi1g0o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=cM7PZkSBbBk:84f_wbi1g0o:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=cM7PZkSBbBk:84f_wbi1g0o:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=cM7PZkSBbBk:84f_wbi1g0o:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/cM7PZkSBbBk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/04/07/developers-are-afraid-to-choose-a-different-presentation-technology/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/04/07/developers-are-afraid-to-choose-a-different-presentation-technology/</feedburner:origLink></item>
		<item>
		<title>MVC Pager update: now with AJAX support</title>
		<link>http://feedproxy.google.com/~r/martijnboland/~3/CTYBprnblic/</link>
		<comments>http://blogs.taiga.nl/martijn/2011/03/23/mvc-pager-update-now-with-ajax-support/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 13:26:59 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/2011/03/23/mvc-pager-update-now-with-ajax-support/</guid>
		<description><![CDATA[The MVC pager now has support for AJAX scenario’s, thanks to Bart Lenaerts. This was my first GitHub pull request and everything went pretty smoothly. Check out the demo application for an example. Visit the GitHub project page to download the solution.]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/">MVC pager</a> now has support for AJAX scenario’s, thanks to <a href="https://github.com/blenaerts">Bart Lenaerts</a>. This was my first <a href="https://github.com">GitHub</a> pull request and everything went pretty smoothly.</p>
<p>Check out the demo application for an example. Visit the <a href="https://github.com/martijnboland/MvcPaging">GitHub project</a> page to download the solution.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/martijnboland?a=CTYBprnblic:qLWdJCe6qOg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=CTYBprnblic:qLWdJCe6qOg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/martijnboland?i=CTYBprnblic:qLWdJCe6qOg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/martijnboland?a=CTYBprnblic:qLWdJCe6qOg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/martijnboland?d=qj6IDK7rITs" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/martijnboland/~4/CTYBprnblic" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2011/03/23/mvc-pager-update-now-with-ajax-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blogs.taiga.nl/martijn/2011/03/23/mvc-pager-update-now-with-ajax-support/</feedburner:origLink></item>
	</channel>
</rss>

