devLink 2014: Presentation Materials

Super stoked to present at devLink this year. I’m trying to get with the times and provide my materials before hand so you can get your hands on them before you forget about them. You can find everything from my slide deck to code in my GitHub repos.

Crawl Walk Talk – Windows Phone App Lifecycle and Cortana API

Repo: CrawlWalkTalk

Master Windows 8.1 Location and Proximity Capabilities

Repo: WindowsLocationAndProximity

For those that see this before I hope you attend, and for all those that attend thank you so much for coming and please let me know what you thought of the presentation and materials. I’m always trying to improve. For those that find these materials after the presentation please check them out and let me know if I can answer any questions you may have!

MVC Series Part 2: AccountController Testing

Introduction

Click here to download code and sample project

In my first post of the series, I explained the perils and pitfalls that I had to overcome with dynamically adding items. One of the next problem I ran into was dealing with unit testing the AccountController. More specifically, attempting to represent the UserManager class. Since unit testing is a fundamental necessity for any server project, testing the controller was a necessity.

Attempting to Test

So, let’s first create a test class for the AccountController and include a simple test for determining if a user was registered. Here is how my class first appeared:

[TestClass]
public class AccountControllerTest
{
	[TestMethod]
	public void AccountController_Register_UserRegistered()
	{
		var accountController = new AccountController();
		var registerViewModel = new RegisterViewModel
		{
			Email = "test@test.com",
			Password = "123456"
		};

		var result = accountController.Register(registerViewModel).Result;
		Assert.IsTrue(result is RedirectToRouteResult);
		Assert.IsTrue( _accountController.ModelState.All(kvp => kvp.Key != "") );
	}
}

When running the unit test I get a NullReferenceException thrown when attempting to access the UserManager. At first I assumed this was due to not having a UserManager created, but debugging at the location of the thrown exception led me to this:

ApplicationUserManager UserManager
{
     get
     {
          return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
     }
     private set
     {
          _userManager = value;
     }
}

The exception is actually getting thrown on the HttpContext property that is part of ASP.Net internals. We cannot assign HttpContext directly on a controller since it is read-only, but the ControllerContext on it is not, which explains how to do that here. We can create this easily enough by installing the Moq NuGet package to help mock this out. We will install the package and place the initialization of our AccountController into a initialize test class that will get called prior to every unit test:

private AccountController _acocuntController;

[TestInitialize]
public void Initialization()
{
     var request = new Mock<HttpRequestBase>();
     request.Expect( r => r.HttpMethod ).Returns( "GET" );
     var mockHttpContext = new Mock<HttpContextBase>();
     mockHttpContext.Expect( c => c.Request ).Returns( request.Object );
     var mockControllerContext = new ControllerContext( mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object );

     _acocuntController = new AccountController
     {
          ControllerContext = mockControllerContext
     };
}

Now when we run our application we no longer have to worry about the HttpContext, but still there is another NullReferenceException being thrown. This time it is from the call to ‘GetOwinContext’.

Alternative Route

At this point, attempting to mock out all of HttpContext’s features seems like a never ending road. All we really want is the ability to use UserManager’s feature to register a user. In order for us to do that we will need to mock out the IAuthenticationManager. This is no easy feat considering how well embedded the UserManager is within the AccountController. Fortunately, a post mentioned here mentions the right direction for substituting the ApplicationUserManager.

What we want to do is create a new class, called AccountManager, that will act as an access to the UserManager. The AccountManager will take in an IAuthenticationManager and also a IdentityDbContext, in casewe need to specify the specific context. I decided to place this class in a separate library that both the MVC and unit test libraries can access. If you decide to do the same and copy the class from the sample project, most of the dependencies will get resolved except for the HttpContextBase extension ‘GetOwinContext’. The reason is because that extension needs Microsoft.Owin.Host.SystemWeb. You can simply install this dependency in your library as a Nuget package through this command:

  • Install-Package Microsoft.Owin.Host.SystemWeb

Now that we have our AccountManager, we need to make sure our AccountController will use this class rather than attempting to create the UserManager from HttpContext. This starts with the constructor, where now we will have it accept our manager rather than passing in a UserManager:

public AccountController( AccountManager<ApplicationUserManager, ApplicationDbContext, ApplicationUser> manager)
{
	_manager = manager;
}

Then we will change the access to AccountController.UserManager to use the AccountManager:

public ApplicationUserManager UserManager
{
	get
	{
		return _manager.UserManager;
	}
}

