<?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>Arrange Act Assert &#187; Asp.Net MVC</title> <atom:link href="http://www.arrangeactassert.com/category/asp-net-mvc/feed/" rel="self" type="application/rss+xml" /><link>http://www.arrangeactassert.com</link> <description>Jag Reehal on Agile Development, ASP.NET MVC and all manner of good stuff</description> <lastBuildDate>Thu, 24 Nov 2011 00:01:20 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /> <item><title>How to deploy ASP.NET MVC applications to AppHarbor</title><link>http://www.arrangeactassert.com/how-to-deploy-asp-net-mvc-applications-to-appharbor/</link> <comments>http://www.arrangeactassert.com/how-to-deploy-asp-net-mvc-applications-to-appharbor/#comments</comments> <pubDate>Wed, 13 Apr 2011 01:59:46 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[AppHarbor]]></category> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Entity Framework]]></category> <category><![CDATA[Git]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1785</guid> <description><![CDATA[I’ve already blogged about how awesome AppHarbor is. So to back up my opinion I’ve decided to write a tutorial about how to deploy an ASP.NET MVC application to AppHarbor. The application we’ll be deploying will be the ASP.NET MVC Music Store (created by James Senior, Jon Galloway and Scott Hanselman) which uses ASP.NET MVC [...]]]></description> <content:encoded><![CDATA[<p>I’ve already blogged about <a
href="http://www.arrangeactassert.com/why-im-using-appharbor-to-host-my-asp-net-mvc-sites/">how awesome AppHarbor</a> is.</p><p>So to back up my opinion I’ve decided to write a tutorial about how to deploy an <a
href="http://www.asp.net/mvc">ASP.NET MVC</a> application to <a
href="http://appharbor.com/">AppHarbor</a>.</p><p>The application we’ll be deploying will be the <a
href="http://mvcmusicstore.codeplex.com">ASP.NET MVC Music Store</a> (created by <a
href="http://twitter.com/jsenior">James Senior</a>, <a
href="http://twitter.com/jongalloway">Jon Galloway</a> and <a
href="http://twitter.com/shanselman">Scott Hanselman</a>) which uses ASP.NET MVC 3 with Razor syntax and data access via <a
href="http://msdn.microsoft.com/en-us/data/aa937723">Entity Framework 4</a>.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/ASPNETMVCMusicStoreHomepage.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/ASPNETMVCMusicStoreHomepage.png" alt="ASP.NET MVC MusicStore Homepage" title="ASP.NET MVC MusicStore Homepage" width="690" height="339" class="aligncenter size-full wp-image-1805" /></a></p><p><a
href="http://mvcmusicstoredemo.apphb.com/">Click here</a> to a deployed version of the ASP.NET MVC Music Store running on AppHarbor.</p><p>To follow along with the tutorial you’ll need to have the following installed:</p><ul><li><a
href="http://www.microsoft.com/express/Web/">Visual Web Developer 2010 Express</a> or <a
href="http://www.microsoft.com/visualstudio/">Visual Studio 2010</a></li><li><a
href="http://www.microsoft.com/express/Web/">SQL Server 2008 Express</a> or <a
href="http://www.microsoft.com/sqlserver/2008">SQL Server 2008</a></li><li><a
href="http://www.asp.net/mvc/mvc3">ASP.NET MVC 3</a></li><li><a
href="http://code.google.com/p/msysgit/">Git</a> (<a
href="http://help.github.com/win-set-up-git/">use this guide to help you install</a>)</li><li><a
href="http://mvcmusicstore.codeplex.com">A downloaded an unzipped version of the ASP.NET MVC Music Store</a></li></ul><p>If you&#8217;re also going to use the ASP.NET MVC Music Store please ensure you change the ..\Views\Shared\_Layout.cshtml to include HTML to indicate the site is a sample available from codeplex and a noindex robots meta tag.</p><pre class="brush: xml; gutter: true; highlight: [4,5,12,13,14]; title: ; toolbar: true; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta name=&quot;robots&quot; content=&quot;noindex,nofollow&quot; /&gt;
    &lt;title&gt;This is a ASP.NET MVC sample application which can be downloaded at http://mvcmusicstore.codeplex.com&lt;/title&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot;
        type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.4.4.min.js&quot;)&quot;
        type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
 &lt;p style=&quot;padding:20px;background-color:#000;color:#FFF;text-align:center&quot;&gt;
        This is a ASP.NET MVC sample application which can be downloaded at &lt;a href=&quot;http://mvcmusicstore.codeplex.com&quot;&gt;http://mvcmusicstore.codeplex.com&lt;/a&gt;
    &lt;/p&gt;
    &lt;div id=&quot;header&quot;&gt;
        &lt;h1&gt;
            &lt;a href=&quot;/&quot;&gt;ASP.NET MVC MUSIC STORE&lt;/a&gt;
        &lt;/h1&gt;
       &lt;ul id=&quot;navlist&quot;&gt;
           &lt;li class=&quot;first&quot;&gt;&lt;a href=&quot;@Url.Content(&quot;~&quot;)&quot; id=&quot;current&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
           &lt;li&gt;&lt;a href=&quot;@Url.Content(&quot;~/Store/&quot;)&quot;&gt;Store&lt;/a&gt;&lt;/li&gt;
           &lt;li&gt;@{Html.RenderAction(&quot;CartSummary&quot;, &quot;ShoppingCart&quot;);}&lt;/li&gt;
           &lt;li&gt;&lt;a href=&quot;@Url.Content(&quot;~/StoreManager/&quot;)&quot;&gt;Admin&lt;/a&gt;&lt;/li&gt;
       &lt;/ul&gt;
    &lt;/div&gt;
    @{Html.RenderAction(&quot;GenreMenu&quot;, &quot;Store&quot;);}
    &lt;div id=&quot;main&quot;&gt;
        @RenderBody()
    &lt;/div&gt;
    &lt;div id=&quot;footer&quot;&gt;
        built with &lt;a href=&quot;http://asp.net/mvc&quot;&gt;ASP.NET MVC 3&lt;/a&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><h3 class="subheading">Let&#8217;s get started</h3><style type="text/css">#steps{padding:0
