Unit Testing ASP.NET WebAPI Controllers

Having just written some ASP.NET WebAPI controllers I then needed to accomplish the task of creating Unit Tests for them.  The tests would need to accomplish model validation via DataAnnotation and Json.NET attributes, authentication for all HTTP methods except GET (did I mention IIS was involved here) and in the process exercise an underlying SQL data layer (see UNIT TESTING USING LOCALDB).  I also wanted to write as few Unit Tests as possible and limit mocking but still exercise the whole pipeline.

Some URLs that helped me immensely were:

Some very important things I wanted to accomplish were:

  • Exercise the complete pipeline but without the use of IIS (in any flavor) and without SQLServer (although I guess you could argue that LocalDB is a version of SQLServer)
  • Write the unit tests using code similar to what I would be using in Production code.  This requirement meant I could not use some of the alternate methods for testing Controllers by using a Controller context or special code to make sure DataAnnotation validation was occurring.

The end result eventually boiled down primarily to a single method which makes use of an in memory HttpServer, a reference to the static WebApiConfig class from the Web project containing the controllers and some code to add Basic Auth as needed to the request.  The only configuration necessary in the Unit Test app.config was the <system.web><authentication/></system.web> information necessary to enable authentication and the <connectionString/> section for access to the LocalDB database used in the Unit Tests.