Dependency Injection

Now the immediate problem with this is that MVC’s controllers are stateless and handle the creation of all the classes, including any objects that are injected into the class. Fortunately, Unity has dependency injection specifically for MVC that will allow us to inject our own objects. As of this writing, I went ahead and installed Unity’s MVC 5, which is referenced here. It’s a very seamless process to integrate Unity into your MVC project. After installing the package, open the Global.asax.cs, where your Application_Start() method is stored and add in ‘UnityConfig.RegisterComponents();’. Afterwards, in the App_Start folder, open the UnityConfig.cs file and register our AccountManager:

container.RegisterType<AccountManager<ApplicationUserManager, ApplicationDbContext, ApplicationUser>>(new InjectionConstructor());

We will also need to override our initialization process for the AccountController to ensure the AccountManager either gets the embedded HttpContext from the AccountController or one we provide during test:

protected override void Initialize( RequestContext requestContext )
{
	base.Initialize( requestContext );
	_manager.Initialize( HttpContext );
}

We will also need to remove the references to AuthenticationManager and instead have our AccountController reference the AccountManager’s AuthenticationManager. This will also cause our SignInAsync method to this:

private async Task SignInAsync( ApplicationUser user, bool isPersistent )
{
	await _manager.SignInAsync( user, isPersistent );
}

Mocking AccountController

Now we can run our application and register a user using our AccountManager. With this implementation in place, we simply need to mock out our IAuthenticationManager. Here is a post that describes a bit of the process. So, following suit, we go ahead and mock out the necessary classes for initializing up our test AccountController, all under the same Initialization class:

private AccountController _accountController;

[TestInitialize]
public void Initialization()
{
	// mocking HttpContext
	var request = new Mock<HttpRequestBase>();
	request.Expect( r => r.HttpMethod ).Returns( "GET" );
	var mockHttpContext = new Mock<HttpContextBase>();
	mockHttpContext.Expect( c => c.Request ).Returns( request.Object );
	var mockControllerContext = new ControllerContext( mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object );

	// mocking IAuthenticationManager
	var authDbContext = new ApplicationDbContext();
	var mockAuthenticationManager = new Mock<IAuthenticationManager>();
	mockAuthenticationManager.Setup( am => am.SignOut() );
	mockAuthenticationManager.Setup( am => am.SignIn() );

	var mockUrl = new Mock<UrlHelper>();

        var manager = new AccountManager<ApplicationUserManager, ApplicationDbContext, ApplicationUser>( authDbContext, mockAuthenticationManager.Object );
	_accountController = new AccountController( manager )
	{
		Url = mockUrl.Object,
		ControllerContext = mockControllerContext
	};

	// using our mocked HttpContext
	_accountController.AccountManager.Initialize( _accountController.HttpContext );
}

Now we can effectively test our AccountController’s logic. It’s unfortunate this process was anything but straight forward, but at least we are able to have better unit test code coverage over our project.

MVC Series Part 1: Dynamically Adding Items Part 3

Collections named with same substring in a Dynamic Item

Click here to download code and sample project

In the second part of the series, I discussed how to include a collection inside a dynamic item. Here is one gotcha that I ran into during development. Let’s say we decide to add a Publisher for every new book and you want the ability to add a few books the publisher has distributed. Here is the PublisherViewModel class I created:

public class PublisherViewModel
	{
		public PublisherViewModel()
		{
			Books = new List<PublisherBookViewModel>();
			for ( int i = 0; i < 3; i++ )
			{
				Books.Add( new PublisherBookViewModel() );
			}
		}
		public string Name { get; set; }

		public IList<PublisherBookViewModel> Books { get; set; }
	}

Here is how the html would look for PublisherViewModel:

<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor( model => @Model.Name )
    </dt>
    <dd>
        @Html.EditorFor( model => @Model.Name )
    </dd>
    <br />

    <dt>
        @Html.DisplayNameFor( model => @Model.Books )
    </dt>
    <dd>
        @for ( int i = 0; i < @Model.Books.Count(); i++ )
        {
            @Html.EditorFor( model => @Model.Books[i] )
        }
    </dd>
</dl>

I went ahead and created a new class for the books collection called PublisherBookViewModel. It simply contains one property for Name. Here is how the Html looks:

@using ( Html.BeginCollectionItem( "Books" ) )
{
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor( model => @Model.Name )
        </dt>
        <dd>
            @Html.EditorFor( model => @Model.Name )
        </dd>
    </dl>
}