0 0 18px;color:#008000}#steps
li{margin-bottom:10px}</style><ol
id="steps"><li> <a
href="http://www.arrangeactassert.com/how-to-add-a-asp-net-mvc-solution-to-a-git-repository">How to add a ASP.NET MVC solution to a Git repository</a></li><li><a
href="http://www.arrangeactassert.com/how-to-push-a-asp-net-mvc-git-repository-to-appharbor">How to push a ASP.NET MVC Git repository to AppHarbor</a></li><li><a
href="http://www.arrangeactassert.com/how-to-create-a-sql-server-database-in-appharbor">How To Create a SQL Server Database in AppHarbor</a></li><li><a
href="http://www.arrangeactassert.com/how-to-configure-asp-net-mvc-to-use-a-sql-server-database-in-appharbor">How to configure ASP.NET MVC to use a SQL Server database in AppHarbor</a></li></ol><h3 class="subheading">I can browse around the store and add things to my cart but can’t log in as an administrator</h3><p>That’s because you can only have one database per application&#8230; something I didn’t know when I started this series.</p><p>As AppHarbor doesn’t support file storage (yet) you can’t use the ASPDBNET.MDF database which the music store uses for ASP.NET Membership. <a
href="http://support.appharbor.com/discussions/problems/379-app_data-copy-on-new-deploy">See this AppHarbor support entry for more details</a>.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/OnlyOneAppHarborDatabaseIsAllowed.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/OnlyOneAppHarborDatabaseIsAllowed.png" alt="Only One AppHarbor Database Is Allowed" title="Only One AppHarbor Database Is Allowed" width="558" height="107" class="alignleft size-full wp-image-1909" /></a></p><p><br/><br
/> You can of course workaround this by adding membership tables etc. to the existing SQL Server database by via an alternative membership provider which includes using another application hosted on AppHarbor.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-deploy-asp-net-mvc-applications-to-appharbor/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>How to add a ASP.NET MVC solution to a Git repository</title><link>http://www.arrangeactassert.com/how-to-add-a-asp-net-mvc-solution-to-a-git-repository/</link> <comments>http://www.arrangeactassert.com/how-to-add-a-asp-net-mvc-solution-to-a-git-repository/#comments</comments> <pubDate>Wed, 13 Apr 2011 01:59:05 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[AppHarbor]]></category> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Git]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1789</guid> <description><![CDATA[In this tutorial we’ll be looking at how to add a ASP.NET MVC solution to a Git repository. This tutorial is part of a series about how to deploy ASP.NET MVC applications to AppHarbor. If you haven’t installed Git yet use this guide to get you started. Before you initialize you git repository it’s a [...]]]></description> <content:encoded><![CDATA[<p>In this tutorial we’ll be looking at how to add a ASP.NET MVC solution to a Git repository.</p><p>This tutorial is part of a series about <a
href="http://www.arrangeactassert.com/how-to-deploy-asp-net-mvc-applications-to-appharbor">how to deploy ASP.NET MVC applications to AppHarbor</a>.</p><p>If you haven’t installed Git yet use this <a
href="http://progit.org/book/ch1-3.html">guide</a> to get you started.</p><p>Before you initialize you git repository it’s a good idea to have a .gitignore file in root of the repository which instructs Git what files to ignore.</p><p>As you can see in the example below it excludes things which you don’t need to version control such as output directories and anything created by ReSharper.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
*git
#ignore thumbnails created by windows
Thumbs.db
#Ignore files build by Visual Studio
*.obj
*.exe
*.pdb
*.user
*.aps
*.pch
*.vspscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.cache
*.ilk
*.log
[Bb]in
[Dd]ebug*/
*.lib
*.sbr
obj/
[Rr]elease*/
_ReSharper*/
[Tt]est[Rr]esult*
</pre><p>In the directory containing your ASP.NET MVC solution, right click and start Git Bash, or start Git Bash and navigate to the directory.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/GitDirectoryLocation.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/GitDirectoryLocation.png" alt="Git Directory Location" title="Git Directory Location" width="690" height="643" class="aligncenter size-full wp-image-1814" /></a></p><p>If this is the first time you’re using Git I recommended executing the following commands to set your user name and email address in the git.config which are used to track commits in the Git repository.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
git config --global user.name jagreehal
git config --global user.email jag.reehal@gmail.com
</pre><p>To initialise a repository execute the following command</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
git init
</pre><p>Because we’ve used a gitignore file we can use the following Git command to add all files in the directory (and sub directories) into the repository.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
git add .
</pre><p>Alternatively you could have added each file individually like this (for those who want total control)</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
git add &lt;filename&gt;
</pre><p>The final step is to commit your changes.  The –m option allows you to add a message (otherwise you’ll be promoted for one)</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
git commit -m &quot;Initial commit&quot;
</pre><p>In the next part of the series we’ll be looking at <a
href="http://www.arrangeactassert.com/how-to-push-a-asp-net-mvc-git-repository-to-appharbor">how to push your ASP.NET MVC Git repository to AppHarbor</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-add-a-asp-net-mvc-solution-to-a-git-repository/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How to push a ASP.NET MVC Git repository to AppHarbor</title><link>http://www.arrangeactassert.com/how-to-push-a-asp-net-mvc-git-repository-to-appharbor/</link> <comments>http://www.arrangeactassert.com/how-to-push-a-asp-net-mvc-git-repository-to-appharbor/#comments</comments> <pubDate>Wed, 13 Apr 2011 01:58:52 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[AppHarbor]]></category> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Git]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1801</guid> <description><![CDATA[In this tutorial I’ll be showing you how to push a Git repository for a .NET solution site to AppHarbor. This follows on from the tutorial for adding a ASP.NET MVC solution to a Git repository. The first steps are to create an AppHarbor account if you haven’t got one, and then create an application [...]]]></description> <content:encoded><![CDATA[<p>In this tutorial I’ll be showing you how to push a Git repository for a .NET solution site to AppHarbor.</p><p>This follows on from the tutorial for <a
href="http://www.arrangeactassert.com/how-to-add-a-asp-net-mvc-solution-to-a-git-repository">adding a ASP.NET MVC solution to a Git repository.</a></p><p>The first steps are to create an AppHarbor account if you haven’t got one, and then create an application</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/CreateAppHarborApp.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/CreateAppHarborApp.png" alt="Create AppHarbor App" title="Create AppHarbor App" width="353" height="339" class="alignleft size-full wp-image-1818" /></a></p><p><br/><br
/> on the following page keep a note of the URLs where you’ll be pushing your Git repository to</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/AppHarborURLs.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/AppHarborURLs.png" alt="App Harbor URLs" title="App Harbor URLs" width="690" height="563" class="alignleft size-full wp-image-1819" /></a></p><p><br/><br
/> In the directory containing your ASP.NET MVC solution start Git Bash, or start Git Bash and navigate to the directory.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/GitDirectoryLocationToPush.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/GitDirectoryLocationToPush.png" alt="Git Directory Location To Push" title="Git Directory Location To Push" width="660" height="685" class="alignleft size-full wp-image-1826" /></a></p><p><br/><br
/> Execute the following commands (substituting your URLs) to push your ASP.NET MVC solution to AppHarbor.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
git remote add appharbor https://jagreehal@appharbor.com/MvcMusicStoreDemo.git
git push appharbor master
</pre><p>When you’re prompted to enter your password, use the same one for your AppHarbor account.</p><p>Next go to the build page on AppHarbor to see the status of your app.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/AppHarborBuild.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/AppHarborBuild.png" alt="App Harbor Build" title="App Harbor Build" width="690" height="532" class="alignleft size-full wp-image-1823" /></a></p><p><br/><br
/> If you’re following along with the example to deploy the ASP.NET MVC Music Store to AppHarbor you’ll see the site doesn’t work yet.</p><p>That’s because you can’t use MDF database files in AppHarbor yet so the next step is <a
href=" http://www.arrangeactassert.com/how-to-create-a-sql-server-database-in-appharbor">create the ASP.NET MVC Music Store SQL Server database in AppHarbor</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-push-a-asp-net-mvc-git-repository-to-appharbor/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How To Create a SQL Server Database in AppHarbor</title><link>http://www.arrangeactassert.com/how-to-create-a-sql-server-database-in-appharbor/</link> <comments>http://www.arrangeactassert.com/how-to-create-a-sql-server-database-in-appharbor/#comments</comments> <pubDate>Wed, 13 Apr 2011 01:58:31 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[AppHarbor]]></category> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Entity Framework]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1829</guid> <description><![CDATA[In the last part of the tutorial about how to deploy ASP.NET MVC applications to AppHarbor we pushed an ASP.NET MVC site to AppHarbor. Although the build was successful an error occured when viewing the site becuase it couldn’t connect to the attached database. To fix this we need to create a SQL Server Database [...]]]></description> <content:encoded><![CDATA[<p>In the last part of the tutorial about <a
href="http://www.arrangeactassert.com/how-to-deploy-asp-net-mvc-applications-to-appharbor">how to deploy ASP.NET MVC applications to AppHarbor</a> we <a
href="http://www.arrangeactassert.com/how-to-push-a-asp-net-mvc-git-repository-to-appharbor">pushed an ASP.NET MVC site to AppHarbor</a>.</p><p>Although the build was successful an error occured when viewing the site becuase it couldn’t connect to the attached database.</p><p>To fix this we need to create a SQL Server Database in Appharbor.</p><p>On the AppHarbor application management page click the link to &#8216;Add database&#8217;</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/AppHarborBuild.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/AppHarborBuild.png" alt="App Harbor Build" title="App Harbor Build" width="690" height="532" class="alignleft size-full wp-image-1823" /></a><br
/> <br/></p><p>Next choose SQL Server as the database type, enter a connection string name and click the create button.</p><p>I used the same connection string name used by Entity Framework 4 in the ASP.NET MVC Music Store application.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/NewAppHarborDatabase.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/NewAppHarborDatabase.png" alt="New AppHarbor Database" title="New AppHarbor Database" width="670" height="602" class="alignleft size-full wp-image-1830" /></a></p><p><br/><br
/> The following screen shows you what connection string should be used in your config file and information about how to connect to the Appharbor database from Microsoft SQL Server Managemnt Studio.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/DatabaseConnectionSettings.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/DatabaseConnectionSettings.png" alt="Database Connection Settings" title="Database Connection Settings" width="690" height="657" class="alignleft size-full wp-image-1831" /></a></p><p><br/><br
/> When you connect to the database in Microsoft SQL Server Managemnt Studio you’ll see the database is empty.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/EmptyAppHarborDatabase.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/EmptyAppHarborDatabase.png" alt="Empty AppHarbor Database" title="Empty AppHarbor Database" width="361" height="475" class="alignleft size-full wp-image-1832" /></a></p><p><br/><br
/> In the Assets/Data folder in the ASP.NET MVC Music Store you’ll find a ‘MvcMusicStore-Create.sql’ SQL script which can be used to create and populate the tables required by the application.</p><p>Before running the script delete the first line that looks like this</p><pre class="brush: sql; gutter: false; title: ; toolbar: true; notranslate">
USE [C:\USERS\JON\DOCUMENTS\JON-SHARE\MVCMUSICSTORE-MVC3\MVCMUSICSTORE\MVCMUSICSTORE\APP_DATA\MVCMUSICSTORE.MDF]
</pre><p>When the script has been completed successfully the tables will have been created and populated</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/PopulatedAppHarborDatabase.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/PopulatedAppHarborDatabase.png" alt="Populated AppHarbor Database" title="Populated AppHarbor Database" width="660" height="715" class="alignleft size-full wp-image-1833" /></a></p><p><br/><br
/> In the next step of this tutorial we will see <a
href=" http://www.arrangeactassert.com/how-to-configure-asp-net-mvc-to-use-a-sql-server-database-in-appharbor">how to configure ASP.NET MVC to use a SQL Server database in AppHarbor</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-create-a-sql-server-database-in-appharbor/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>How to configure ASP.NET MVC to use a SQL Server database in AppHarbor</title><link>http://www.arrangeactassert.com/how-to-configure-asp-net-mvc-to-use-a-sql-server-database-in-appharbor/</link> <comments>http://www.arrangeactassert.com/how-to-configure-asp-net-mvc-to-use-a-sql-server-database-in-appharbor/#comments</comments> <pubDate>Wed, 13 Apr 2011 01:58:20 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[AppHarbor]]></category> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Git]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1836</guid> <description><![CDATA[In this tutorial about how to deploy ASP.NET MVC applications to AppHarbor is to update the ASP.NET MVC web.config file, commit the change and push the Git repository to AppHarbor. Modify the connection string in the ASP.NET MVC web.config to use the AppHarbor database created in last tutorial. In the directory containing your ASP.NET MVC [...]]]></description> <content:encoded><![CDATA[<p>In this tutorial about <a
href="http://www.arrangeactassert.com/how-to-deploy-asp-net-mvc-applications-to-appharbor">how to deploy ASP.NET MVC applications to AppHarbor</a> is to update the ASP.NET MVC web.config file, commit the change and push the Git repository to AppHarbor.</p><p>Modify the connection string in the ASP.NET MVC web.config to use the <a
href="http://www.arrangeactassert.com/how-to-create-a-sql-server-database-in-appharbor">AppHarbor database created in last tutorial</a>.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;connectionStrings&gt;
  &lt;add name=&quot;MusicStoreEntities&quot;
        connectionString=&quot;Server=db003.appharbor.net;Database=db1814;User ID=db1814;Password=&lt;yourpassword&gt;&quot;
        providerName=&quot;System.Data.SqlClient&quot; /&gt;
