<?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>Captain Codeman</title>
	<atom:link href="http://www.captaincodeman.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.captaincodeman.com</link>
	<description>Software Developer</description>
	<lastBuildDate>Thu, 01 Jul 2010 01:56:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Error with Azure local development storage and table named &#8216;event&#8217;</title>
		<link>http://www.captaincodeman.com/2010/06/30/error-azure-local-development-storage-table-named-event/</link>
		<comments>http://www.captaincodeman.com/2010/06/30/error-azure-local-development-storage-table-named-event/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 01:53:34 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[table]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=217</guid>
		<description><![CDATA[While working on an Azure event-sourcing provider for my CQRS framework I came across a really strange problem so I&#8217;m posting the details in-case anyone else comes across a similar issue so they can save wasting as much time on it as I did! Basically, the local development storage doesn&#8217;t seem to like you having <a href="http://www.captaincodeman.com/2010/06/30/error-azure-local-development-storage-table-named-event/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>While working on an Azure event-sourcing provider for my CQRS framework I came across a really strange problem so I&#8217;m posting the details in-case anyone else comes across a similar issue so they can save wasting as much time on it as I did! Basically, the local development storage doesn&#8217;t seem to like you having a table called &#8216;event&#8217; (I haven&#8217;t tested it on the live system).</p>
<p>Here is some test code to demonstrate the behavior:</p>
<pre class="brush:csharp">class Program
{
    static void Main(string[] args)
    {
        const string tableName = "test";
        var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;

        var tableClient = storageAccount.CreateCloudTableClient();
        tableClient.CreateTableIfNotExist(tableName);

        var dataContext = tableClient.GetDataServiceContext();

        var bobdylan = new Artist
            {
                PartitionKey = "folk",
                RowKey = "bob-dylan",
                Name = "Bob Dylan"
            };

        dataContext.AddObject(tableName, bobdylan);
        dataContext.SaveChanges();
    }
}

[DataServiceKey("PartitionKey", "RowKey")]
public class Artist
{
    public virtual String PartitionKey { get; set; }
    public virtual String RowKey { get; set; }
    public DateTime Timestamp { get; set; }
    public string Name { get; set; }
}</pre>
<p>With the table called &#8216;test&#8217; in the example shown everything works fine and the table and data appear in the storage explorer:</p>
<p><a href="http://www.captaincodeman.com/?attachment_id=214" rel="attachment wp-att-214"><img src="http://www.captaincodeman.com/wp-content/uploads/2010/06/azure-table-working.png" alt="" title="azure-table-working" width="647" height="196" class="alignnone size-full wp-image-214" /></a></p>
<p>If we change the table name to &#8220;event&#8221; though we&#8217;ll get a DataServiceRequestException raised when we attempt to save changes:</p>
<p><a href="http://www.captaincodeman.com/2010/06/30/error-azure-local-development-storage-table-named-event/azure-table-error/" rel="attachment wp-att-218"><img src="http://www.captaincodeman.com/wp-content/uploads/2010/06/azure-table-error.png" alt="" title="azure-table-error" width="651" height="286" class="alignnone size-full wp-image-218" /></a></p>
<p>Strangely, the table <strong><em>does</em></strong> get created OK but just won&#8217;t let you save anything into it. I originally thought this may be an issue with a SQL reserved word (because the development storage is simulated using a SQL database) but I&#8217;m not sure this is the actual cause.</p>
<p>I guess I can&#8217;t have an &#8216;event&#8217; table like I wanted and will have to settle for &#8216;events&#8217; instead!</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/06/30/error-azure-local-development-storage-table-named-event/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pattern for efficiently paging database rows on a web page</title>
		<link>http://www.captaincodeman.com/2010/06/06/pattern-efficiently-paging-database-rows-web-page/</link>
		<comments>http://www.captaincodeman.com/2010/06/06/pattern-efficiently-paging-database-rows-web-page/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 16:57:34 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[action]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[paging]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=200</guid>
		<description><![CDATA[The technique I use for paging through database rows which I’ve found works efficiently and is easy to re-use. It works well for both traditional and AJAX requests and handles sorting and filtering requirements as well. This is based on ASP.NET MVC, jQuery and NHibernate + SQL Server but the principals will be the same for other technologies.


No related posts.]]></description>
			<content:encoded><![CDATA[<p>It shouldn’t be difficult to read rows from a database and render them on a web page – it’s a pretty fundamental operation that most web apps have to do but a surprising number don’t get quite right, especially when the volume of data grows and it can’t all be loaded and rendered within a single request. I’ve recently come across several ‘enterprise applications’ that simply fail to get it right – one extreme example loaded <em><strong>all</strong></em> the database rows into session state and then used LINQ to get and display the pages from that (!) and another took the approach of simply not paging the results at all which meant huge pages that were incredibly slow to load and as the data grew beyond the simple developer-test dataset.</p>
<p>So, I’m going to try and explain the technique I use for paging through rows which I’ve found works efficiently and is easy to re-use. It works well for both traditional and AJAX requests and handles sorting and filtering requirements as well. This is based on ASP.NET MVC, jQuery and NHibernate + SQL Server but the principals will be the same for other technologies (I’ve used the same basic approach with MongoDB as the back-end data-store).</p>
<h2>Paged Data Model</h2>
<p>We’ll start by defining a generic abstract class that will make it easy for us to re-use the approach for different lists. This will represent the ‘set’ of data on a page together with some additional information about the position of the page within the entire list, the total number of records and the sort order applied etc…</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Represents a paged list of data.
/// &lt;/summary&gt;
/// &lt;typeparam name="T"&gt;The item type in the list&lt;/typeparam&gt;
/// &lt;typeparam name="TS"&gt;The sort order specifier type.&lt;/typeparam&gt;
public abstract class PagedList&lt;T, TS&gt;
{
    /// &lt;summary&gt;
    /// Gets or sets the list of entities.
    /// &lt;/summary&gt;
    public IEnumerable&lt;T&gt; List { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the current page number.
    /// &lt;/summary&gt;
    public int PageNo { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the number of records per page.
    /// &lt;/summary&gt;
    public int PageSize { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the total number of records.
    /// &lt;/summary&gt;
    public int RecordCount { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets the first record number displayed.
    /// &lt;/summary&gt;
    public int StartRecord { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets a value indicating whether this &lt;see cref="PagedList&lt;T, TS&gt;"/&gt; is the latest page.
    /// &lt;/summary&gt;
    /// &lt;value&gt;&lt;c&gt;true&lt;/c&gt; if latest; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/value&gt;
    public bool Latest { get; set; }

    /// &lt;summary&gt;
    /// Gets or sets SortSeq.
    /// &lt;/summary&gt;
    public TS SortSeq { get; set; }
}</pre>
<p>The &lt;T&gt; and &lt;TS&gt; generic property types represent the type of entry that will be in the list (the ‘things’ we are paging over) and an Enum representing the sort-order required. As an example, we’ll page over a set of UserSummary entities and the sort-order will be defined with a UserSortSequence Enum:</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// How users are ordered in result sets
/// &lt;/summary&gt;
public enum UserSortSequence
{
    /// &lt;summary&gt;
    /// Order by name alphabetically
    /// &lt;/summary&gt;
    ByName, 

    /// &lt;summary&gt;
    /// Order by date joined
    /// &lt;/summary&gt;
    ByJoined, 

    /// &lt;summary&gt;
    /// Order by number of topics started
    /// &lt;/summary&gt;
    ByTopics, 

    /// &lt;summary&gt;
    /// Order by number of posts
    /// &lt;/summary&gt;
    ByPosts, 

    /// &lt;summary&gt;
    /// Order by reputation
    /// &lt;/summary&gt;
    ByReputation
}</pre>
<p>The PagedList is abstract so we need to create a specific class to represent the type of paged set that we want to use and this class will also contain any additional filtering parameters that our paging system will use. In this case, we will create a UserSet class that contains an additional Name property for filtering.</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Represents a user set.
/// &lt;/summary&gt;
public class UserSet : PagedList&lt;UserSummary, UserSortSequence&gt;
{
    /// &lt;summary&gt;
    /// Gets or sets Name to filter.
    /// &lt;/summary&gt;
    public string Name { get; set; }
}</pre>
<h2>Controller &amp; Action</h2>
<p>With these classes in place we can create a controller action to handle the request. A simplified version is shown below:</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Display paged user set filtered and sorted as required.
/// &lt;/summary&gt;
/// &lt;param name="name"&gt;The name filter.&lt;/param&gt;
/// &lt;param name="page"&gt;The page number.&lt;/param&gt;
/// &lt;param name="size"&gt;The page size.&lt;/param&gt;
/// &lt;param name="sort"&gt;The sort sequence.&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public ActionResult Index(string name, int page, int size, UserSortSequence sort)
{
    var model = new UserSet { PageNo = page, PageSize = size, SortSeq = sort, Name = name };
    this.Repository.PopulateUserSet(model);

    return View(model);
}</pre>
<h2>Data Access Layer</h2>
<p>The real work is done in the PopulateUserSet method of the repository. This needs to do 3 things:</p>
<ol>
<li>Get the total number of rows matching whatever filter criteria are specified.</li>
<li>Calculate the rows to display based on the page number and page size specified.</li>
<li>Get the set of data from the database applying any sort order specified.</li>
</ol>
<p>The sample below uses several NHibernate features and takes advantage of it’s ability to translate a paged-set request into the specific dialect of the database in question using whatever ROW_NUMBER functionality may be available so that the query operates as efficiently as possible.</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Populate user set with paged data.
/// &lt;/summary&gt;
/// &lt;param name="userset"&gt;The user set.&lt;/param&gt;
public void PopulateUserSet(UserSet userset)
{
    // Get total count for all users in this set
    userset.RecordCount = this.session.CreateCriteria(typeof(Account))
        .Add(Restrictions.Like("Name", userset.Name, MatchMode.Anywhere))
        .SetProjection(Projections.RowCount())
        .UniqueResult&lt;int&gt;();

    // calculate the last page based on the record count and page size
    int lastPage = ((userset.RecordCount - 1) / userset.PageSize) + 1;

    // ensure page number is in range
    if (userset.PageNo &lt; 1) {
        userset.PageNo = 1;
    }
    else if (userset.PageNo &gt; lastPage) {
        userset.PageNo = lastPage;
        userset.Latest = true;
    }

    userset.StartRecord = (userset.PageNo - 1) * userset.PageSize;

    // create criteria to get user account with paging
    ICriteria userListCriteria = this.session.CreateCriteria(typeof(UserSummary))
        .Add(Restrictions.Like("Name", userset.Name, MatchMode.Anywhere))
        .SetFirstResult(userset.StartRecord)
        .SetMaxResults(userset.PageSize);

    // add ordering to criteria
    switch (userset.SortSeq)
    {
        case UserSortSequence.ByJoined:
            userListCriteria.AddOrder(Order.Asc("RegisteredOn"));
            break;
        case UserSortSequence.ByName:
            userListCriteria.AddOrder(Order.Asc("Name"));
            break;
        case UserSortSequence.ByPosts:
            userListCriteria.AddOrder(Order.Desc("PostCount"));
            break;
        case UserSortSequence.ByReputation:
            userListCriteria.AddOrder(Order.Desc("Reputation"));
            break;
        case UserSortSequence.ByTopics:
            userListCriteria.AddOrder(Order.Desc("TopicCount"));
            break;
    }

    // get the list of users
    userset.List = userListCriteria.List&lt;UserSummary&gt;();
}</pre>
<h2>View Rendering</h2>
<p>So, we have a representation of a paged set of data, the action to retrieve it and the repository method to populate it. We now need a way of displaying the data and providing links for the user to navigate around it. How the rows are rendered obviously depends on the requirements of your application.</p>
<pre class="brush:html"><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UserSet>" %>

<asp:Content ContentPlaceHolderID="content" runat="server">
<ul id="data" class="topics">
    <% foreach (UserSummary userSummary in Model.List) { %>
        <%= Html.DisplayFor(x => userSummary) %>
    <% } %>
    </ul>
<ul class="paging"></ul>

</asp:Content>

<asp:Content ContentPlaceHolderID="scripts" runat="server">
    <script type="text/javascript">
        $(function() {  
            setPaging('<%= Html.Encode(Model.Name) %>', <%= Model.PageNo %>, <%= Model.PageSize %>, <%= Model.RecordCount %>);	
        });

        function setPaging(name, page, pageSize, records) {
            $('.paging').paging({
                page: page,
                pageSize: pageSize,
                records: records,
                url: '<%= Url.RouteUrl("users", new { name = "***", page = 99999 }) %>'.replace('***', name).replace('99999', '#')
            });    
        }
    </script>
</asp:Content></pre>
<h2>Rendering Paged Links</h2>
<p>I’m using a jQuery plug-in to display the page links because it saves doing so much work on the server and it makes it easier to AJAX enable the UI. In the full implementation the controller action can return a full view or just the JSON data for the paged set and the UI uses a template to render it and update the page links.</p>
<p>The paging itself is rendered using a jQuery plug-in. This is designed to intelligently decide which links to render and whether to enable or disable the previous and next links. It keeps the first and last links always visible and ensures that a few links either side of the current page (which is highlighted) are rendered while avoiding silly gaps (like having 1, 2, … 4 instead of 1, 2, 3, 4). Also, the ‘…’ separators are also links to the midpoint of the non-displayed sequence to make it easier to quickly jump around even large lists.</p>
<p>Here is an example of a 10 page set of links rendering using the rules outlines above:</p>
<p><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="page-links" src="http://www.captaincodeman.com/wp-content/uploads/2010/06/pagelinks.png" border="0" alt="page-links" width="300" height="331" /></p>
<p>The code to render this is below:</p>
<pre class="brush:javascript">/*
 * jQuery paging plugin
 *
 * http://www.captaincodeman.com/
 *
 */
(function($) {
    $.fn.paging = function(options) {

        // extend our default options with those provided.
        var settings = $.extend(true, {}, $.fn.paging.defaults, options);

        return this.each(function() {

            function render() {
                panel.empty();

                // calc pages, separators etc... to output
                var pageCount = Math.floor((settings.records - 1) / settings.pageSize) + 1;

                var pages = [];
                var pageStart, pageFinish;

                if (settings.inline) {
                    settings.prev = false;
                    settings.next = false;
                }

                var prevNextCount = 0;
                if (settings.prev) prevNextCount++;
                if (settings.next) prevNextCount++;

                if (settings.prev) {
                    if (currentPage &gt; 1) {
                        pages[pages.length] = new PageEntry(settings.prevText, currentPage - 1, PageType.Previous);
                    } else {
                        pages[pages.length] = new PageEntry(settings.prevText, currentPage, PageType.PreviousDisabled);
                    }
                }

                if (pageCount &lt;= settings.max + (settings.min * 2) + prevNextCount) {
                    // no separator required
                    addPages(pages, 1, pageCount);
                } else
                    if (currentPage &lt;= settings.max) {
                    // cluster at the start
                    addPages(pages, 1, Math.max(currentPage + 1, settings.max));
                    addSeparator(pages, Math.max(currentPage + 1, settings.max), pageCount - settings.min);
                    addPages(pages, pageCount - settings.min + 1, pageCount);
                } else
                    if (currentPage &gt;= pageCount - settings.max + 1) {
                    // cluster at the end
                    addPages(pages, 1, settings.min);
                    addSeparator(pages, settings.min, Math.min(currentPage - 1, pageCount - settings.max + 1));
                    addPages(pages, Math.min(currentPage - 1, pageCount - settings.max + 1), pageCount);
                } else {
                    // cluster in the middle
                    var offset = (settings.max - 1) / 2;
                    addPages(pages, 1, settings.min);
                    addSeparator(pages, settings.min, currentPage - offset);
                    addPages(pages, currentPage - offset, currentPage + offset);
                    addSeparator(pages, currentPage + offset, pageCount - settings.min + 1);
                    addPages(pages, pageCount - settings.min + 1, pageCount);
                }

                if (settings.next) {
                    if (currentPage &lt; pageCount) {
                        pages[pages.length] = new PageEntry(settings.nextText, currentPage + 1, PageType.Next);
                    } else {
                        pages[pages.length] = new PageEntry(settings.nextText, currentPage, PageType.NextDisabled);
                    }
                }

                // render pages
                for (var idx = 0; idx &lt; pages.length; idx++) {
                    if (settings.inline &#038;&#038; pages[idx].Page == 1) {
                    } else {

                        var clickHandler = function(page) {
                            return function(event) { return pageSelected(UrlFormat(page), page, event); }
                        }

                        var item;

                        switch (pages[idx].PageType) {
                            case PageType.Previous:
                            case PageType.Next:
                                item = $("&lt;a /&gt;")
                                    .bind("click", clickHandler(pages[idx].Page))
						            .attr("href", UrlFormat(pages[idx].Page))
						            .attr("class", 'prevnext')
						            .attr("title", "page " + pages[idx].Page)
						            .text(pages[idx].Text);
                                break;
                            case PageType.PreviousDisabled:
                            case PageType.NextDisabled:
                                item = $("&lt;span /&gt;")
						            .attr("class", 'prevnext')
						            .text(pages[idx].Text);
                                break;
                            case PageType.Separator:
                                item = $("&lt;a /&gt;")
                                    .bind("click", clickHandler(pages[idx].Page))
						            .attr("href", UrlFormat(pages[idx].Page))
						            .attr("class", 'sep')
						            .attr("title", "page " + pages[idx].Page)
						            .text(pages[idx].Text);
                                break;
                            case PageType.Page:
                                item = $("&lt;a /&gt;")
                                    .bind("click", clickHandler(pages[idx].Page))
						            .attr("href", UrlFormat(pages[idx].Page))
						            .attr("title", "page " + pages[idx].Page)
						            .text(pages[idx].Text);
                                break;
                            case PageType.PageSelected:
                                item = $("&lt;span /&gt;")
						            .attr("class", 'current')
						            .text(pages[idx].Text);
                                break;
                        }

                        panel.append(item);
                    }
                };
            }

            function pageSelected(url, page, event) {
                currentPage = page;
                var continuePropagation = settings.callback(url, page);
                if (!continuePropagation) {
                    if (event.stopPropagation) {
                        event.stopPropagation();
                    }
                    else {
                        event.cancelBubble = true;
                    }
                    render();
                }
                return continuePropagation;
            }

            function addPages(pages, start, finish) {
                for (var page = start; page &lt;= finish; page++) {
                    if (page == currentPage) {
                        pages[pages.length] = new PageEntry(page, page, PageType.PageSelected);
                    } else {
                        pages[pages.length] = new PageEntry(page, page, PageType.Page);
                    }
                }
            }

            function addSeparator(pages, start, finish) {
                var page = Math.ceil((finish - start) / 2) + start;
                pages[pages.length] = new PageEntry(settings.separatorText, page, PageType.Separator);
            }

            function UrlFormat(page) {
                return settings.url.replace("#", page);
            }

            var panel = jQuery(this);
            var currentPage = settings.page;
            render();
        });
    };

    var PageType = {
        Previous: 3,
        PreviousDisabled: 4,
        Next: 5,
        NextDisabled: 6,
        Separator: 7,
        Page: 8,
        PageSelected: 9
    }

    function PageEntry(text, page, pageType) {
        this.Text = text;
        this.Page = page;
        this.PageType = pageType;
    }

    $.fn.paging.defaults = {
        page: 1,
        pageSize: 20,
        records: 0,
        min: 1,
        max: 3,
        inline: false,
        prev: true,
        prevText: '« prev',
        next: true,
        nextText: 'next »',
        separator: true,
        separatorText: '...',
        url: '#',
        callback: function() { return true; }
    };

})(jQuery);</pre>
<h2>Summary</h2>
<p>These are all the pieces and hopefully it gives you an idea of how it all works. A full implementation will usually contain some extra pieces – besides the AJAX enabled rendering using JSON and client-side templates I’ll also have other links to enable to page-size to be adjusted and the sort-order changed and these are persisted to a cookie in the controller action using a custom binder. Hopefully though, what I’ve shown here will help you get a good solid and efficient paging system implemented.</p>
<p>Please let me know if any part of this is unclear or you’d like further details on any of the pieces.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/06/06/pattern-efficiently-paging-database-rows-web-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running MongoDb on Microsoft Windows Azure with CloudDrive</title>
		<link>http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/</link>
		<comments>http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/#comments</comments>
		<pubDate>Tue, 25 May 2010 04:38:17 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[clouddrive]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=162</guid>
		<description><![CDATA[I&#8217;ve been playing around with the whole CQRS approach and think MongoDb works really well for the query side of things. I also figured it was time I tried Azure so I had a look round the web to see if there we&#8217;re instructions on how to run MongoDb on Microsoft&#8217;s Azure cloud. It turned out <a href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing around with the whole CQRS approach and think <a href="http://www.mongodb.org/">MongoDb</a> works really well for the query side of things. I also figured it was time I tried Azure so I had a look round the web to see if there we&#8217;re instructions on how to run MongoDb on <a href="http://www.microsoft.com/windowsazure/">Microsoft&#8217;s Azure cloud</a>. It turned out there were only a few mentions of it or a general approach that should work but no detailed instructions on how to do it. So, I figured I&#8217;d give it a go and for a total-Azure-newbie it didn&#8217;t turn out to be too difficult.</p>
<p><a rel="attachment wp-att-165" href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/windows-azure-logo-lg/"><img class="alignnone size-full wp-image-165" style="margin-left: 20px; margin-right: 20px;" title="windows-azure-logo-lg" src="http://www.captaincodeman.com/wp-content/uploads/2010/05/windows-azure-logo-lg.png" alt="" width="359" height="75" /></a><a rel="attachment wp-att-164" href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/logo-mongodb-onwhite/"><img class="alignnone size-full wp-image-164" style="margin-left: 20px; margin-right: 20px;" title="logo-mongodb-onwhite" src="http://www.captaincodeman.com/wp-content/uploads/2010/05/logo-mongodb-onwhite.png" alt="" width="225" height="75" /></a></p>
<p>Obviously you&#8217;ll need an Azure account which you may get with MSDN or you can sign-up for their &#8216;free&#8217; account which has a limited number of hours included before you have to start paying. One thing to be REALLY careful of though &#8211; just deploying an app to Azure starts the clock running and leaving it deployed but turned off counts as hours so be sure to delete any experimental deployments you make after trying things out!!</p>
<p>First of all though it&#8217;s important to understand where MongoDb would fit with Azure. Each web or worker role runs as a virtual machine which has an amount of local storage included depending on the size of the VM, currently the four pre-defined VMs are:</p>
<div id="_mcePaste">
<ul>
<li><strong>Small</strong>: 1 core processor, 1.7GB RAM, <span style="text-decoration: underline;">250GB hard disk</span></li>
<li><strong>Medium</strong>: 2 core processors, 3.5GB RAM, <span style="text-decoration: underline;">500GB hard disk</span></li>
<li><strong>Large</strong>: 4 core processors, 7GB RAM, <span style="text-decoration: underline;">1000GB hard disk</span></li>
<li><strong>Extra Large:</strong> 8 core processors, 15GB RAM, <span style="text-decoration: underline;">2000GB hard disk</span></li>
</ul>
</div>
<p>This local storage is <em><strong>only temporary</strong></em> though and while it can be used for processing by the role instance running it isn&#8217;t available to any others and when the instance is moved, upgraded or recycled then it is lost forever (as in, gone for good).</p>
<p>For permanent storage Azure offers SQL-type databases (which we&#8217;re not interested in), Table storage (which would be an alternative to MongoDb but harder to query and with more limitations) and Blob storage.</p>
<p>We&#8217;re interested in Blob storage or more specifically Page-Blobs which support random read-write access &#8230; just like a disk drive. In fact, almost exactly like a disk drive because Azure provides a new CloudDrive which uses a VHD drive image stored as a Page-Blob (so it&#8217;s permanent) and can be mounted as a disk-drive within an Azure role instance.</p>
<p>The VHD images can range from 16Mb to 1Tb and apparently you only pay for the storage that is actually used, not the zeroed-bytes (although I haven&#8217;t tested this personally).</p>
<p>So, let&#8217;s look at the code to create a CloudDrive, mount it in an Azure worker role and run MongoDb as a process that can use the mounted CloudDrive for it&#8217;s permanent storage so that everything is kept between machine restarts. We&#8217;ll also create an MVC role to test direct connectivity to MongoDb between the two VMs using internal endpoints so that we don&#8217;t incur charges for Queue storage or Service Bus messages.</p>
<p>The first step is to create a &#8216;Windows Azure Cloud Service&#8217; project in Visual Studio 2010 and add both an MVC 2 and Worker role to it.</p>
<p>We will need a copy of the mongod.exe to include in the worker role so just drag and drop that to the project and set it to be Content copied when updated. Note that the Azure VMs are 64-bit instances so you need the 64-bit Windows version of MongoDb.</p>
<p><a rel="attachment wp-att-176" href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/mongod-exe/"><img class="alignnone size-full wp-image-176" title="mongod-exe" src="http://www.captaincodeman.com/wp-content/uploads/2010/05/mongod-exe.png" alt="" width="232" height="479" /></a></p>
<p>We&#8217;ll also need to add a reference to the .NET MongoDb client library to the web role. I&#8217;m using the <a href="http://github.com/samus/mongodb-csharp">mongodb-csharp</a> one but you can use one of the others if you prefer.</p>
<p>Our worker role needs a connection to the Azure storage account which we&#8217;re going to call &#8216;MongDbData&#8217;</p>
<p><a rel="attachment wp-att-181" href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/settings-mongodbdata/"><img class="alignnone size-full wp-image-181" title="settings-mongoDbData" src="http://www.captaincodeman.com/wp-content/uploads/2010/05/settings-mongoDbData.png" alt="" width="766" height="314" /></a></p>
<p>The other configured setting that we need to define is some local storage allocated as a cache for use with the CloudDrive, we&#8217;ll call this &#8216;MongoDbCache&#8217;. For this demo we&#8217;re going to create a 4Gb cache which will match the 4Gb drive we&#8217;ll create for MongoDb data. I haven&#8217;t played enough to evaluate performance yet but from what I understand this cache acts a little like the write-cache that you can turn on for your local hard drive.</p>
<p><a rel="attachment wp-att-182" href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/settings-mongodbcache/"><img class="alignnone size-full wp-image-182" title="settings-mongoDbCache" src="http://www.captaincodeman.com/wp-content/uploads/2010/05/settings-mongoDbCache.png" alt="" width="763" height="309" /></a></p>
<p>The last piece before we can crack on with some coding is to define an endpoint which is how the Web Role / MVC App will communicate with the MongoDb server on the Worker Role. This basically tells Azure that we&#8217;d like an IP Address and a port to use and it makes sure that we can use it and no one else can. It should be possible to make the endpoint public to the world if you wanted but that isn&#8217;t the purpose of this demo. The endpoint is called &#8216;MongoDbEndpoint&#8217; and set to Internal / TCP:</p>
<p><a rel="attachment wp-att-183" href="http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/settings-mongodbendpoint/"><img class="alignnone size-full wp-image-183" title="settings-mongoDbEndpoint" src="http://www.captaincodeman.com/wp-content/uploads/2010/05/settings-mongoDbEndpoint.png" alt="" width="764" height="311" /></a></p>
<p>Now for the code and first we&#8217;ll change the WorkerRole.cs file in the WorkerRole1 project (as you can see, I put a lot of effort into customizing the project names!). We&#8217;re going to need to keep a reference to the CloudDrive that we&#8217;re mounting and also the MongoDb process that we&#8217;re going to start so that we can shut them down cleanly when the instance is stopping:</p>
<pre class="brush:csharp">private CloudDrive _mongoDrive;
private Process _mongoProcess;</pre>
<p>In the OnStart() method I&#8217;ve added some code copied from the Azure SDK Thumbnail sample &#8211; this prepares the CloudStorageAccount configuration so that we can use the method CloudStorageAccount.FromConfigurationSetting() to load the details from configuration (this just makes it easier to switch to using the Dev Fabric on our local machine without changing code). I&#8217;ve also added a call to StartMongo() and created an OnStop() method which simply closes the MongoDb process and unmounts the CloudDrive when the instance is stopping:</p>
<pre class="brush:csharp">public override bool OnStart()
{
    // Set the maximum number of concurrent connections
    ServicePointManager.DefaultConnectionLimit = 12;

    DiagnosticMonitor.Start("DiagnosticsConnectionString");

    #region Setup CloudStorageAccount Configuration Setting Publisher

    // This code sets up a handler to update CloudStorageAccount instances when their corresponding
    // configuration settings change in the service configuration file.
    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =&gt;
    {
        // Provide the configSetter with the initial value
        configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

        RoleEnvironment.Changed += (sender, arg) =&gt;
        {
            if (arg.Changes.OfType()
                .Any((change) =&gt; (change.ConfigurationSettingName == configName)))
            {
                // The corresponding configuration setting has changed, propagate the value
                if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                {
                    // In this case, the change to the storage account credentials in the
                    // service configuration is significant enough that the role needs to be
                    // recycled in order to use the latest settings. (for example, the
                    // endpoint has changed)
                    RoleEnvironment.RequestRecycle();
                }
            }
        };
    });
    #endregion

    // For information on handling configuration changes
    // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
    RoleEnvironment.Changing += RoleEnvironmentChanging;

    StartMongo();

    return base.OnStart();
}

public override void OnStop()
{
    _mongoProcess.Close();
    _mongoDrive.Unmount();

    base.OnStop();
}</pre>
<p>Next is the code to create the CloudDrive and start the MongoDb process running:</p>
<pre class="brush:csharp">private void StartMongo()
{
    // local cache drive we'll use on the CM
    LocalResource localCache = RoleEnvironment.GetLocalResource("MongoDbCache");

    Trace.TraceInformation("MongoDbCache {0} {1}", localCache.RootPath, localCache.MaximumSizeInMegabytes);
    // we'll use all the cache space we can (note: InitializeCache doesn't work with trailing slash)
    CloudDrive.InitializeCache(localCache.RootPath.TrimEnd('\\'), localCache.MaximumSizeInMegabytes);

    // connect to the storage account
    CloudStorageAccount storageAccount = CloudStorageAccount.FromConfigurationSetting("MongoDbData");

    // client for talking to our blob files
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // the container that our dive is going to live in
    CloudBlobContainer drives = blobClient.GetContainerReference("drives");

    // create blob container (it has to exist before creating the cloud drive)
    try {drives.CreateIfNotExist();} catch {}

    // get the url to the vhd page blob we'll be using
    var vhdUrl = blobClient.GetContainerReference("drives").GetPageBlobReference("MongoDb.vhd").Uri.ToString();
    Trace.TraceInformation("MongoDb.vhd {0}", vhdUrl);

    // create the cloud drive
    _mongoDrive = storageAccount.CreateCloudDrive(vhdUrl);
    try
    {
        _mongoDrive.Create(localCache.MaximumSizeInMegabytes);
    }
    catch (CloudDriveException ex)
    {
        // exception is thrown if all is well but the drive already exists
    }

    // mount the drive and get the root path of the drive it's mounted as
    var dataPath = _mongoDrive.Mount(localCache.MaximumSizeInMegabytes, DriveMountOptions.Force) + @"\";
    Trace.TraceInformation("Mounted as {0}", dataPath);

    // get the internal enpoint that we're going to use for MongoDb
    var ep = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["MongoDbEndpoint"];

    // create the process to host mongo
    _mongoProcess = new Process();
    var startInfo = _mongoProcess.StartInfo;
    // so we can redirect streams
    startInfo.UseShellExecute = false;
    // we don't need a window, it's hard to see the monitor from here (jk)
    startInfo.CreateNoWindow = false;
    // the mongo daemon is included in our project in the current directory
    startInfo.FileName = @"mongod.exe";
    startInfo.WorkingDirectory = Environment.CurrentDirectory;
    // specify the ip address and port for MongoDb to use and also the path to the data
    startInfo.Arguments = string.Format(@"--bind_ip {0} --port {1} --dbpath {2} --quiet", ep.IPEndpoint.Address, ep.IPEndpoint.Port, dataPath);
    // capture mongo output to Azure log files
    startInfo.RedirectStandardError = true;
    startInfo.RedirectStandardOutput = true;
    _mongoProcess.ErrorDataReceived += (sender, evt) =&gt; WriteLine(evt.Data);
    _mongoProcess.OutputDataReceived += (sender, evt) =&gt; WriteLine(evt.Data);

    Trace.TraceInformation("Mongo Process {0}", startInfo.Arguments);

    // start mongo going
    _mongoProcess.Start();
    _mongoProcess.BeginErrorReadLine();
    _mongoProcess.BeginOutputReadLine();
}</pre>
<p>[TODO: Add more explanation !!]</p>
<p>So, that&#8217;s the server-side, oops, I mean Worker Role setup which will now run MongoDb and persist the data permanently. We could get fancier and have multiple roles with slave / sharded instances of MongoDb but they will follow a similar pattern.</p>
<p>The client-side in the Web Role MVC app is very simple and the only extra work we need to do is to figure out the IP Address and Port that we need to connect to MongoDb using which are setup for us by Azure. The RoleEnvironment lets us get to this and I believe (but could be wrong so don&#8217;t quote me) that the App Fabric part of Azure handles the communication between roles to pass this information. Once we have it we can create our connection to MongoDb as normal and save NoSQL JSON documents to our hearts content &#8230;</p>
<pre class="brush:csharp">var workerRoles = RoleEnvironment.Roles["WorkerRole1"];
var workerRoleInstance = workerRoles.Instances[0];
RoleInstanceEndpoint ep = workerRoleInstance.InstanceEndpoints["MongoDbEndpoint"];

string connectionString = string.Format("Server={0}:{1}", ep.IPEndpoint.Address, ep.IPEndpoint.Port);

var mongo = new Mongo(connectionString);
mongo.Connect();
var db = mongo.GetDatabase("notes");</pre>
<p>I hope you find this useful. I&#8217;ll try and add some extra notes to explain the code and the thinking behind it in more detail and will post some follow ups to cover deploying the app to Azure and what I&#8217;ve learned of that process.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/05/24/mongodb-azure-clouddrive/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Benefits of NoSQL (MongoDb) for the Query-side of CQRS</title>
		<link>http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/</link>
		<comments>http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 02:31:26 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=158</guid>
		<description><![CDATA[As you may know I&#8217;ve been researching CQRS and the benefits of using this approach to developing systems. My focus at the moment is on the Query side of things and for this I&#8217;ve been comparing a SQL Server / NHibernate solution with a NoSQL alternative using MongoDb. For this, I&#8217;ve been using a simple forum <a href="http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>As you may know I&#8217;ve been researching CQRS and the benefits of using this approach to developing systems. My focus at the moment is on the Query side of things and for this I&#8217;ve been comparing a SQL Server / NHibernate solution with a NoSQL alternative using MongoDb. For this, I&#8217;ve been using a simple forum app that I&#8217;ve been working on with a database of around 4m posts and 200k topics.</p>
<p>I&#8217;ll post more detailed results when I have time to show things in more detail (with some example code) but basically, the performance difference I&#8217;ve been seeing is huge.</p>
<p>The SQL Server / NHibernate solution was generating about 10 requests per second and had SQL Server at about 50% of the CPU. The MongoDB backed solution was running at around 50 requests per second and MongoDb was sat at around 3-4% of CPU time.</p>
<p>Right now, I&#8217;m very excited about the possibilities of improving app performance (especially now that Google are taking this into account when calculating page-rank) but also, the difference in the complexity of the code between the two systems is also refreshing with the MongoDb solution very, very simple and quick to develop.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/04/11/benefits-nosql-mongodb-query-cqrs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Circles of Interest</title>
		<link>http://www.captaincodeman.com/2010/03/31/circles-interest/</link>
		<comments>http://www.captaincodeman.com/2010/03/31/circles-interest/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 19:05:02 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[lucene]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[nosql]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=151</guid>
		<description><![CDATA[Technologies that I'm interested in and passionate about vs those that ... well, not so much


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I saw this on another blog and thought it was a neat way of showing the technologies that I am interested in or indifferent to.</p>
<h2><span style="color: #339966;">Positive / Core</span></h2>
<p>Things I care about or am interested in learning:</p>
<ul>
<li>ASP.NET MVC</li>
<li>HTML5 / CSS3</li>
<li>jQuery / JavaScript</li>
<li>DDDD / ESB / EDA / SOA / CQRS</li>
<li>Dependency Injection</li>
<li>Architecture</li>
<li>Lucene</li>
<li>Document Databases</li>
<li>Cloud Computing</li>
<li>User Interface Design</li>
<li>NoSQL data stores</li>
<li>MongoDB</li>
<li>Event Sourcing</li>
</ul>
<h2><span style="color: #3366ff;">Neutral / Non-core</span></h2>
<p>Things I care about but not as much or already know:</p>
<ul>
<li>ASP.NET WebForms</li>
<li>SQL Server</li>
<li>ETL</li>
<li>LINQ</li>
<li>AJAX, TDD</li>
<li>Source Control</li>
<li>WCF</li>
</ul>
<h2><span style="color: #993300;">Negative</span></h2>
<p>Things I don&#8217;t care about and have no particular interest or excitement in:</p>
<ul>
<li>Team System</li>
<li>Sharepoint</li>
<li>WPF</li>
<li>Silverlight</li>
<li>Flash</li>
<li>Windows</li>
<li>Office</li>
<li>Virtualization</li>
</ul>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/03/31/circles-interest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Homongous! MongoDB, NoSQL and CQRS</title>
		<link>http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/</link>
		<comments>http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 17:11:55 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[automapper]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[fluentnhibernate]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[nosql]]></category>
		<category><![CDATA[object database]]></category>
		<category><![CDATA[rdbms]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.captaincodeman.com/?p=131</guid>
		<description><![CDATA[I&#8217;ve got what I consider to be a pretty good development stack &#8211; all the usual suspects: MVC for the front-end; data stored in SQL Server or MySQL and accessed via NHibernate with mappings using FluentNHibernate conventions; the domain model mapped to a view model using AutoMapper and a sprinkling of NInject dependency injection to <a href="http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve got what I consider to be a pretty good development stack &#8211; all the usual suspects: <a href="http://www.asp.net/mvc/">MVC</a> for the front-end; data stored in <a href="http://www.microsoft.com/sqlserver/">SQL Server</a> or <a href="http://www.mysql.com/">MySQL</a> and accessed via <a href="http://nhforge.org/">NHibernate</a> with mappings using <a href="http://fluentnhibernate.org/">FluentNHibernate</a> conventions; the domain model mapped to a view model using <a href="http://automapper.codeplex.com/">AutoMapper</a> and a sprinkling of <a href="http://ninject.org/">NInject</a> dependency injection to tie it all together without direct dependencies.</p>
<p>And of course it works, it&#8217;s proven &#8211; lots of people use this approach. Lately though I&#8217;ve been reading a lot about different architectural approaches and in particular <a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/">CQRS</a> or &#8216;<a href="http://elegantcode.com/2009/11/11/cqrs-la-greg-young/">Command Query Responsibility Segregation</a>&#8216; from <a href="http://www.udidahan.com/?blog=true">Udi Dahan</a> and <a href="http://codebetter.com/blogs/gregyoung/">Greg Young</a> which, among other things, promotes the idea of having a separate denormalized repository for querying data and another, possibly normalized relational database, for writing to.</p>
<p>Because the query-side repository is denormalized it really lends itself to using a <a href="http://en.wikipedia.org/wiki/NoSQL">NoSQL approach</a> which seems to be gaining ground so I thought I&#8217;d give it a try to see how well it would work using a forum app I&#8217;ve been re-developing (currently an MVC/NHibernate/SQL Server based app).</p>
<p>Now, it&#8217;s not facebook but it&#8217;s not trivial either &#8211; there are about 4m posts spread over 200k topics and I&#8217;ve done quite a bit of work on the database side of things to make sure it&#8217;s efficient and normalized. One feature I&#8217;m implementing is to go away from the old and boring topic list that most forums have (where they show the topic title, author, date, number of replies and sometimes the date and author of the latest reply) and present it more graphically with the avatar of the topic starter, the title, date and folder it&#8217;s in and then the avatars of the last 3 or more (depending on configuration) people who have replied. Here&#8217;s an example:</p>
<p><a rel="attachment wp-att-132" href="http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/topic-summary/"><img class="alignnone size-full wp-image-132" title="topic-summary" src="http://www.captaincodeman.com/wp-content/uploads/2010/03/topic-summary.png" alt="" width="600" height="60" /></a></p>
<p>Now, to do this with the relational model means that I need to do quite a few table joins and when there are 4m+ rows that I need to be able to sort and page over it can start to chug a little. So, to speed things up I&#8217;ve spent some time optimizing the queries to use <a href="http://msdn.microsoft.com/en-us/library/cc917715.aspx">Indexed Views</a> to combine the Topic, Folder and Author and <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx">Common Table Expressions (CTE)</a> to get the last 3 replies which means joining the Topic, Post and Author tables again. It all works and it&#8217;s pretty quick but it&#8217;s been a lot of work to get it to that point.</p>
<p>So, the first test was to pick a NoSQL database to try as an alternative. I read up on quite a few and looked at the features and compatibility with Windows/C#/.NET including <a href="http://couchdb.apache.org/">CouchDB</a>, <a href="http://www.mongodb.org/">MongoDB</a>, <a href="http://cassandra.apache.org/">Cassandra</a>, <a href="http://project-voldemort.com/">Voldemort </a>and <a href="http://nosql-database.org/">others</a> and in the end decided to go with MongoDB.</p>
<p><a href="http://www.mongodb.org/display/DOCS/Quickstart">Downloading and installing MongoDB</a> (basically just unzipping the files) was easy and with the excellent documentation I was up and running really quickly and ready to start trying things out.</p>
<p>The first step was to try reading and writing documents using C# and this was really straightforward using the <a href="http://www.mongodb.org/display/DOCS/C+Sharp+Language+Center">mongodb-csharp driver</a>. So, next step was to convert the data from SQL Server into it. I already had the queries that created the paged views of data &#8211; typically with 10 or 20 records per page and thought I&#8217;d just re-use that. Running against the whole recordset really slowed it down though but after SQL Server chugged away for 10 or 15 minutes and used 6.5Gb of RAM it managed to give me the data and I created the <a href="http://www.json.org/">JSON</a> documents in-memory ready for inserting.</p>
<p>So, I call &#8216;Insert&#8217; to add the collection of documents to the MongoDB store. And it failed. Well, actually &#8230; I assumed it failed because it only seemed to take about 5 seconds and my console app finished. When I went to the MongoDB console and queried the data though it was all there &#8230; and I could query it, sort it, page through it, very VERY quickly &#8211; much quicker than using SQL Server and the relational model. Windows process explorer showed MongoDB used just a few Mb of RAM to do this.</p>
<p>Because querying was so easy and so direct I no longer needed to use an OR/M to address the <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch">object-relational impedance mismatch</a> (a fancy way of saying an RDBMS sucks for OO) and I no longer needed to transform the persistent domain model into a view model before presenting it. I can just get the view model objects straight from the store and render them. Fast, simple, and I get to delete lots of code which is kind of soul destroying when you&#8217;ve written it but I&#8217;m excited at all the code I won&#8217;t have to write in future with this approach and the performance.</p>
<p>MongoDB is very, very fast and very easy to use although it requires a slightly different way of thinking when you&#8217;re more used to working with a relational model. One of the big selling points is that it&#8217;s easier to scale than a relational system and while I didn&#8217;t try the sharding support (which is in alpha) I did give the replication a go &#8211; again, it was much easier to setup than the equivalent would be with SQL Server and it performed very well.</p>
<p>Finally, I did a few more experiments to test the insert performance compared to SQL Server and basically setup a simple table with an Id, Name and Number column and inserted 500,000 rows. I used parameterized queries for SQL Server, re-used the same command object and wrapped it all in a single transaction but it took over 55 seconds to run (plus I had to create the database and table in advance which took a minute or two). Doing the same thing with MongoDB ran in under 10 seconds and the client code was much simpler and I didn&#8217;t have any initial setup.</p>
<p>I&#8217;m definitely going to explore MongoDB more and plan on making use of it in future projects when it&#8217;s appropriate. The next piece to look at is the Command side of CQRS where I want to use <a href="http://codebetter.com/blogs/gregyoung/archive/2010/02/20/why-use-event-sourcing.aspx">event sourcing for storage</a> and an event driven / service oriented architecture and better domain driven design techniques.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/03/31/homongous-mongodb-nosql-cqrs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blog Reboot</title>
		<link>http://www.captaincodeman.com/2010/03/21/blog-reboot/</link>
		<comments>http://www.captaincodeman.com/2010/03/21/blog-reboot/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 17:40:07 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[captain codeman]]></category>

		<guid isPermaLink="false">http://74.55.37.203/?p=103</guid>
		<description><![CDATA[I decided to switch to a different blogging platform and move the (pitifully) small amount of content that I&#8217;d posted over. So, this blog is now running on WordPress instead of BlogEngine.NET. At the same time, I&#8217;ve decided to try and improve my own personal &#8216;brand&#8217; and promote my skills a bit more hence the <a href="http://www.captaincodeman.com/2010/03/21/blog-reboot/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I decided to switch to a different blogging platform and move the (pitifully) small amount of content that I&#8217;d posted over. So, this blog is now running on WordPress instead of BlogEngine.NET.</p>
<p>At the same time, I&#8217;ve decided to try and improve my own personal &#8216;brand&#8217; and promote my skills a bit more hence the tongue-FIRMLY-in-cheek &#8216;Captain Codeman&#8217; moniker.</p>
<p>I don&#8217;t have any illusions about being a super-hero or even a super-developer although I&#8217;d hope my colleagues think I&#8217;m at least on the better-side of average. I just wanted to come up with something that was a bit memorable and could give me an excuse to use the awesome cool little character I found on iStockPhoto:</p>
<p><a rel="attachment wp-att-70" href="http://www.captaincodeman.com/?attachment_id=70"><img class="alignleft size-full wp-image-70" title="superhero-thumbup" src="http://www.captaincodeman.com/wp-content/uploads/2010/03/superhero-thumbup.jpg" alt="" width="284" height="423" /></a></p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/03/21/blog-reboot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Absolute URLs using MVC (without extension methods)</title>
		<link>http://www.captaincodeman.com/2010/02/03/absolute-urls-using-mvc-without-extension-methods/</link>
		<comments>http://www.captaincodeman.com/2010/02/03/absolute-urls-using-mvc-without-extension-methods/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 17:29:49 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Rendering]]></category>
		<category><![CDATA[Routing]]></category>
		<category><![CDATA[action]]></category>

		<guid isPermaLink="false">http://blogs.intesoft.net/post.aspx?id=019a9ef7-023a-46c7-97a9-94fd14f7a28e</guid>
		<description><![CDATA[Do you need to generate absolute URLs within your MVC application? Often this will be in the form of URLs used outside of the web-browser such as those used within Atom Publishing Protocol collections or maybe links that are going to be sent out in emails. Basically, anything where the regular relative URL won’t do. <a href="http://www.captaincodeman.com/2010/02/03/absolute-urls-using-mvc-without-extension-methods/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Do you need to generate absolute URLs within your MVC application?</p>
<p>Often this will be in the form of URLs used outside of the web-browser such as those used within Atom Publishing Protocol collections or maybe links that are going to be sent out in emails. Basically, anything where the regular relative URL won’t do.</p>
<p>A quick search of Google will turn up a number of blog posts or forum answers showing how to do this by creating extension methods for the Url helper class but really, everything that is needed is already baked into the MVC framework already … and I’ve only just realized it after using it since the CTP releases!</p>
<p><span id="more-4"></span></p>
<p>All you need to do is specify the protocol within the Url.Action or Url.RouteUrl method. Here are some regular looking URLs:</p>
<pre class="csharpcode">&lt;%= Url.Action(<span class="str">"About"</span>, <span class="str">"Home"</span>) %&gt;&lt;br /&gt;
&lt;%= Url.RouteUrl(<span class="str">"Default"</span>, <span class="kwrd">new</span> { Action = <span class="str">"About"</span> }) %&gt;&lt;br /&gt;</pre>
<p><!-- .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; } --></p>
<p>Which produce the same output:</p>
<p>/Home/About</p>
<p>/Home/About</p>
<p>If we add the protocol then it changes to:</p>
<pre class="csharpcode">&lt;%= Url.Action(<span class="str">"About"</span>, <span class="str">"Home"</span>, <span class="kwrd">null</span>, <span class="str">"http"</span>) %&gt;&lt;br /&gt;
&lt;%= Url.RouteUrl(<span class="str">"Default"</span>, <span class="kwrd">new</span> { Action = <span class="str">"About"</span> }, <span class="str">"http"</span>) %&gt;&lt;br /&gt;</pre>
<p><!-- .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; } --></p>
<p>http://localhost:51868/Home/About</p>
<p>http://localhost:51868/Home/About</p>
<p>Instead of having the ‘http’ hard-coded like that you can instead use whatever protocol was used for the request so URLs will be correct whether they are using http or https (assuming they don’t need to be a specific one), e.g.:</p>
<pre class="csharpcode">&lt;%= Url.Action(<span class="str">"About"</span>, <span class="str">"Home"</span>, <span class="kwrd">null</span>, Request.Url.Scheme) %&gt;&lt;br /&gt;
&lt;%= Url.RouteUrl(<span class="str">"Default"</span>, <span class="kwrd">new</span> { Action = <span class="str">"About"</span> }, Request.Url.Scheme) %&gt;&lt;br /&gt;</pre>
<p><!-- .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; } --></p>
<p>If you just pass the protocol / scheme then the host name and port number are generated automatically based on the site that the app is running on. You can also pass the host name as well if you want (if the public host name doesn’t match the one the site is actually running on).</p>
<p>This works for the Url helper only, the protocol isn’t an option in the Html helper used to general complete html anchor links but I’m guessing that if you need an absolute URL you are needing something else beyond a plain link anyway and it isn’t too much trouble to just define the anchor element in a view and use the Url helper in the href attribute only.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2010/02/03/absolute-urls-using-mvc-without-extension-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When to use RenderAction vs RenderPartial with ASP.NET MVC</title>
		<link>http://www.captaincodeman.com/2009/02/21/when-to-use-renderaction-vs-renderpartial-with-asp-net-mvc/</link>
		<comments>http://www.captaincodeman.com/2009/02/21/when-to-use-renderaction-vs-renderpartial-with-asp-net-mvc/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 23:36:55 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Rendering]]></category>
		<category><![CDATA[action]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://blogs.intesoft.net/post.aspx?id=ba353b21-0cfd-4960-8c1f-510d9f4907ee</guid>
		<description><![CDATA[At first glance, RenderAction and RenderPartial both do a very similar thing – they load ‘some other content’ into the view being rendered at the place they are called. Personally, I think they should be used for different scenarios so these are my thoughts on where each one should be used and why. First though, <a href="http://www.captaincodeman.com/2009/02/21/when-to-use-renderaction-vs-renderpartial-with-asp-net-mvc/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>At first glance, RenderAction and RenderPartial both do a very similar thing – they load ‘some other content’ into the view being rendered at the place they are called. Personally, I think they should be used for different scenarios so these are my thoughts on where each one should be used and why.</p>
<p>First though, a quick recap on what they do:</p>
<ul>
<li>RenderPartial renders a control with some model passed to it. </li>
<li>RenderAction (or <a title="RenderSubAction alternative to RenderAction for Sub-Controllers in MVC" href="http://blogs.intesoft.net/post/2009/02/RenderSubAction-alternative-to-RenderAction-for-sub-controllers-using-asp-net-mvc.aspx" target="_blank">RenderSubAction</a> which addresses some issues) calls a controller action and then renders whatever view that returns with whatever model that controller action passes through it. </li>
</ul>
<p>Hmmn, they sound pretty similar don’t they! The thing to note though is that the model passed to RenderPartial is <em><strong>either</strong></em> the current model being rendered by the calling view <em>or a subset of it</em>. Anything that a RenderPartial view being called is going to need has to be passed into the Model of the calling view. The view rendered using RenderAction on the other hand could contain a completely different model with no need for this to be passed in to our parent view.</p>
<p>Because of this, I think RenderPartial is most appropriate when what it is going to output could be considered part of the calling view but separating it out into a user control makes sense to allow re-use and avoid repeating the same rendering code in multiple views. For example, if you are rendering a person name in lots of places then instead of repeating within each view the code to output it:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">=&quot;&lt;%= Url.Action(&quot;</span><span class="attr">Display</span><span class="kwrd">&quot;, &quot;</span><span class="attr">Person</span><span class="kwrd">&quot;, new { id = Model.Person.Id}) %&gt;&quot;</span><span class="kwrd">&gt;</span>
  <span class="asp">&lt;%</span>= Model.Person.Salutation <span class="asp">%&gt;</span> <span class="asp">&lt;%</span>= Model.Person.Forename <span class="asp">%&gt;</span> <span class="asp">&lt;%</span>= Model.Person.Surname <span class="asp">%&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span></pre>
<p>
  <br />Instead, you move this to a separate user control such as ‘PersonName.ascx’ which expects a Person as the model:</p>
<pre class="csharpcode"><span class="asp">&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&lt;Person&gt;&quot; %&gt;</span>
<span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">=&quot;&lt;%= Url.Action(&quot;</span><span class="attr">Display</span><span class="kwrd">&quot;, &quot;</span><span class="attr">Person</span><span class="kwrd">&quot;, new { id = Model.Id}) %&gt;&quot;</span><span class="kwrd">&gt;</span>
    <span class="asp">&lt;%</span>= Model.Salutation <span class="asp">%&gt;</span> <span class="asp">&lt;%</span>= Model.Forename <span class="asp">%&gt;</span> <span class="asp">&lt;%</span>= Model.Surname <span class="asp">%&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span></pre>
<p>
  <br />Now, any place a view wants to output a persons name then you can instead call a PartialView and pass in the appropriate model:</p>
<pre class="csharpcode"><span class="asp">&lt;%</span>= Html.RenderPartial(<span class="str">&quot;PersonName&quot;</span>, Model.Person); <span class="asp">%&gt;</span>&#160;</pre>
<p>
  <br />Why would you want to do this? Well, it helps consistency and avoids repetition which makes it easy if, for example, you decide that name should not longer be in the format “Mr John Smith” but instead “Smith, John (Mr)” and you want to throw in a little jQuery magic to display a profile popup whenever anyone hovers the mouse over the name. This is a simple example but hopefully it demonstrates some benefits of using it compared to repeating the code in each view – with larger chunks of output the benefits of using RenderPartial would be even more apparent</p>
<p>So that is where and how I think RenderPartial should be used. How about RenderAction?</p>
<p>Well, I think this has it’s place when the thing that needs to be rendered <em><strong>isn’t the responsibility of the calling view or controller</strong></em>.</p>
<p>For example, I may have a PersonController responsible for CRUD operations on the Person class including a Display action and view but I do not want either of these to have any responsibility for anything to do with the display of Projects that the person is working on. If I want to display a list of assigned projects within the Person Display view then I would use RenderAction to add it but the responsibility and knowledge of how to do this resides with the ProjectController and it’s views. This would be called as follows:</p>
<pre class="csharpcode"><span class="asp">&lt;%</span> Html.RenderAction(<span class="str">&quot;List&quot;</span>, <span class="str">&quot;Project&quot;</span>, <span class="kwrd">new</span> {personId = Model.Person.Id}); <span class="asp">%&gt;</span>&#160;</pre>
<p>
  <br />(incidentally … note that, unlike many of the other extension methods, RenderAction doesn’t return a string so there is no ‘=’ at the beginning and a ‘;’ at the end)</p>
<p>Now, how the Project List is retrieved and rendered is completely the concern of the ProjectController class as it should be and the output can contain whatever it needs to display the list, provide actions to edit project entries and so on.</p>
<p>Another benefit of this approach is if you create different skinned versions of an app. By keeping things modular it is much easier to decide to include something in the view for one skin but not another. So, the skin (set of views) for a full desktop browser may call RenderAction to include the list in the same page whereas the skin for a mobile device friendly interface (think iPhone) would perhaps just include a link instead – both are handled by changing the view instead of changing the controllers which could otherwise be the case.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2009/02/21/when-to-use-renderaction-vs-renderpartial-with-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RenderSubAction alternative to RenderAction for Sub-Controllers in MVC</title>
		<link>http://www.captaincodeman.com/2009/02/21/rendersubaction-alternative-to-renderaction-for-sub-controllers-in-mvc/</link>
		<comments>http://www.captaincodeman.com/2009/02/21/rendersubaction-alternative-to-renderaction-for-sub-controllers-in-mvc/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 22:08:12 +0000</pubDate>
		<dc:creator>Captain Codeman</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Rendering]]></category>
		<category><![CDATA[action]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[render]]></category>

		<guid isPermaLink="false">http://blogs.intesoft.net/post.aspx?id=2588ca1e-5544-4616-bc54-b4d75e6f8e99</guid>
		<description><![CDATA[The ASP.NET MVC Futures assembly contains several RenderAction extension methods for HtmlHelper to allow another action to be rendered at some point within a view. Typically, this allows each controller to handle different responsibilities rather than things being combined into the parent. So, for example, a PersonController is responsible for retrieving and assembling the model <a href="http://www.captaincodeman.com/2009/02/21/rendersubaction-alternative-to-renderaction-for-sub-controllers-in-mvc/" class="more-link">More &#62;</a>


No related posts.]]></description>
			<content:encoded><![CDATA[<p>The ASP.NET MVC Futures assembly contains several RenderAction extension methods for HtmlHelper to allow another action to be rendered at some point within a view. Typically, this allows each controller to handle different responsibilities rather than things being combined into the parent.</p>
<p>So, for example, a PersonController is responsible for retrieving and assembling the model to represent a Person and pass it to the View for rendering but it should not handle Contacts – the display and CRUD operations on contacts should be handled by a ContactController and RenderAction is a convenient way to insert a list of contacts for a person into the persion display view.</p>
<p>So, we have a PersonController which will retrieve a Person model and pass it to the Display view. Inside this Display view, we have a call to render a list of contacts for that person:</p>
<p><font face="Courier New">&lt;% Html.RenderSubAction(&quot;List&quot;, &quot;Contact&quot;, new { personId = Model.Id }); %&gt;</font></p>
<p>I’ve come across two problems when using this though:</p>
<p>1. If the parent controller action requested uses the HTTP POST method then the controller action picked up for all child actions will <em>also</em> be the POST version (if there is one). This is rarely the desired behavior though – I’d only expect to be sending a POST to the ContactController when I want to change something related to a contact and not when updating a person.</p>
<p>2. If the [ValidateInput(false)] attribute is used to allow HTML code to be posted (imagine a ‘Biography’ field on Person with a nice WYSIWYG TinyMCE Editor control …) then the request will fail unless all the child actions are automatically marked with the same attribute. I would prefer to only have to mark the methods I specifically want a POST request containing HTML input to be called.</p>
<p>So, I created a set of alternative RenderSubAction extension methods which address both these issues:</p>
<p>1. Whatever the HTTP method used for the parent action, the routing will match the GET version for child actions called.</p>
<p>2. The state of the [ValidateInput()] attribute will be set on all child actions called.</p>
<p>The code is below … just reference the namespace that you put it in within your web.config file and then change the RenderAction method to RenderSubAction – the method signatures are identical so it is a drop-in replacement.</p>
<p>I’d be interested in any feedback on this approach.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> HtmlHelperExtensions {
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RenderSubAction&lt;TController&gt;(<span class="kwrd">this</span> HtmlHelper helper,             Expression&lt;Action&lt;TController&gt;&gt; action)
        <span class="kwrd">where</span> TController : Controller {
        RouteValueDictionary routeValuesFromExpression = ExpressionHelper</pre>
<pre class="csharpcode">            .GetRouteValuesFromExpression(action);
        helper.RenderRoute(routeValuesFromExpression);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RenderSubAction(<span class="kwrd">this</span> HtmlHelper helper, <span class="kwrd">string</span> actionName) {
        helper.RenderSubAction(actionName, <span class="kwrd">null</span>);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RenderSubAction(<span class="kwrd">this</span> HtmlHelper helper, <span class="kwrd">string</span> actionName, <span class="kwrd">string</span> controllerName) {
        helper.RenderSubAction(actionName, controllerName, <span class="kwrd">null</span>);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RenderSubAction(<span class="kwrd">this</span> HtmlHelper helper, <span class="kwrd">string</span> actionName, <span class="kwrd">string</span> controllerName,             <span class="kwrd">object</span> routeValues) {
        helper.RenderSubAction(actionName, controllerName, <span class="kwrd">new</span> RouteValueDictionary(routeValues));
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RenderSubAction(<span class="kwrd">this</span> HtmlHelper helper, <span class="kwrd">string</span> actionName, <span class="kwrd">string</span> controllerName,
                                    RouteValueDictionary routeValues) {
        RouteValueDictionary dictionary = routeValues != <span class="kwrd">null</span> ? <span class="kwrd">new</span> RouteValueDictionary(routeValues)             : <span class="kwrd">new</span> RouteValueDictionary();
        <span class="kwrd">foreach</span> (var pair <span class="kwrd">in</span> helper.ViewContext.RouteData.Values) {
            <span class="kwrd">if</span> (!dictionary.ContainsKey(pair.Key)) {
                dictionary.Add(pair.Key, pair.Value);
            }
        }
        <span class="kwrd">if</span> (!<span class="kwrd">string</span>.IsNullOrEmpty(actionName)) {
            dictionary[<span class="str">&quot;action&quot;</span>] = actionName;
        }
        <span class="kwrd">if</span> (!<span class="kwrd">string</span>.IsNullOrEmpty(controllerName)) {
            dictionary[<span class="str">&quot;controller&quot;</span>] = controllerName;
        }
        helper.RenderRoute(dictionary);
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RenderRoute(<span class="kwrd">this</span> HtmlHelper helper, RouteValueDictionary routeValues) {
        var routeData = <span class="kwrd">new</span> RouteData();
        <span class="kwrd">foreach</span> (var pair <span class="kwrd">in</span> routeValues) {
            routeData.Values.Add(pair.Key, pair.Value);
        }
        HttpContextBase httpContext = <span class="kwrd">new</span> OverrideRequestHttpContextWrapper(HttpContext.Current);
        var context = <span class="kwrd">new</span> RequestContext(httpContext, routeData);
        <span class="kwrd">bool</span> validateRequest = helper.ViewContext.Controller.ValidateRequest;
        <span class="kwrd">new</span> RenderSubActionMvcHandler(context, validateRequest).ProcessRequestInternal(httpContext);
    }

    <span class="preproc">#region</span> Nested type: RenderSubActionMvcHandler

    <span class="kwrd">private</span> <span class="kwrd">class</span> RenderSubActionMvcHandler : MvcHandler {
        <span class="kwrd">private</span> <span class="kwrd">bool</span> _validateRequest;
        <span class="kwrd">public</span> RenderSubActionMvcHandler(RequestContext context, <span class="kwrd">bool</span> validateRequest) : <span class="kwrd">base</span>(context) {
            _validateRequest = validateRequest;
        }

        <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> AddVersionHeader(HttpContextBase httpContext) {}

        <span class="kwrd">public</span> <span class="kwrd">void</span> ProcessRequestInternal(HttpContextBase httpContext) {
            AddVersionHeader(httpContext);
            <span class="kwrd">string</span> requiredString = RequestContext.RouteData.GetRequiredString(<span class="str">&quot;controller&quot;</span>);
            IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = controllerFactory.CreateController(RequestContext, requiredString);
            <span class="kwrd">if</span> (controller == <span class="kwrd">null</span>)
            {
                <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(<span class="kwrd">string</span>.Format(CultureInfo.CurrentUICulture,                     <span class="str">&quot;The IControllerFactory '{0}' did not return a controller for a controller named '{1}'.&quot;</span>,                     <span class="kwrd">new</span> <span class="kwrd">object</span>[] { controllerFactory.GetType(), requiredString }));
            }
            <span class="kwrd">try</span>
            {
                ((ControllerBase) controller).ValidateRequest = _validateRequest;
                controller.Execute(RequestContext);
            }
            <span class="kwrd">finally</span>
            {
                controllerFactory.ReleaseController(controller);
            }
        }
    }

    <span class="kwrd">private</span> <span class="kwrd">class</span> OverrideHttpMethodHttpRequestWrapper : HttpRequestWrapper {
        <span class="kwrd">public</span> OverrideHttpMethodHttpRequestWrapper(HttpRequest httpRequest) : <span class="kwrd">base</span>(httpRequest) { }

        <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> HttpMethod {
            get { <span class="kwrd">return</span> <span class="str">&quot;GET&quot;</span>; }
        }
    }

    <span class="kwrd">private</span> <span class="kwrd">class</span> OverrideRequestHttpContextWrapper : HttpContextWrapper {
        <span class="kwrd">private</span> <span class="kwrd">readonly</span> HttpContext _httpContext;
        <span class="kwrd">public</span> OverrideRequestHttpContextWrapper(HttpContext httpContext) : <span class="kwrd">base</span>(httpContext) {
            _httpContext = httpContext;
        }

        <span class="kwrd">public</span> <span class="kwrd">override</span> HttpRequestBase Request {
            get { <span class="kwrd">return</span> <span class="kwrd">new</span> OverrideHttpMethodHttpRequestWrapper(_httpContext.Request); }
        }
    }

    <span class="preproc">#endregion</span>
}</pre>
<style type="text/css">
<p>.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; }</style>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.captaincodeman.com/2009/02/21/rendersubaction-alternative-to-renderaction-for-sub-controllers-in-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