But when I go to create one new Book and post back, I actually end up receiving 4 items in my ‘NewBooks’ collection. How did this even happen?

Well, the reason this occurred is again thanks to our BeginCollectionItem HtmlHelper class. The extra logic that we added in the last article seems to merely grab the first occurrence of our collection name:

collectionName = htmlFieldPrefix.Substring( 0, htmlFieldPrefix.IndexOf( collectionName ) + collectionName.Length );

If we look at what the HtmlFieldPrefix string looks like coming in we can start to spot the problem:

"NewBooks[18fe8281-9b41-43ff-bcc9-a14ce3e99dc8].Publisher.Books[0]"

So, our parent dynamic item is being bounded to a collection called ‘NewBooks’, but the PublisherViewViewModel has its own collection of items called ‘Books’. Our Substring method needs to be a little bit smarter by replacing ‘IndexOf’ with ‘LastIndexOf’. And with that, we will no longer have issues with sub collection binding.

This is as far as I took with dynamically adding items in MVC, but at some point it would be nice to be able to add dynamic items to a dynamic item (i.e., instead of pre-populating our Characters collection, we let the user add as many as they need). Perhaps another day I will delve into this.

MVC Series Part 1: Dynamically Adding Items Part 2

Collections in a Dynamic Item

Click here to download code and sample project

In the first part of the series, I discussed how to add items dynamically. So, why don’t we expand on our idea and let’s say we want to add the ability to include another collection into our original dynamic item. We will expand our BookViewModel editor template to include a collection of 5 story Characters a user can insert:

<dl id="booksContainer">
        @foreach ( var classicBook in @Model.ClassicBooks )
        {
            <dl>
                <dt>
                    @Html.DisplayNameFor( model => classicBook.Title )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Title )
                </dd>

                <dt>
                    @Html.DisplayNameFor( model => classicBook.Author )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Author )
                </dd>
            </dl>
        }
</dl>

And we included a CharacterViewModel editor template that only includes the ability to insert first and last name. But when you attempt to add a book with a characters we run into the same problem originally where the new Characters are not binding correctly. The reason this exists is because our HtmlHelper is not able to uniquely identify sub items inside a recently dynamically added item. Makes sense?

No? Well, let’s discuss first what the BeginCollectionItem Html helper generates when injected into the Html element. Here is the BookViewModel’s partial view for the title:

<dt>
    @Html.DisplayNameFor( model => @Model.Title )
</dt>
<dd>
    @Html.EditorFor( model => @Model.Title )
</dd>

And here is the output that actually gets injected into the Html element after passing through the Html helper:

<dt>
    Title
</dt>
<dd>
    <input class="text-box single-line"
           id="NewBooks_3ad36db7-7685-4c8e-aadd-a2309f65e858__Title"
           name="NewBooks[3ad36db7-7685-4c8e-aadd-a2309f65e858].Title"
           type="text" value="" />
</dd>

Here you can see how the Html helper is inserting a Guid into the id and name fields so MVC can uniquely identify the property back to the item. But if we use the same comparison for Character, here is the partial view for name:

<dt>
    FirstName
</dt>
<dd>
    <input class="text-box single-line"
           id="Characters_dd611290-f64b-4b1a-9add-bad035f7b94f__FirstName"
           name="Characters[dd611290-f64b-4b1a-9add-bad035f7b94f].FirstName"
           type="text" value="" />
</dd>
<dt>
    LastName
</dt>
<dd>
    <input class="text-box single-line"
           id="Characters_dd611290-f64b-4b1a-9add-bad035f7b94f__LastName"
           name="Characters[dd611290-f64b-4b1a-9add-bad035f7b94f].LastName"
           type="text" value="" />
</dd>

Although the character model is correctly getting a Guid assigned, there is no way for MVC to know that CharacterViewModel belongs to a NewBooks sub item. In order to solve this, we need to delve into our BeginCollectionItem Html helper and make sure it retains the ‘NewBooks’ guid. This is quite straightforward if we do a comparison on the incoming collection name:

var htmlFieldPrefix = html.ViewData.TemplateInfo.HtmlFieldPrefix;
if ( htmlFieldPrefix.Contains( collectionName ) )
{
        collectionName = htmlFieldPrefix.Substring( 0, htmlFieldPrefix.IndexOf( collectionName ) + collectionName.Length );
}

