<?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; jQuery UI</title> <atom:link href="http://www.arrangeactassert.com/category/jquery-ui/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>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> <item><title>Having fun with jQuery UI</title><link>http://www.arrangeactassert.com/having-fun-with-jquery-ui/</link> <comments>http://www.arrangeactassert.com/having-fun-with-jquery-ui/#comments</comments> <pubDate>Tue, 10 Nov 2009 23:32:30 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery UI]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=412</guid> <description><![CDATA[As my nephew is coming round to visit in a couple of weeks, I want to create a game he could play. The aim of the game is to match pictures to a word. The demo shown below uses the jQuery UI library which makes the dragging and dropping possible. If you want to know [...]]]></description> <content:encoded><![CDATA[<p>As my nephew is coming round to visit in a couple of weeks, I want to create a game he could play.</p><p>The aim of the game is to match pictures to a word.  The demo shown below uses the <a
href="http://jqueryui.com/home">jQuery UI</a> library which makes the dragging and dropping possible.  If you want to know more check out the excellent <a
href="http://jqueryui.com/demos/draggable/">draggable</a> and <a
href="http://jqueryui.com/demos/droppable/">droppable</a> demos.<br
/> <em><br
/> As this is just a demo the animals are hard coded so if you hit play again you will see the same animals.</em><br
/><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><br
/><script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"></script><br
/><script src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/gameScript.js" type="text/javascript"></script></p><link
href="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/gameStyles.css" rel="stylesheet" type="text/css" /><div
id="gameContainer"><div
id="gameTitle">Can you match the picture to the word?</div><p
id="instructions">Drag the picture to the box on the right</p><div
id="items"> <img
class="draggable correct" id="Cow" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/cow.png" /><br
/> <img
class="draggable" id="Pig" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/pig.png" /><br
/> <img
class="draggable" id="Sheep" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/sheep.png" /></div><div
id="droppable"><p
id="itemName">Cow</p></p></div><div
id="results"><div
id="correctResult"> <input
id="playAgain" type="button" value="Click here to play again"/></div><div
id="incorrectResult"></div></p></div></div><p><br/><br
/> The demo uses the <a
href="http://jquery.com/">jQuery</a> and <a
href="http://jqueryui.com/home">jQuery UI</a> libraries (hosted by Google) and the javascript shown below</p><pre class="brush: jscript; gutter: false; title: ; toolbar: true; notranslate">
$(function() {
    var result = $('#incorrectResult');
    var correctResult = $('#correctResult');

    $(&quot;.draggable&quot;).draggable({
        containment: '#gameContainer',
        revert: 'invalid',
        start: function(event, ui) {
            result.fadeOut(1000);
        },
        stop: function(event, ui) {
            if (!$(this).hasClass('correct')) {
                result.html(&quot;Try again that's a &quot; + $(this).attr(&quot;id&quot;));
                result.fadeIn(1000);
            }
        }
    });

    $(&quot;#droppable&quot;).droppable({
        accept: '.correct',
        drop: function(event, ui) {
            $(&quot;.draggable&quot;).draggable('disable');
            correctResult.fadeIn(1000);
            correctResult.prepend('Well done! You found the ' + ui.draggable.attr('id') + ' ');
        }
    });

    $(&quot;#playAgain&quot;).click(function() {
        location.reload(true);
    });
});
</pre><p>The html used to create the game looks like this</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;div id=&quot;gameContainer&quot;&gt;
    &lt;div id=&quot;gameTitle&quot;&gt;Can you match the picture to the word?&lt;/div&gt;
    &lt;p id=&quot;instructions&quot;&gt;Drag the picture to the box on the right&lt;/p&gt;
    &lt;div id=&quot;items&quot;&gt;
        &lt;img class=&quot;draggable correct&quot; id=&quot;Cow&quot; src=&quot;http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/cow.png&quot; /&gt;&lt;br /&gt;
        &lt;img class=&quot;draggable&quot; id=&quot;Pig&quot; src=&quot;http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/pig.png&quot; /&gt;&lt;br /&gt;
        &lt;img class=&quot;draggable&quot; id=&quot;Sheep&quot; src=&quot;http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/sheep.png&quot; /&gt;
    &lt;/div&gt;
    &lt;div id=&quot;droppable&quot;&gt;
        &lt;p id=&quot;itemName&quot;&gt;Cow&lt;/p&gt;
    &lt;/div&gt;
    &lt;div id=&quot;results&quot;&gt;
        &lt;div id=&quot;correctResult&quot;&gt;
            &lt;input id=&quot;playAgain&quot; type=&quot;button&quot; value=&quot;Click here to play again&quot; /&gt;
        &lt;/div&gt;
        &lt;div id=&quot;incorrectResult&quot; /&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre><p><em>Yes the html and javascript won’t win any awards, the fact it works in a blog post is good enough for me <img
src='http://www.arrangeactassert.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </em></p><h3 class="subheading">What’s next?</h3><p>To begin with I will create a version of the game using ASP.NET MVC, jQuery and jQuery UI.  This will look like demo shown in this post with additional functionality to randomise the pictures.</p><p>Then I will create a version of the game using Silverlight.</p><p>Once this is complete I will refactor both solutions to share as much code as possible.  I’m assuming <a
href="http://code.msdn.microsoft.com/RiaServices">RIA services</a> is the tool of choice but we will see.</p><p>After that maybe (way in the future) I might attempt to write this game for the Android platform and take advantage of touch screen mobile phones.  I have never developed an application before so this should be an interesting challenge.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/having-fun-with-jquery-ui/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Served from: www.arrangeactassert.com @ 2012-02-05 23:29:00 by W3 Total Cache -->