&lt;/connectionStrings&gt;
</pre><p>In the directory containing your ASP.NET MVC solution, right click and start Git Bash, or start Git Bash and navigate to the directory.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/GitDirectoryLocationToPush.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/GitDirectoryLocationToPush.png" alt="Git Directory Location To Push" title="Git Directory Location To Push" width="660" height="685" class="alignleft size-full wp-image-1826" /></a></p><p><br/><br
/> Execute the following commands to commit the updated web.config file in the git repository and push to AppHarbor</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
git add MvcMusicStore/web.config
git commit –m &quot;Now using AppHarbor SQL Server&quot;
git push appharbor master
</pre><p>Once the appliation has been built you should have <a
href="http://mvcmusicstoredemo.apphb.com/">a working ASP.NET MVC Music store running in AppHarbor</a>.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2011/04/WorkingMusicStoreInAppHarbor.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2011/04/WorkingMusicStoreInAppHarbor.png" alt="Working Music Store In AppHarbor" title="Working Music Store In AppHarbor" width="690" height="606" class="alignleft size-full wp-image-1837" /></a></p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-configure-asp-net-mvc-to-use-a-sql-server-database-in-appharbor/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Why I&#8217;m using AppHarbor to host my ASP.NET MVC sites</title><link>http://www.arrangeactassert.com/why-im-using-appharbor-to-host-my-asp-net-mvc-sites/</link> <comments>http://www.arrangeactassert.com/why-im-using-appharbor-to-host-my-asp-net-mvc-sites/#comments</comments> <pubDate>Thu, 07 Apr 2011 08:00:14 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[AppHarbor]]></category> <category><![CDATA[Asp.Net MVC]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1750</guid> <description><![CDATA[About two months ago I heard about Heroku, a hosting service which can host Ruby apps in the cloud for free. I was envious that Ruby folk could do away with traditional hosting solutions and move to a cloud platform that was fresh, modern and simple to use. Without paying a penny you get one [...]]]></description> <content:encoded><![CDATA[<p>About two months ago I heard about <a
href="http://heroku.com">Heroku</a>, a hosting service which can host  Ruby apps in the cloud for free.</p> <section
style="background:#29264D; padding:10px;margin:10px 0;"> <a
href="http://heroku.com/"><img
src="https://nav.heroku.com/images/logos/logo.png" alt="Heroku" /></a><br
/> </section><p>I was envious that Ruby folk could do away with traditional hosting solutions and move to a cloud platform that was fresh, modern and simple to use.</p><p>Without paying a penny you get one dyno which handles concurrent HTTP requests which you can easily scale up by adding additional web or background processors without breaking the bank.</p><p>Used in conjunction with <a
href="https://github.com/mojombo/jekyll">Jekyll</a>, a static web site generator, one dyno should be adequate for most people&#8217;s needs.</p><p>So I started putting together a site for my new company.</p><p>This was great except I needed to do some custom tasks which meant creating Ruby extensions&#8230; which meant I had to learn Ruby.</p><p>Then a colleague mentioned <a
href="http://appharbor.com">AppHarbor</a>.</p> <section
style="color:#7A987A;background:#243239; padding:30px 10px;margin:10px 0;font-family:calibri;font-weight:bold;font-size:24px"> App Harbor</section><p>AppHarbor is like Heroku for .Net developers, providing a free platform to host .Net applications in the cloud.</p><p>Similar to Heroku you can scale up but with the added bonus of a free 20mb instance of Sql Server.</p><p>I haven&#8217;t been so excited by something like this in the .Net world for a while, and am so impressed by what the team have achieved.</p><p>There&#8217;s plenty of good documentation on how to get started on the web already, so check out</p><ul><li> <a
href="http://www.hanselman.com/blog/HanselminutesPodcast255TheOpinionatedCloudLearningAboutAppHarbor.aspx">Scott Hanselman&#8217;s podcast &#8216;The Opinionated Cloud &#8211; Learning about AppHarbor&#8217;</a></li><li> <a
href="http://www.aaronstannard.com/post/2011/01/14/Getting-Started-with-AppHarbor-e28093-Heroku-for-NET.aspx">Getting Started with AppHarbor, Heroku for .NET by Aaron Stannard</a></li></ul><p>for more information.</p><h3 class="subheading">Still not impressed?</h3><p>What if I said that you could push code up to AppHarbor and see changes on your live site within minutes or that AppHarbor only deploys changes to your live site if the build and unit tests are successful?</p><p>It&#8217;s clever stuff, you&#8217;ve effectively got a free continuous integration server in the cloud!</p><p>You can even go back and deploy old versions if you ever need to.</p><p>AppHarbor is still new so they are missing a couple of useful features at the moment.  But they are getting better all the time.</p><p>Questions in the support forum and answered quickly, and they really do seem to be listening to the community.</p><p>I’ve already moved my company ASP.NET MVC site over and will be writing more about AppHarbor next week.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/why-im-using-appharbor-to-host-my-asp-net-mvc-sites/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Using Html.Raw in ASP.NET MVC Razor Views</title><link>http://www.arrangeactassert.com/using-html-raw-in-asp-net-mvc-razor-views/</link> <comments>http://www.arrangeactassert.com/using-html-raw-in-asp-net-mvc-razor-views/#comments</comments> <pubDate>Mon, 13 Dec 2010 12:00:14 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Razor]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1451</guid> <description><![CDATA[With the release of ASP.NET MVC 3 Release Candidate 2 (RC2) you can finally use Html.Raw when you don’t your output to be encoded. So this means you don’t have to use @MvcHtmlString.Create(ViewBag.HtmlOutput) or @(new HtmlString(ViewBag.HtmlOutput)) or anything else to output a string containing HTML in ASP.NET MVC. An example of using Html.Raw in ASP.NET [...]]]></description> <content:encoded><![CDATA[<p>With the release of ASP.NET MVC 3 Release Candidate 2 (RC2) you can finally use Html.Raw when you don’t your output to be encoded.</p><p>So this means you don’t have to use</p><p>@MvcHtmlString.Create(ViewBag.HtmlOutput)</p><p>or</p><p>@(new HtmlString(ViewBag.HtmlOutput))</p><p>or anything else to output a string containing HTML in ASP.NET MVC.</p><h3 class="subheading">An example of using Html.Raw in ASP.NET MVC 3 using Razor</h3><p>The code below shows the HTML string to be outputted being added the dynamic ViewBag collection.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class HomeController : Controller
{
    public ActionResult Index()
    {
        StringBuilder htmlOutput = new StringBuilder();
        htmlOutput.Append(&quot;&lt;p&gt;The image below is from &quot; );
        htmlOutput.Append(&quot;&lt;a href=\&quot;http://commons.wikimedia.org/wiki/Main_Page\&quot;&gt;Wikimedia Commons&lt;/a&gt;&quot;);
        htmlOutput.Append(&quot;&lt;/p&gt;&quot;);
        htmlOutput.Append(&quot;&lt;img src=\&quot;http://upload.wikimedia.org/wikipedia/commons/6/63/CampNou.jpg\&quot; alt=\&quot;Cam Nou\&quot; title=\&quot;Cam Nou\&quot;/&gt;&quot;);
        ViewBag.HtmlOutput = htmlOutput.ToString();
        return View();
    }
}
</pre><p>Which can be used in a view like this</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
@{
    ViewBag.Title = &quot;Index&quot;;
}

@Html.Raw(ViewBag.HtmlOutput)
</pre><p>to show the following output in a browser</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2010/12/OutputUsingHtmlRaw.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2010/12/OutputUsingHtmlRaw.png" alt="Output Using HtmlRaw in ASP.NET MVC" title="Output Using HtmlRaw" width="466" height="524" class="aligncenter size-full wp-image-1465" /></a></p><p>For more information check out <a
href="http://weblogs.asp.net/scottgu/archive/2010/12/10/announcing-asp-net-mvc-3-release-candidate-2.aspx">Scott Gu’s post Announcing ASP.NET MVC 3 (Release Candidate 2)</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/using-html-raw-in-asp-net-mvc-razor-views/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>When to use Html.RenderPartial and Html.RenderAction in ASP.NET MVC Razor Views</title><link>http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/</link> <comments>http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/#comments</comments> <pubDate>Mon, 13 Dec 2010 10:00:45 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Razor]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1402</guid> <description><![CDATA[In this blog post I want to show examples when to use Html.RenderPartial and Html.RenderAction when creating web sites in ASP.NET MVC using the Razor view engine. Some background information on Html.RenderAction and Html.RenderPartial Html.RenderAction is a somewhat contentious feature because it invokes a controller action. This means each time it’s called a new request [...]]]></description> <content:encoded><![CDATA[<p>In this blog post I want to show examples when to use Html.RenderPartial and Html.RenderAction when creating web sites in ASP.NET MVC using the Razor view engine.</p><h3 class="subheading">Some background information on Html.RenderAction and Html.RenderPartial</h3><p>Html.RenderAction is a somewhat contentious feature because it invokes a controller action.</p><p>This means each time it’s called a new request (which has to go through the ASP.NET MVC pipeline) is made.</p><p>As shown below ASP.NET MVC requests are routed to a controller.  It&#8217;s the controller that decides what view to call and what data (model) to pass to it.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2010/12/ASPNETMVCRenderAction.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2010/12/ASPNETMVCRenderAction.png" alt="Architecture for Html.RenderAction" title="Architecture for Html.RenderAction" width="692" height="178" class="aligncenter size-full wp-image-1417" /></a>A view has one responsibility and that&#8217;s to render HTML.  It’s supposed to be simple, it doesn’t know (or care) where the data in the model comes from.</p><p>The thing MVC traditionalists frown upon is the fact that Html.RenderAction can execute child actions in ASP.NET MVC views.</p><p>However given that Html.RenderAction just like an AJAX request is a form of sub request, the case against seems somewhat outdated and doesn&#8217;t take into the account using Html.RenderAction will allow you to separate concerns of models and controllers as we will see later in this post.</p><p>For Html.RenderPartial the content of the partial view is added to content of the host view, either directly to the response output (or by using a StringWriter if you use or Html.Partial).</p><h3 class="subheading">Examples of when to use Html.RenderPartial and Html.RenderAction</h3><p>The mockup below shows a blog post with comments and a list of categories in a side bar.</p><p><a
href="http://www.arrangeactassert.com/wp-content/uploads/2010/12/mockup.png"><img
src="http://www.arrangeactassert.com/wp-content/uploads/2010/12/mockup.png" alt="ASP.NET MVC mockup" title="ASP.NET MVC mockup" width="687" height="910" class="aligncenter size-full wp-image-1419" /></a></p><h3 class="subheading">When to use Html.RenderPartial (or Html.Partial)</h3><p>For the page we’re designing I would create a view to show the blog post and call Html.RenderPartial to output the comments</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
@model WhenToUseRenderActionAndRenderPartial.Models.ShowPostViewModel
@{
    ViewBag.Title = Model.Post.Title;
}

&lt;section&gt;
    &lt;article&gt;
        &lt;header&gt;
            &lt;h1&gt;@Model.Post.Title&lt;/h1&gt;
        Posted on | &lt;time datetime=&quot;@Model.Post.DatePublished.ToString(&quot;s&quot;)&quot;&gt;
           @Model.Post.DatePublished.ToLongDateString()
        &lt;/time&gt; | @Model.Comments.Count() Comments
        &lt;/header&gt;
        @Html.Raw(Model.Post.Content)
    &lt;/article&gt;
&lt;/section&gt;
@{Html.RenderPartial(&quot;_Comments&quot;, Model.Comments);}
</pre><p>The partial view for comments would look like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
@model IEnumerable&lt;WhenToUseRenderActionAndRenderPartial.Models.Comment&gt;
&lt;section&gt;
    &lt;header&gt;
        &lt;h3&gt;
            Comments&lt;/h3&gt;
    &lt;/header&gt;
    @foreach (var comment in Model)
    {
        &lt;article&gt;
            &lt;header&gt;
                @comment.Author on
                &lt;time datetime=&quot;@comment.DateCreated.ToString(&quot;s&quot;) &quot;&gt;
                    @comment.DateCreated.ToLongDateString()
                &lt;/time&gt;
            &lt;/header&gt;
            &lt;img alt=&quot;@comment.Author&quot; src=@comment.ImageUrl /&gt;
            &lt;p&gt;
                @comment.Content
            &lt;/p&gt;
        &lt;/article&gt;
    }
&lt;/section&gt;
</pre><p>This means the ShowPost action in the Blog controller</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using WhenToUseRenderActionAndRenderPartial.Models;

namespace WhenToUseRenderActionAndRenderPartial.Controllers
{
    public class BlogController : Controller
    {
        public ActionResult ShowPost()
        {
            ShowPostViewModel viewModel = new ShowPostViewModel();
            viewModel.Post = new Post
                            {
                                Title = &quot;Blog Title&quot;,
                                Content = &quot;&lt;p&gt;Lorem ipsum dolor sit amet&lt;/p&gt;&quot;,
                                DatePublished = new DateTime(2010, 10, 5)
                            };
            viewModel.Comments = new List&lt;Comment&gt;()
                                             {
                                                 new Comment()
                                                     {
                                                         Author = &quot;Andrew&quot;,
                                                         Content = &quot;I think&quot;,
                                                         DateCreated = new DateTime(2010, 10, 5)
                                                     },
                                                new Comment()
                                                     {
                                                         Author = &quot;Bill&quot;,
                                                         Content = &quot;I reckon&quot;,
                                                         DateCreated = new DateTime(2010, 10, 5)
                                                     },
                                                new Comment()
                                                     {
                                                         Author = &quot;Chris&quot;,
                                                         Content = &quot;My opinion&quot;,
                                                         DateCreated = new DateTime(2010, 10, 6)
                                                     }
                                             };
            return View(viewModel);
        }
    }
}
</pre><p>needs to pass a model with properties for the blog post and its comments to the view.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class Post
{
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime DatePublished { get; set; }
}

public class Comment
{
    public string Content { get; set; }
    public string Author { get; set; }
    public string ImageUrl { get; set; }
    public DateTime DateCreated { get; set; }
}

public class ShowPostViewModel
{
    public Post Post { get; set; }
    public IEnumerable&lt;Comment&gt; Comments { get; set; }
}
</pre><h3 class="subheading">When to use Html.RenderAction (or Html.Action)</h3><p>So while we could add a property for categories to the ShowPostViewModel used for the ShowPost page and use Html.RenderPartial to display them, we have to add a category property to every model in our solution where categories are shown.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ShowPostViewModel
{
    public Post Post { get; set; }
    public IEnumerable&lt;Comment&gt; Comments { get; set; }
    public IEnumerable&lt;Category&gt; Categories { get; set; }
}

public class AnotherViewModel
{
    public string StringToOutput { get; set; }
    public IEnumerable&lt;Category&gt; Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</pre><p>And using a base class with a categories property and have ViewModel classes inherit from it would just be bloating models with unrelated data and concerns.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ViewModelBase
{
    public IEnumerable&lt;Category&gt; Categories { get; set; }
}

public class ShowPostViewModel : ViewModelBase
{
    public Post Post { get; set; }
    public IEnumerable&lt;Comment&gt; Comments { get; set; }
}
</pre><p>So if you want to display the same information on multiple pages and the data doesn’t necessarily depend on or isn’t related to the rest of the page, something like a widget to display categories then I would use Html.RenderAction.</p><p>As shown in the markup below Html.RenderAction is called from the layout page for the blog post.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;@ViewBag.Title&lt;/title&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.4.4.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    @RenderBody()
    @{Html.RenderAction(&quot;Show&quot;, &quot;Category&quot;);}
&lt;/body&gt;
&lt;/html&gt;
</pre><h3 class="subheading">Jag Reehal’s Final Thought on &#8216;When to use Html.RenderPartial and Html.RenderAction in ASP.NET MVC Razor Views&#8217;</h3><p>In cases where a model for the page is already populated with all the information required I would use Html.RenderPartial.</p><p>If the same information is shown on multiple pages it’s likely that the data needs to be in its own model so I would use Html.RenderAction.  As shown in this post I would say layout pages are going to the most common place Html.RenderAction will be used.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/feed/</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>ASP.NET MVC Razor View Best Practices – Keep logic out of your Razor views</title><link>http://www.arrangeactassert.com/asp-net-mvc-razor-view-best-practices-keep-logic-out-of-your-razor-views/</link> <comments>http://www.arrangeactassert.com/asp-net-mvc-razor-view-best-practices-keep-logic-out-of-your-razor-views/#comments</comments> <pubDate>Mon, 02 Aug 2010 00:11:25 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[Razor]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1129</guid> <description><![CDATA[Last year I wrote a blog post about how you could keep logic out of your ASP.NET MVC views. Now with the introduction of the Razor view engine for ASP.NET MVC, I thought it would be a good idea to do a ‘Razor’ version. The code used in this post can be downloaded here. If [...]]]></description> <content:encoded><![CDATA[<p>Last year I wrote a blog post about how you could <a
href="http://www.arrangeactassert.com/asp-net-mvc-view-best-practices-keep-logic-out-of-your-views/">keep logic out of your ASP.NET MVC views</a>.</p><p>Now with the <a
href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx">introduction of the Razor view engine for ASP.NET MVC</a>, I thought it would be a good idea to do a ‘Razor’ version.</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Keep%20logic%20out%20of%20your%20Razor%20views.zip">here</a>.</p><p>If you recall the reasons you should not have logic in your views are because they will become difficult to read, maintain and test at the very least.</p><h3 class="subheading">How to decide what CSS class to use for the stock level in a Razor view</h3><p>The screenshot below shows the three possible messages displayed to the user depending on the number of units in stock.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/OutputForLogicOutOfViewsBlogPost.png" alt="Output For Logic Out Of Views Blog Post" /></p><h3 class="subheading">An example of a Razor view with conditional logic</h3><p>We could select the CSS class for the corresponding number of units in stock using multiple if statements like this</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
@inherits System.Web.Mvc.WebViewPage&lt;KeepLogicOutOfYourRazorViews.Models.Product&gt;
@using KeepLogicOutOfYourRazorViews.Helpers

@{
	View.Title = &quot;Index&quot;;
	LayoutPage = &quot;~/Views/Shared/_Layout.cshtml&quot;;
}

&lt;div class=&quot;example&quot;&gt;
@if(Model.UnitsInStock == 0){
								&lt;div class=&quot;stockLevel stockLevelNone&quot;&gt;
									&lt;span&gt;Number Of Units In Stock: @Model.UnitsInStock&lt;/span&gt;
								&lt;/div&gt;
							}
@if(Model.UnitsInStock &gt; 0 &amp;&amp; Model.UnitsInStock &lt;= 20)
							{
								&lt;div class=&quot;stockLevel stockLevelLow&quot;&gt;
									&lt;span&gt;Number Of Units In Stock:	@Model.UnitsInStock&lt;/span&gt;
								&lt;/div&gt;
							}
@if(Model.UnitsInStock &gt; 20){
								&lt;div class=&quot;stockLevel stockLevelHigh&quot;&gt;
									&lt;span&gt;Number Of Units In Stock: @Model.UnitsInStock&lt;/span&gt;
								&lt;/div&gt;
							}
&lt;/div&gt;
</pre><p>but there are better ways to achieve our goal.</p><h3 class="subheading">So what are the alternatives?</h3><p>We could:</p><ul><li>Move the logic for choosing the CSS class into a helper method</li><li>Create a method to build the HTML for displaying the number of units in stock</li><li> Use a Product data transfer object with a CSS class name property</li><li> Pass all the CSS classes to a method which will return the CSS class to use</li></ul><p>As I want to concentrate on showing code for Razor view engine, if you want to see the methods, unit tests and discussion about the advantages and disadvantages of each option please refer to the <a
href="<a href="http://www.arrangeactassert.com/asp-net-mvc-view-best-practices-keep-logic-out-of-your-views/">original post</a>.</p><h3 class="subheading">What the view would look like if we used a method to get the CSS class in a Razor view</h3><p>The code below shows how we could achieve the same result by calling a method which returns the CSS class for the number of units in stock.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
@inherits System.Web.Mvc.WebViewPage&lt;KeepLogicOutOfYourRazorViews.Models.Product&gt;
@using KeepLogicOutOfYourRazorViews.Helpers

@{
	View.Title = &quot;Index&quot;;
	LayoutPage = &quot;~/Views/Shared/_Layout.cshtml&quot;;
}

&lt;div class=&quot;example&quot;&gt;
	&lt;div class=&quot;stockLevel @ProductCssHelper.GetCssClassForUnitsInStock(Model.UnitsInStock)&quot;&gt;
		&lt;span&gt;Number Of Units In Stock: @Model.UnitsInStock&lt;/span&gt;
	&lt;/div&gt;
&lt;/div&gt;
</pre><h3 class="subheading">What the view would look like if we passed the CSS classes to a method  in a Razor view</h3><p>Alternatively, a more designer friendly way would be to pass the CSS classes to a method which returns the appropriate CSS class to use for the stock level.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; wrap-lines: true; notranslate">
@inherits System.Web.Mvc.WebViewPage&lt;KeepLogicOutOfYourRazorViews.Models.Product&gt;
@using KeepLogicOutOfYourRazorViews.Helpers

@{
	View.Title = &quot;Index&quot;;
	LayoutPage = &quot;~/Views/Shared/_Layout.cshtml&quot;;
}

&lt;div class=&quot;example&quot;&gt;
	&lt;div class=&quot;stockLevel
		@ProductCssHelper.SelectCssClassForUnitsInStock(
														 Model.UnitsInStock,
														 &quot;stockLevelNone&quot;,
														 &quot;stockLevelLow&quot;,
														 &quot;stockLevelHigh&quot;
													   )&quot;&gt;
		&lt;span&gt;Number Of Units In Stock: @Model.UnitsInStock&lt;/span&gt;
	&lt;/div&gt;
&lt;/div&gt;
</pre><h3 class="subheading">Jag Reehal’s Final Thought on ‘ASP.NET MVC Razor View Best Practices – Keep logic out of your Razor views’</h3><p>Razor does a fantastic job of cleaning up your views, but to keep them even cleaner the best practice to keep logic out of yours view still applies.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/asp-net-mvc-razor-view-best-practices-keep-logic-out-of-your-razor-views/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Creating the animals game using Asp.Net MVC, jQuery and jQueryUI</title><link>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/</link> <comments>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/#comments</comments> <pubDate>Wed, 02 Dec 2009 09:36:50 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery UI]]></category> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=483</guid> <description><![CDATA[A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the ‘Having fun with jQuery UI’ blog post. In this post we will go through how to create the game using ASP.NET MVC, jQuery and jQuery UI. The screenshot below shows the game [...]]]></description> <content:encoded><![CDATA[<p>A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the <a
href="http://www.arrangeactassert.com/having-fun-with-jquery-ui/">‘Having fun with jQuery UI</a>’ blog post.</p><p>In this post we will go through how to create the game using <a
href="http://www.asp.net/mvc/">ASP.NET MVC</a>, <a
href="http://jquery.com/">jQuery</a> and <a
href="http://jqueryui.com/">jQuery UI</a>.</p><p>The screenshot below shows the game running.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ScreenshotOfGameUsingASP.NET-MVC-jQueryAndjQueryUI.png" alt="Screenshot of Game using Asp.Net MVC, jQuery and jQueryUI" /></p><p>The code used for creating the game in ASP.NET MVC, jQuery and jQuery UI can be downloaded <a
href="http://cid-8a29bf85dc9538dc.skydrive.live.com/self.aspx/.Public/GameUsingAspNetMVCandJQueryUI.zip">here</a>.</p><h3 class="subheading">Getting Started</h3><p>Instead of three animals used in the demo, the game now contains fourteen.   I’ve created a repository which returns the animals.  To keep things simple there’s no database here, instead the animals are hard coded.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;

namespace GameUsingAspNetMVCandJQueryUI.Core.Repository
{
    public class AnimalsRepository : IAnimalsRepository
    {
        public IQueryable&lt;Animal&gt; GetAll()
        {
            return new Animal[]
                       {
                           new Animal(){Name = &quot;Cow&quot;},
                           new Animal(){Name = &quot;Cat&quot;},
                           new Animal(){Name = &quot;Chicken&quot;},
                           new Animal(){Name = &quot;Dog&quot;},
                           new Animal(){Name = &quot;Elephant&quot;},
                           new Animal(){Name = &quot;Giraffe&quot;},
                           new Animal(){Name = &quot;Hippo&quot;},
                           new Animal(){Name = &quot;Lion&quot;},
                           new Animal(){Name = &quot;Monkey&quot;},
                           new Animal(){Name = &quot;Mouse&quot;},
                           new Animal(){Name = &quot;Owl&quot;},
                           new Animal(){Name = &quot;Penguin&quot;},
                           new Animal(){Name = &quot;Pig&quot;},
                           new Animal(){Name = &quot;Sheep&quot;},
                       }
                .AsQueryable();
        }
    }
}
</pre><h3 class="subheading">Command Query Separation</h3><p>One of the features I have added is to ensure a correct answer for the current game could not be the correct answer in the next.  As the repository class was responsible for getting animals, having it contain any logic would violate good design principles.</p><p>So the logic goes into the service layer which returns a data transfer object for animals and the correct answer.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.ExtensionMethods;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;

namespace GameUsingAspNetMVCandJQueryUI.Core.Service
{
    public class AnimalsService : IAnimalsService
    {
        private readonly IAnimalsRepository _animalsRepository;

        public AnimalsService(IAnimalsRepository animalsRepository)
        {
            _animalsRepository = animalsRepository;
        }

        public AnimalsDto GetAnimalsForGameWithCorrectAnswer(int numberOfAnimals, string previousAnimal)
        {
            AnimalsDto animalsDto = new AnimalsDto();
            animalsDto.Animals = _animalsRepository
                .GetAll()
                .Where(a =&gt; a.Name != previousAnimal)
                .Shuffle()
                .Take(numberOfAnimals);

            animalsDto.CorrectAnswer = animalsDto.Animals.Shuffle().First().Name;

            return animalsDto;
        }
    }
}
</pre><p>This also makes testing easier because the tests can focus on making sure the service is doing what it should like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;
using GameUsingAspNetMVCandJQueryUI.Core.Service;
using NBehave.Spec.NUnit;
using NUnit.Framework;
using Rhino.Mocks;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class AnimalsServiceTests
    {
        private IAnimalsService _animalsService;
        private IAnimalsRepository _animalsRepository;

        private readonly IQueryable&lt;Animal&gt; _animalsStub = new Animal[]
                           {
                               new Animal(){Name = &quot;Cow&quot;},
                               new Animal(){Name = &quot;Pig&quot;},
                               new Animal(){Name = &quot;Sheep&quot;},
                           }.AsQueryable();

        [SetUp]
        public void SetUp()
        {
            _animalsRepository = MockRepository.GenerateStub&lt;IAnimalsRepository&gt;();
            _animalsService = new AnimalsService(_animalsRepository);
        }

        [Test]
        public void Should_Exclude_Previous_Animal_When_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            var previousAnimal = _animalsStub.First();

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal.Name);

            // Assert
            result.Animals.Count(a =&gt; a.Name == previousAnimal.Name).ShouldEqual(0);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            string previousAnimal = String.Empty;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result..Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Null()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            string previousAnimal = null;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result.Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Correct_Answer_Should_Not_Be_Empty()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);            

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, null);

            // Assert
            result.CorrectAnswer.ShouldNotBeEmpty();
        }
    }
}
</pre><h3 class="subheading">The LINQ Shuffle</h3><p>Even though we have removed the previous answer, if the animals were returned as they are the answer would just be the next one in the list.  So to keep the game exciting, a shuffle extension method is used to shuffle the answers.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;