And let’s take a look again at our injected output:

<dt>
     FirstName
</dt>
<dd>
    <input class="text-box single-line"
           id="NewBooks_1a95a483-e5c7-4696-ac91-bd9f0563b83b__Characters_e3e949f5-aae7-44cd-9aa8-419658c25e75__FirstName"
           name="NewBooks[1a95a483-e5c7-4696-ac91-bd9f0563b83b].Characters[e3e949f5-aae7-44cd-9aa8-419658c25e75].FirstName"
           type="text" value="" />
</dd>
<dt>
    LastName
</dt>
<dd>
    <input class="text-box single-line"
           id="NewBooks_1a95a483-e5c7-4696-ac91-bd9f0563b83b__Characters_e3e949f5-aae7-44cd-9aa8-419658c25e75__LastName"
           name="NewBooks[1a95a483-e5c7-4696-ac91-bd9f0563b83b].Characters[e3e949f5-aae7-44cd-9aa8-419658c25e75].LastName"
           type="text" value="" />
</dd>

Now our character items will get posted back onto our dynamic item.

MVC Series Part 1: Dynamically Adding Items Part 1

Introduction

Recently, I have been exposed to working on a project using ASP.NET MVC 5. My experience working with MVC for the first time was overall positive, but it did run into quite a few hair pulling scenarios. My background up to this point primarily dealt with C# WPF applications, but with a little bit of web development on the side.  In this series, I will discuss some of the major issues that led to many sleepless nights working on this project. And although these scenarios may not seem to be the most difficult to an experienced MVC developer, these are the problems that caused major hiccups to a first timer like myself.

Dynamically Adding Items

Click here to download code and sample project

In one of the first major issues I needed to attempt to solve was trying to add items dynamically to a View. Representing a collection already populated is fairly straight forward using MVC’s Razor, as represented here in my collection of classical books:

<dl class="dl-horizontal" id="booksContainer">
        @foreach ( var classicBook in @Model.ClassicBooks )
        {
            <dl class="dl-horizontal">
                <dt>
                    @Html.DisplayNameFor( model => classicBook.Title )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Title )
                </dd>

                <dt>
                    @Html.DisplayNameFor( model => classicBook.Author )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Author )
                </dd>
            </dl>
        }
</dl>

We can even go one step further and place this inside a ‘DisplayTemplate’ and push the display content into a partial view:
dynamic img 1

<dl class="dl-horizontal" id="booksContainer">
        @foreach ( var classicBook in @Model.ClassicBooks )
        {
            @Html.DisplayFor(model => classicBook);
        }
</dl>

But how do we add content on the fly?

Well, we could have a button that inserts javascript into our ‘booksContainer’ element and this would provide a seamless experience for the user. But what if we decide to change how the view looks? And how could we get this to post back to MVC server? What about if we decided to take in an image file as well?

Given I did not want to update the view in two places, I managed to find a solution that managed to do all of the above, linked here.

In summary, I was able to use an ajax call to retrieve my BookViewModel’s partial html view from the server and inject it into an html element:

  • Adding an editor partial view for the BookViewModel

dynamic img2

  • Including the html element that will take in new books:
    <div id="newBooks">
        @for ( int i = 0; i < @Model.NewBooks.Count(); i++ )
    
        {
    
            @Html.EditorFor( model => @Model.NewBooks[i] )
    
        }
    
    </div>
  • On the server, the HomeController’s method that simply returns my partial view:
    public ActionResult CreateNewBook()
    {
    
        var bookViewModel = new BookViewModel();
    
        return PartialView( "~/Views/Shared/EditorTemplates/BookViewModel.cshtml", bookViewModel );
    
    }
    
    
  • The ajax call that handles the add book button click and injects the returned partial view:
    @section Scripts {
        <script type="text/javascript">
    
            $("#addbook").on('click', function () {
    
                $.ajax({
                    async: false,
                    url: '/Home/CreateNewBook'
                }).success(function (partialView) {
    
                    $('#newBooks').append(partialView);
    
                });
            });
    
        </script>
    }
    

And now we can dynamically add items on button click! The user is able to add as many books as they want, click submit, and the collection of books will get received on HttpPost. But, when we put a break post on our post method, the NewBooks collection comes back as empty. Why is this happening?

Well the reason is because MVC can only bind back a collection of items if it can uniquely identify each one. This article actually describes how you can get a collection of items to bind appropriately on post back, linked here.