The main method looks like:

    protected static Tuple SendRequest(HttpMethod method, Uri uri, HttpContent content = null, 
	string username = null, string password = null)
    {
	HttpConfiguration config = new HttpConfiguration {IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always};
	// The WebApiConfig class is from the Web project being tested.
	WebApiConfig.Register(config);
	HttpServer server = new HttpServer(config);
	using (HttpMessageInvoker client = new HttpMessageInvoker(server))
	{
	    using (HttpRequestMessage request = new HttpRequestMessage(method, uri.ToString()) { Content = content})
	    {
		if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
		{
		    request.Headers.Add("Authorization",
			"Basic " +
			Convert.ToBase64String(
				Encoding.GetEncoding("iso-8859-1")
					.GetBytes(string.Format("{0}:{1}", username, password))));
		}

		using (HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
		{
		    return new Tuple(response.StatusCode, response.Content as ObjectContent);
		}
	    }
	}
    }

This allowed me to write fairly simple code in the Unit Tests themselves while still allowing the Unit Test to exercise model validation, authentication, data access layer AND the Controller methods themselves such as:

    [TestMethod]
    [DeploymentItem(@"MyDatabase.mdf")]
    [DeploymentItem(@"MyDatabase_log.ldf")]
    public void GetSingleEntity_That_Does_Not_Exist_Should_Return_NotFound()
    {
	// TestInitialize should have cleared the database.
	Tuple result = SendRequest(HttpMethod.Get, new Uri("http://localhost/api/entity/1"));
	Assert.AreEqual(HttpStatusCode.NotFound, result.Item1);
    }

Unit Testing using LocalDB

 

I recently wrote some code with the typical data access layer as an interface to SQLServer.  The code I wrote doesn’t include a UI and has various operations occurring in its pipeline including authentication, model validation, data aggregation and so forth.  So now that the code is written it’s time for Unit Testing right?

Anybody that has had to write Unit Tests has at some point encountered issues with testing scenarios that include some kind of server.  A typical server issue when associated with a Unit Test is the need to build and/or reset the state of the server so that data is “just right” so that the Unit Test can perform its job.  That server might be IIS, SQLServer, SharePoint or something else but as soon as any server is introduced into the mix there is an immediate desire to pull back and start mocking things to remove the server issues. 

Unfortunately that means (when dealing with a database server) that stored procedures, table/column definitions and things like unique or check constraints, SQL data access layer and transaction/nested transaction commit/aborts won’t get tested.

Desiring to test these things along with everything else in the pipeline I thought that LocalDB might be the answer to my issues.  This article is about implementing that.

Generating/Updating the LocalDB Database

 

To start the process I created everything I need in a local SQLServer instance.  This makes it easy to implement and test since there are very good tools to do this.

Once I had all of it working in my local SQLServer I created a Visual Studio 2013 SSDT ‘SQL Server Database Project’.  The great thing about this project is how it makes it so easy to move changes from one database to another.  In my case, every time I made a change to the database, I needed to move the changes to a the VS database project (source control), SQL Azure database AND to my Unit Test LocalDB.  Doing all of this for any change takes less than 5 minutes each time.

One quirk I ran into with the ‘SQL Server Database Project’ is that schema compare wouldn’t connect to the LocalDB that was in my Unit Test project.  I eventually ended up leaving the LocalDB in the APP_DATA folder in a Web project where I would make the updates and then file copy the database into the Unit Test project.

The database files are stored at the root of the Unit Test project.  I would prefer to store them in a folder but idiosyncrasies with the [DeploymentItemAttribute] and changes in behavior on how the Unit Test runs in Release versus Debug caused me to just leave it in the root of the project and configure the [DeploymentItemAttribute] to also copy the database files into the root of the test location rather than a folder.

Configure the LocalDB Database

 

Mark the database files as ‘Content’ and ‘Copy Always’ and attribute each Unit Test with:

	[DeploymentItem(@"MyDatabase.mdf")]
	[DeploymentItem(@"MyDatabase_log.ldf")]
  

The connection string I left in the app.config for the Unit Test project and it presented the next challenge.  When a Unit Test is run the actual on disk location of the database file will vary.  Combine this with the need to use AttachDbFilename in the LocalDB connection string and you could create some interesting code pulling out connection string, figuring out directories and using string.Format to doctor the connection string before use.  However the location in the code that actually pulls the connection string from the configuration was deep within the SQL data layer and I didn’t want to try to modify the code to work with both Unit Test and Production.  Thankfully I found the answer to this at http://stackoverflow.com/questions/12244495/how-to-set-up-localdb-for-unit-tests-in-visual-studio-2012-and-entity-framework.  Combining using ‘|DataDirectory|’ in the connection string in the app.config with the following code in each test class solved that problem.

	[ClassInitialize]
	public static void ClassSetup(TestContext context)
	{
	    AppDomain.CurrentDomain.SetData(
		"DataDirectory",
		Path.Combine(context.TestDeploymentDir, string.Empty));
	}

Reset Database State for Each Test

 

So now the Unit Test can use the LocalDB but I also need to reset the database state before each Unit Test runs.  I could figure out a scenario like detaching the database (if it’s attached), recopying the database files and reattaching it before each test but I thought it would be easier to just use the same database and in [TestInitialize] I could just truncate all of the tables. 

Unfortunately all of the tables have identity columns, foreign keys, check constraints and all of the usual things you find in a database.  This meant I couldn’t run a SQL script in [TestInitialize] to just truncate all of the tables.

I then decided I’d delete all of the rows from each table and use DBCC CHECKIDENT to reset the identity columns so I could guarantee row ids in objects that were inserted into the SQL tables.  This led me down an interesting path.

Look at the documentation on DBCC CHECKIDENT and you’ll find the following in the documentation

image

The highlighted text is inconsistent with the behavior of SQLServer 2014 and LocalDB v11.0.  I didn’t test with any other versions of SQLServer or LocalDB so I don’t know if they have these issues as well but the actual behavior (you can decide for yourself which SQL is obeying the documentation as it’s still not clear to me) when using “DBCC CHECKIDENT(‘MyTable’, RESEED, 0)” after ‘DELETE FROM MyTable’ is:

  • SQLServer 2014 – The next row inserted has a row id of 1
  • LocalDB v11.0 – The next row inserted has a row id of 0!!!!

What?  I didn’t even know it was possible to have a Row ID of 0.  After many trials and tribulations and wondering if I needed to rethink using LocalDB I came up with the following SQL script that is run in [TestInitialize] (it runs before every test):

    BEGIN TRY
	BEGIN TRAN T1

	DECLARE @ID_TO_CHECK BIGINT

	DELETE FROM MyTable
	DBCC CHECKIDENT('MyTable', RESEED, 0)

	SAVE TRANSACTION T2
	INSERT INTO MyTable(Title) VALUES('test')
	SELECT @ID_TO_CHECK = MAX(MyTableId) FROM MyTable
	IF (@ID_TO_CHECK > 0)
	BEGIN
		ROLLBACK TRANSACTION T2
		DBCC CHECKIDENT('MyTable', RESEED, 0)
	END
	ELSE
		DELETE FROM MyTable

	-- Do more tables

	COMMIT TRAN T1
    END TRY
    BEGIN CATCH
	DECLARE @Error INT
	DECLARE @ErrorMessage NVARCHAR(4000)
	DECLARE @ErrorSeverity INT
	DECLARE @ErrorState INT

	SELECT @ErrorMessage = ERROR_MESSAGE(), 
		   @ErrorSeverity = ERROR_SEVERITY(), 
		   @ErrorState = ERROR_STATE()

	ROLLBACK TRAN T1
	RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState)
    END CATCH

This makes sure that when the test runs the next row that is inserted into the table will have a Row ID of 1 (NOT 0!!).

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