namespace GameUsingAspNetMVCandJQueryUI
{
    public static class GameExtensions
    {
        public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; items)
        {
            var rnd = new Random();
            IEnumerable&lt;int&gt; numbers = Enumerable.Range(0, items.Count()).OrderBy(r =&gt; rnd.Next());
            var randomItems = new List&lt;T&gt;();
            foreach (int number in numbers)
            {
                randomItems.Add(items.Skip(number).First());
            }
            return randomItems;
        }
    }
}
</pre><p>This can be unit tested as shown below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Collections.Generic;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using NUnit.Framework;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class GameExtensionsTests
    {
        [Test]
        public void Can_Shuffle_Animals()
        {
            List&lt;Animal&gt; animals = new List&lt;Animal&gt;()
                           {
                               new Animal(){Name = &quot;Cow&quot;},
                               new Animal(){Name = &quot;Pig&quot;},
                               new Animal(){Name = &quot;Sheep&quot;},
                           };
            IList&lt;Animal&gt; result = animals.Shuffle().ToList();
            Assert.IsFalse(
                animals[0].Equals(result[0]) &amp;&amp;
                animals[1].Equals(result[1]) &amp;&amp;
                animals[2].Equals(result[2]),
                &quot;Animals should have been shuffled&quot;);
        }
    }
}
</pre><h3 class="subheading">What happens when a player opens the game in their browser?</h3><p>When the page loads an Ajax call is made using jQuery to an Asp.Net MVC action method which returns a JsonResult.</p><pre class="brush: jscript; gutter: false; title: ; toolbar: true; notranslate">
   $.getJSON(&quot;/Game/GetAnimals&quot;,
            { numberOfAnimals: numberOfItemsToGet, previousAnimal: correctAnswer.text() },
            function(data) {
                addItems(data);
                $(&quot;#droppable&quot;).droppable(droppableOptions);
                assignDraggables();
                hideItemsForLevel();
                setUpSlider();
                setTimeout(function() {
                    instructions.text(instructionsText);
                    items.show();
                }, 1000);
            });
</pre><p>Two parameters are passed to the action method, one for the previous answer and the other for the number of animals required.  The reason for this is because we don’t want to transfer more data over the wire than required, why return fourteen animals when only six are required?</p><p>The ‘GetAnimals’ Asp.Net MVC action method shown below serializes the view model returned by the service layer into JSON.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Web.Mvc;
using GameUsingAspNetMVCandJQueryUI.Core.Service;

namespace GameUsingAspNetMVCandJQueryUI.Controllers
{
    [HandleError]
    public class GameController : Controller
    {
        private readonly IAnimalsService _animalsService;

        public GameController(IAnimalsService animalsService)
        {
            _animalsService = animalsService;
        }

        public ActionResult Index()
        {
            return View(&quot;Index&quot;);
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = &quot;*&quot;)]
        public JsonResult GetAnimals(int numberOfAnimals, string previousAnimal)
        {
            return Json(_animalsService.GetAnimalsForGameWithCorrectAnswer(numberOfAnimals,previousAnimal));
        }
    }
}
</pre><blockquote><p>Notice how I have to be explicit about how I do NOT want the JsonResult to be cached.  If you don&#8217;t add this Internet Explorer will cache the result and you will get the same animals.</p></blockquote><h3 class="subheading">Using the jQuery and jQuery UI in the ASP.NET MVC View</h3><p>The JavaScript used the demo was good enough to perform the dragging and dropping of pictures so the good news is we can use it again here.</p><p>An additional feature I have added is to allow the player to change the difficulty of the game by choosing how many animals are shown on the screen.</p><p>To do this I used the jQuery UI slider and jQuery fade functionality.  The reason I used fade rather show/hide in jQuery was because I didn’t want the animals to move position when a user changed the difficulty as this would have resulted in a poor user experience by confusing the player.</p><p>Currently the message which tells the player if they have selected an incorrect answer is shown when the user stops dragging the animal.  This is a problem because if the user drags a correct animal but doesn’t drop it on the droppable a message isn’t shown.  If I find a fix for this I’ll update the code and this post.</p><h3 class="subheading">Jag Reehal’s Final Thought on ‘Creating the animals game using Asp.Net MVC, jQuery and jQueryUI’</h3><p>I’ve been using jQuery for a while now and I still love it.</p><p>The jQuery UI library is very good and the <a
href="http://jqueryui.com/about">jQuery UI team</a> have done a fantastic job creating demos and documentation.</p><p>I really like how you can create your own custom javascript file which only contains the features you require from the library.</p><p>No doubt some people will question why the service is returning a data transfer object.  I could have returned a collection of animals to the ASP.NET MVC controller and have it create an object to pass to the view.  The reason I didn’t do this is because I know the data transfer object will be used by another user interface layer (Silverlight) and because this would have bloated the controller and that’s not good.  A <a
href="http://www.arrangeactassert.com/asp-net-mvc-controller-best-practices-%E2%80%93-skinny-controllers/">best practice for ASP.NET MVC is to have skinny controllers</a>.</p><p>The images for the animals used in the game are from <a
href="http://www.openclipart.org">http://www.openclipart.org</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> </channel> </rss>
<!-- Served from: www.arrangeactassert.com @ 2012-02-05 23:31:47 by W3 Total Cache -->