Unfortunately, this does not apply when items are getting added dynamically. Luckily, the previous article also solved this problem by creating a Html Helper class, BeginCollectionItem, that adds a unique identifier to every new inserted item. All we need to do is modify our BookViewModel editor template to include it:

@using ( Html.BeginCollectionItem( "NewBooks" ) )
{
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor( model => @Model.Title )
        </dt>
        <dd>
            @Html.EditorFor( model => @Model.Title )
        </dd>

        <dt>
            @Html.DisplayNameFor( model => @Model.Author )
        </dt>
        <dd>
            @Html.EditorFor( model => @Model.Author )
        </dd>

        <dt>
            @Html.DisplayName( "Book Cover File Image" )
        </dt>
        <dd>
            @Html.TextBoxFor( m => @Model.BookCoverUrl, null, new { type = "file", @class = "input-file" } )
        </dd>

    </dl>
}

And with that we can now dynamically add items and they will uniquely get posted back onto the server.

Presentation: Crawl Walk Talk – App Lifecycle and Voice API for Windows Phone

Talk about technical difficulties! Major props to the vNext crew for sticking through my crazy tech issues. For those of you who couldn’t make it VS wouldn’t open any files. It would load the project, but if I tried to open a .xaml file VS crashed. I had installed VS 2013 Update 2 the night before thinking it would fix a code issue for me. Instead it created a nightmare! And then Cortana and I got into a fight. A little reboot fixed her right up. Overall I had fun despite the difficulties. Thanks again to all who attended!

Materials

I’m starting a new practice with this presentation. I’m using GitHub to host ALL of my materials: Code and Deck! I hope that works out better than having to download .zip files. Plus this way you can submit Pull Requests for bugs you see during my presentations. ;-) But seriously, I hope it makes it easier for you to access and for me to update! See link below:

Off to #WPC2014….and to see what Microsoft has in store for its own vNext!

As I finish packing for an exciting week in D.C. at #WPC2014 I am looking forward to the energy and possibilities that Satya Nadella expressed in his email to all Microsoft employees the morning of July 10th.  I have been asked by several people about my reaction….and honestly, I loved it – especially the part about the culture. I love the energy, challenges posed, and notion of change and accountability. All throughout I was thinking “insert InterKnowlogy here” and apply it to our own company. LOVED it. I am looking forward to hearing more along these lines at WPC this week in the keynote messaging. The time for change, a focus on the core that makes the company strongest, and a challenge to its people to drive the best possible services and products to its customers is a mantra that every company should live by.

Personally, I am excited about the vNext environment for Microsoft. I think it has needed both revitalization and accountability shifts for a long time – meaningful ones, not just ‘cut your bottom 10%, regardless’. There are some amazing people distributed across the many teams, products and continents that Microsoft covers. Inspiring, really, that the entire world has access to their products and services. This next wave is set to expand that coverage, building upon the strength of the deployments to date, and creating opportunities where they have not been taken in the past.  Again, there is alignment with that which we hope to accomplish at InterKnowlogy – continuing to expand our team with the best and the brightest, building incredible software solutions and diversifying our client base around the globe.

I would love the chance to meet Satya in person – hoping that his in-person energy is as inspiring as the words on paper. I can only hope to inspire others in the same way in the future – bring on the energy and a fantastic and highly energetic and positive wave of updates to IK!  We certainly have the team to do so, and look forward to adding more to help accomplish our bold goals, and celebrate them along the way!

Here’s to a fantastic week at WPC filled with old friends and new, great announcements, press events, new partnerships and late night events!!

Javascript Handlebars Templates With Custom Helpers

Last time, I talked about Handlebars with Partials and before that it was Basic Handlebars Templates, so now I think it is time to talk about custom helper methods and what they allow us to do. If you have used Handlebars and have used the notation “#each” you have used a helper. Handlebars also lets us create our own Helper Methods, so we can make #DoMyCustomWork. I should also note that any Helper that uses the ‘#’ notation, needs to have the closing ‘/’ notation. For example, the built in “{{#if}}” needs to be closed with a “{{/if}}”.

I am going to build on my project from the last post in which I was using sport team information.

This time, I want to display the NHL teams sorted on the major segmentation, or conference, and the minor segmentation, or division. Basically, NHL teams are in a Division, and each Division belongs to a Conference and I want my list to reflect that.

Since I want to sort the teams based on Conference and Division, I feel like I should look at the most general split, or by conference. To do this I need something that will look at my data and only act on the teams that I want at the moment. It would be logical to think that one option would be to iterate through all the teams and use the built in #if helper. And if you thought that, you are wrong.
The #if only tests for True or “Falsey” values. Yes, “Falsey”. The #if helper checks if the value is “null”, “undefined”, and yes even “false”. A quick example: lets say I have data for a sports league, but the data on individual teams is empty, I can for example “{{#if teams}}” in a template, which will allow me to show the team data if is is there. Next I can put “{{else}}”, and put an error message saying “Team data not provided.”

Enough of that tangent. I want a custom helper that gives me all the teams of a certain NHL Conference. To do this I feel like I should make my helper as generic as possible because this time I want conference, but next time it might be divisions, or team color, or team location. So I want my helper to accept my collection, the property I want to search, and the value that I want to match on. With that criteria, this is what I came up with.

        Handlebars.registerHelper("where", function (collection, property, value, options) {
            var subset = [];

            for (var teamIndex in collection) {
                var team = collection[teamIndex];

                if (team[property] !== undefined && team[property].toLowerCase() === value.toLowerCase()) {
                    subset.push(team);
                }
            }

            return options.fn(subset);
        });

I put this snippet in a “registerHelpers()” function that lives in an object dedicated to Handlebars. But lets dive into the specifics a bit. What I am doing it telling Handlebars that I want to register a helper named “where,” which is a function that takes in 4 parameters: collection, property, value, and options. The first three I explained before. The last one, options, seems like an anomaly. In fact, options is a handlebars construct and that allows me to pass data from the JavaScript back to the template. Once in the function it’s just a basic JS function to iterate through my collection and compare the values, saving off the ones I want. After that has completed I give my subset back to the template by returning the subset through “options.fn().” Again, that is just how handlebars works.

To call this, I simply put :

{{#where <collection> <propertyToSearchOn> <valueToMatch> }}
1
in my template. The stuff in <> are placeholders for the actual values.
For my structure the actual line to call my helper is:
1
{{#where teams "conference" "west" }}

I should also point out that using #where, returns an object and shifts my context. That means using "{{#each teams}}" like in my previous post will no longer work. The object I have when I get to that point is not the same object as I had before. Have no fear, because #where returns just the object I am looking for in an array, I can just change the line of code to be "{{#each this}}." What I am saying there is "for each object in the collection" do whatever is in the each block.

So when I modify my template to use the #where helper

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
        {{#each leagues}}
        <div id="league-accordion" class="panel-group">
            <div class="league-header">
                <h1>{{{name}}} ({{acronym}})</h1>
            </div>

            <h3>Founded {{{founded}}}</h3>
            <div class="panel panel-default">
                {{#where teams "conference" "west" }}
                {{#each this}}
                <div class="conferenceDiv">
                    {{> teamTemplate}}
                </div>
                {{/each}}
                {{/where}}
            </div>
        </div>
        {{/each}}
    </div>
</script>

and run it, I get a list of the teams that have "West" listed as their conference.

The eagle eyed may have noticed that now I only have half my data. I am only showing teams in the West. How can I show teams for both Conferences? Well, I could simply duplicate my #where block and change the string to "east," but what is the fun in that, and I would be duplicating code. What I could do instead is look at my data then iterate the proper number of times.

I will do my best to make this more brief. I want to look at my data see how many Conferences I have in the NHL. Something like a Distinct call to a database. So I made a helper I call, "Distinct." It looks like this:

        Handlebars.registerHelper("distinct", function (listOfObjects, property, options) {
            var unique = {};
            var distinctList = [];

            for (var objectIndex in listOfObjects) {
                var object = listOfObjects[objectIndex];

                if (typeof (unique[object[property]]) == "undefined") {
                    distinctList.push(object[property]);
                }

                unique[object[property]] = 0;
            }

            return options.fn(distinctList);
        });

I call it like this:

{{#distinct teams "conference"}}

Then my full template turns into this:

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
        {{#each leagues}}
        <div id="league-accordion" class="panel-group">
            <div class="league-header">
                <h1>{{{name}}} ({{acronym}})</h1>
            </div>

            <h3>Founded {{{founded}}}</h3>

            {{#distinct teams "conference"}}
            {{#each this}}
            <div class="conferenceDiv">
                <h2>{{this}}</h2>
            </div>
            {{#where ../../teams "conference" this }}
            {{#each this}}
            <div class="conferenceDiv">
                {{> teamTemplate}}
            </div>
            {{/each}}
            {{/where}}

            {{/each}}
            {{/distinct}}
        </div>
        {{/each}}
    </div>
</script>

And now I get both the NHL conferences.

To get to the division level, I do a very similar pattern.
-Get the distinct divisions
-Grab the teams from those division
-Plop them in the DOM

If you want to see this, grab my project.

That explains helpers for Handlebars.

My project (again): Handlebars Sample

JavaScript Handlebars Templates with Partials

Intro
In a previous blog post I provided the basics for creating an HTML template using the handlebars JavaScript library. In that post, I stuck to a very basic template. This time I will kick it up a notch and cover partials. You might be asking “What do I need partials for?” and you asking gives me a way to start explaining. So thanks for asking.

Let’s say you are making several templates from some data that is similar, but not identical. For example, sports leagues. Sports leagues are very similar in how they are composed, but not always identical. Some leagues call the major split conferences others call them leagues. Inside of a league there might be divisions; who knows. But at some point, we get to a level where it’s a single team, and we want all teams to have the same visual representation. This is where the handlebars partial comes in to play. I can make a team template, and use it any other template I want. All I have to do is register that partial with the handlebars library, then reference the partial in my template, and BOOM!, I have the same look across all sports leagues, conferences, divisions, whatever.

For now, I am focusing on one league (the NHL), so each team object has the name of the team, the location, the conference, and the division. I want each team to have the same look, so I am going to make a team template.

<script id="team-template" type="text/x-handlebars-template">
    <div class="teamDiv">
        <h3>
            {{location}} {{name}}
        </h3>
    </div>
</script>

Yes, that template is pretty basic and, for the moment, could go in line with the rest of my template, but if later on I make the template more complex, or I change to have the teams separated out by the conference/division, or I add more sports, I might end up with duplicated code.

Now that I have made my partial, it needs to be registered before it can be used. That is easy to do, and looks like this:

Handlebars.registerPartial("teamTemplate", $("#team-template").html());

Finally, once I have told the Handlebars engine about the template, I can use that partial in other templates. That notation looks like this:

{{> teamTemplate}}

Anywhere that appears in a handlebars script, my partial will be used.

My full template looks like so:

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
        {{#each leagues}}
        <div id="league-accordion" class="panel-group">
            <div class="league-header">
                <h1>{{{name}}} ({{acronym}})</h1>
            </div>

            <h3>Founded {{{founded}}}</h3>
            <div class="panel panel-default">
                {{#each teams}}
                {{> teamTemplate}}
                {{/each}}
            </div>
        </div>
        {{/each}}
    </div>
</script>

When I combine all that with my data, I get something like:

<div id="league-accordion" class="panel-group">
    <div class="league-header">
        <h1>National Hockey League (NHL)</h1>
    </div>
    <h3>Founded 1917</h3>
    <div class="panel panel-default">
    <div class="teamDiv">
        <h3>
            Colorado Avalanche
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Chicago Blackhawks
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Columbus Blue Jackets
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            St. Louis Blues
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Boston Bruins
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Montreal Canadians
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Vancouver Canucks
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Washington Capitals
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            Phoenix Coyotes
        </h3>
    </div>
    <div class="teamDiv">
        <h3>
            New Jersey Devils
        </h3>
    </div>
          ...      
    </div>
</div>

The power of this becomes more obvious as I try to sort my data with the user helpers…..in my next blog.

Review: Dave Fancher’s “The Book of F#”

This book is fantastic! I had little F# experience going into this book and found the basics of the language easy to understand and fun to read. Dave does an excellent job explaining F# from syntax, types, and its functional nature all the way through complex topics like quoted expressions and asynchronous programming. The occasional Dr. Who reference is sure to catch the eye in his exciting code samples. As a C# developer I really appreciated Dave’s chapter that focused on comparing F#’s APIs to C#’s. I feel confident in adding F# to any of my pre-existing C# projects right away. One thing that I found very intriguing was Dave’s focus on using F# for regular application development not just math! F# is not just a niche language for the scientific world, but is a way to help develop extremely testable and reliable code in everyday applications.

I highly recommend Dave Fancher’s “The Book of F#” to every .NET developer. Even if the developer does not adopt F# the lessons taught by the language are invaluable and will make them a better .NET developer in whichever language they use.