Basic Javascript Templates with Handlebars

I have recently worked on a project using Javascript with Handlebars as a templating engine. I do not claim to be a Handlebar, or Javascript, expert, I am just making note of what I have learned for future reference and maybe something I write here will benefit someone else who trying to get started with Handlebars.

I have made a simple little example project with some sports themed data. My data is a collection of sports leagues. Each league has a Name, an acronym, the year it was founded, and can have a collection of teams. Each team has a city, a name, and a division. The structure in Json form is this:

var sportData = {
    league: [
        { name: "National Hockey League", acronym: "NHL", founded: 1917, },
	{ name: "Major League Baseball", acronym: "MLB", founded: 1869, },
        { name: "National Basketball Association", acronym: "NBA", founded: 1946, },
        { name: "National Football League", acronym: "NFL", founded: 1922, },
        { name: "Major League Soccer", acronym: "MLS", founded: 1993, },
    ]
};

In theory this is something that is returned from an API, but for the purpose of this small example, in code will work. So the question is, how can I easily display this data? The answer that I am covering in this blog is……Handlebars. Shocker, right?

So here is my simple Handlebars template to plop that data into the web page for me.

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
        <ul>
            {{#each league}}
            <li>
                <label>{{{name}}} ({{acronym}}) [Founded {{{founded}}}]</label>

            </li>
            {{/each}}
        </ul>
    </div>
</script>

So let’s break this down. This really is just HTML with some handlebars bits injected. So I have a container div I call sport-list. This literally is just a wrapper div that I choose to put. It is not used for anything at the moment. Next I have a <ul> to start my list. Just below that, there is the first bit of handlebars notation, which is {{#each league}}. This is essentially a foreach that is seen in many other languages. So {{#each league}} will look for an object called league within the current data context. Then, for each object within the league object, handlebars will repeat the chunk of code until the matching {{/each}}. Inside of the each, there is an <li> just to make each entry its own list item, then a boat load of curly braces. The first handlebars bit is {{{name}}}, which tells handlebars to put whatever is in the object called “name” there. Then {{{acronym}}} tells handlebars to put whatever is in the object call “acronym” in that place. I am sure that you can now guess what {{{founded}}} does. If any of that data is missing, handlebars essentially leaves it blank.  The last bit of important information is the id on the script tag. That will be what is given to handlebars to let it know what template to use.

Before you can use a handlebars template on a webpage, it needs to compiled. To do that, we have to call “Handlebars.compile()” and pass in the id of the script that you want compiled, in my case that is “sports-template.” I have chosen to put the actual Handlebars.compile call inside of an object called “handlebarsSample” that will also be used to hold as much of the handlebars related javascript as possible. “handlebarsSample” looks like this:

var handlebarsSample = function () {
    function compileTemplate(scriptId) {
        if (scriptId[0] != "#") {
            scriptId = "#" + scriptId;
        }

        return Handlebars.compile($(scriptId).html());
    }

    function registerPartials() {
        //No partials right now
    }

    function registerHelpers() {
        //No Helpers right now
    }

    return {
        compileTemplate: compileTemplate,
        registerPartials: registerPartials,
        registerHelpers: registerHelpers,
    };
}();

To explain this, I will start at the top. The first thing I do is define an object called “handlebarSample,” which is just a function used to house other objects. Currently, those three objects are registerPartials, registerHelpers, and compileTemplate. The two registers are not currently being used because my sample is too simple to need them yet, so I am not going to explain them. They are just placeholders at the moment. compileTemplate, however, is used. That is where I am actually calling the Handlerbars.compile function. This allows me to do some validation or error checking of the script Id that I want to compile. My case I am just making sure that I have the needed “#” that jquery uses to find Ids in the DOM. If the first character is not a “#” put one, then pass that to the compile function, which is returned from this function to where ever the call to it was made.

So now I have data. I have made a template. I have compiled that template. But I have nothing showing up on my webpage yet.  That is because we have not yet plugged the data and template together, nor have we injected the result. The first step is to actually compile the template.

var sampleTemplate = handlebarsSample.compileTemplate("sports-template");

Then I want to take that result, plug the data into, and put it somewhere on the page.

$('#sample-div').append(sampleTemplate(sportData));

Lets work inside-out for this. The sampleTemplate(sportData) is where I plug my data into the handlebars template. Then I use a basic jquery selector to grab the appropriate div, then I just append the results that div which gives the output of:

National Hockey League (NHL) [Founded 1917]
Major League Baseball (MLB) [Founded 1869]
National Basketball Association (NBA) [Founded 1946]
National Football League (NFL) [Founded 1922]
Major League Soccer (MLS) [Founded 1993]

That is the very basics using handlebars. There is a more I plan to cover, including partials and helpers in future blogs, hopefully soon (no promises).

For the full source look at these two files.
SportsLeagues.html
handlebarsSample.js

The 7 Tenets of an Engaging & Natural User Experience – From a Developer’s perspective

One of the more fun projects I have done in the past couple years is a video for Wintellect called “The 7 Tenets of an Engaging & Natural User Experience – From a Developer’s perspective”.  Wintellect has an online training division called WintellectNOW!.  I had never done anything like this in my career and when my buddy Sara Faatz reached out to me I just couldn’t say no.  I have lots of buddies at Wintellect.  It’s a great company.  I knew it would be a ton of work to pull off a good video.  I did a little bit of due dilligence with my other industry peers that speak in front of large technical audience who are wintellect authors and everyone of them had glowing things to say about Wintellect….which I expected.

Now when i say it was a ton of work I am not kidding.  Unlike a normal training video where you record your voice while recording your screen with a tool like camtasia, i had to record my demos the real way….the old fashioned way…and there are 18 demos in this training.  Because user interaction design is an underlying theme of this training and NUI is touching, waving and speaking to computers.  you cannot screen capture that type of user experience and hide under the umbrella of redoing the audio in post production.  I solicited my son Mark, who is a nationally awarded film maker, to do the filming… and I learned a lot about filming and lightning that long sunday from an 18 year old.  The editing was a week long process where i jumped from Kindergarten to 5th grade in my Sony Vegas (Movie Studio) skills.

I think it came out just great.  i have got some really good feedback.  It’s the first “designer” like thing i have done in this format.  So, i am venturing into new territory.  i have started doing user interaction design presentations and keynotes in front of live audiences, but this is different.  i really am looking forward to doing the next one.  It’s just a matter of scheduling and allotting the enormous amount of time.  Sara and I pencilled in a few more titles; i just hope she doesn’t read this post in a timely manner. :)

If you want to view the training it’s easy.  There is a 14-day free trial with no obligation.  Folks just go to:  https://www.wintellectnow.com/Account/Register and enter “HUCKABY-14” in the “Promo code” box.  You’ll have to provide your email address; create a password; and enter your first and last name. Once that’s done, you’ll have access to my video and the entire library for 14 days.

Uploading a file with an MVC 5 Controller with views, using Entity Framework

I’ve been working on a simple CRUD website using MVC 5 (w/ Razor) and EF 6, and when creating or editing a specific item I needed to upload a picture along with the EF object. I looked around and found a few options, but most were more complicated than I needed or they uploaded the picture/file separately from the create/edit views. So I wanted to document the simple hybrid I was able to use.

You start off with a database, EF model of that DB and an MVC 5 Controller with views, using Entity Framework (template from Visual Studio). The concept is virtually the same for Edit or Create, so I’ll only show the code related to Create.

In the .cshtml file I did 2 things.

  1. I updated the Html.BeginForm call to include the Action, Controller, method AND the enctype = “multipart/form-data”
  2. I added an input element that specified its type as a file, and it provided a button to choose a file, and showed the filename after the file was chosen.
<input type="file" name="file" id="file" style="width: 100%;" />

With that finished, I went to the backing controller, to the Create method, and added an additional parameter of HttpPostedFileBase. Now when the user clicks the save/create button the file parameter will be non-null if a file is chosen, and you can handle it however you like. Below is an example:

public async Task<ActionResult> Create( [Bind( Include = "Properties" )] EntityFrameWorkModel model, HttpPostedFileBase file )
{
	if ( file == null )
	{
		ModelState.AddModelError( string.Empty, "An image file must be chosen." );
	}
	else if ( ModelState.IsValid )
	{
		string fileName = Path.GetFileName( file.FileName );
		// save file however desired using file.InputStream
		
		db.EntityFrameworkObjects.Add( model );
		await db.SaveChangesAsync();
		return RedirectToAction( "Index" );
	}
	
	return View( model);
}

As I said, it’s a simple solution, but it’s quick to implement.

Presentation: Introduction to Windows 8.1 App Development

A huge thanks to the crowd at the San Diego .NET Developers Group! You guys were an awesome crowd. Congrats on the 20 year anniversary of the group as well. It’s great to know we have a deep culture of helping and teaching each other in the area. Keep it up!

For those that couldn’t make it we discussed how to handle Page Navigation and App Lifecycle for the first hour then moved into Location Services for the last 30min. Theses are some critical topics for Windows 8.1 App Development that I think a lot of people could use some help with. I only say that because many apps I use behave badly. I hope you find the recording of the session useful. Please leave some comments on what you think!

Materials

 

Again, thanks a bunch! And we’ll catch you next time!

Getting Started with PHP On Windows

Intro

For the four-or-so years that I’ve been writing code, it’s always been with a Microsoft technology; starting with VBScript, moving to VB.Net, and eventually C#, Silverlight, and WPF. I’ve been meaning to dive in to the cross-platform, open source world of Web Development, and I have explored the various aspects of it at different times, so I’m going to do an end-to-end, cross platform “Address Book” based on web technologies…HTML 5, CSS, and JavaScript for the front end, PHP for server side scripting, and MySQL for my database. However, I will still be using a Microsoft product…IIS as my web server, for the sake of familiarity. This walkthrough will help you get PHP installed on your Windows machine, and IIS configured to work with PHP.

Preparing IIS

PHP is very well documented, and I suggest you browse through the manual at http://www.php.net/manual/en/index.php to get familiar with the language before diving right in to the preparation and installation. The steps I list below are for IIS 7, on Windows Vista SP1, Windows 7, or Windows 8, and are based on the instructions in the manual I linked to above.

  1. Assuming you already have IIS 7 installed ( go do that, if you don’t), we need to enable FastCGI on IIS. To do this, open Control Panel, and select Programs and Features. In the column on the left side, click “Turn Windows features on or off”. In the Windows Features dialog, expand Internet Information Services, then expand World Wide Web Services, Application Development Features, and select the check box next to CGI. You should see something like this…..
  2. Click Ok, and Windows will do the installation.

Installing PHP

The actual process of installing PHP requires a bit of reading, because you have to set up the config file once you’ve downloaded and extracted the correct build of PHP. Here is a link to the full process… http://www.php.net/manual/en/install.windows.manual.php . Once you download and extract PHP, and get your config file set up, we’ll need to tell IIS how to process PHP requests.

Configuring IIS to Process PHP

These last steps will guide you through using the IIS Manager UI to create a handler mapping for PHP, and, again are based on the steps in http://www.php.net/manual/en/install.windows.iis7.php . I recommend you take a look at their manual after doing this simple UI setup, as they have detailed information on how to use the command line tool, and information about impersonation and file system access.

  1. Open Control Panel, select Administrative Tools, and double click IIS Manager.
  2. Select the Server node in the tree view on the left side, and then double click the Handler Mappings icon in the IIS section of the Features View. It should look similar to this…    
  3. In the Actions pane on the right, click “Add Module Mapping…” 
  4. Enter the following information in the “Add Module Mapping” dialog…
  • Request path: *.php
  • Module: FastCgiModule
  • Executable: C:\[Path to PHP installation]\php-cgi.exe
  • Name: PHP_via_FastCGI

5.  Click “Request Restrictions” button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

6.  Click OK on all the dialogs to save the configuration.

Test

If everything went according to plan, your default website is now configured to process PHP requests. Here’s how we test it…

  1. Open up Notepad and enter the following line of text, without the quotation marks surrounding it…”<?php echo ‘Hello World’; ?> “
  2. Click File, Save As…, and save the file as Test.php ( be sure to set the file type to All Files) in your My Documents folder.
  3. Copy the Test.php file to C:\inetpub\wwwroot.
  4. Finally, open a web browser and browse to localhost/test.php. You should see your Hello World output.

Conclusion / Now What?

This walkthrough covered the very basics of getting PHP installed, and setting up IIS to process PHP requests. It didn’t begin to touch on the actual language, syntax, or usage of PHP, but there is great documentation and plenty of walkthroughs at php.net to get you started on using PHP. My next blogs will be about setting up MySQL ( Spoiler: it was infinitely easier than my first attempts at installing and configuring Microsoft SQL Server ) and connecting to it from PHP, and how to use browser detection to detect mobile devices and load appropriate css sheets.

CES 2014 – My Presentation and Invite to a Private Party (VIP Reception)

ces

I am pretty excited (and honored to be invited back) to speak at CES International in Las Vegas again this year.  My presentation details are below in case you are going to CES and can attend.

But, I’m also keynoting a VIP Reception that same night.  it’s a private event with a party (cocktails / food) after.  It should be totally fun.  It’s sponsored by the Microsoft Perspective Pixel Team, Avnet, and hosted at The Integration Center.  It’s free and transportation to and from the CES conference center is provided.  I have provided the Details and registration link and private code below.

Details:

Register to Attend VIP Reception at CES 2014

You are invited to attend a VIP reception at CES 2014 hosted by Perceptive Pixel (PPI) by Microsoft and Avnet. The International CES Conference covers all things groundbreaking, market-leading and pioneering in the consumer electronics (CE) industry and PPI will be there to showcase how you can leverage our devices to redefine your meeting experiences.

The reception hosted at the Integration Center in Las Vegas brings together industry-leading companies and ideas under one roof. The event will kick off with a special keynote presentation from Tim Huckaby  on “The Engaging User Experience & the Natural User Interface”. This demo focused keynote will take an amusing look at the past and take an impressive look at some of the best NUI software being built today and into the immediate future and will even delve into the NUI of the future.

A cocktail reception will immediately follow the keynote, where you will have the opportunity to meet with key executives from Microsoft and Avnet to learn more about how we are working together to drive innovation and collaboration in the industry while networking with fellow CES attendees. You will also have an opportunity to see demos and learn how PPI is enabling organizations to spark creativity, ignite collaborative power, showcase their best.

Space for the reception is limited, use the link below to RSVP and secure your space to attend. Registration closes Friday,

When& Where:

Wednesday, January 8th

4:30 – 5:30 PM – Keynote Presentation The inNEVation Center

5:30 – 7:30 PM – Cocktail Reception The Integration Center

6795 Edmond Street, Las Vegas, NV 89118

(702) 605-9800

Transportation:

Shuttles will pick up attendees at 4:00 PM at the Venetian Resort Hotel Bus & Tour Lobby

Shuttles will depart the Integration center at 7:30 PM to return to the Venetian Resort 

Link to Register:

https://msevents.microsoft.com/CUI/InviteOnly.aspx?EventID=C0-41-DD-A3-8F-29-24-BF-A0-2D-85-33-19-6A-99-72&Culture=en-US&community=0

RSVP Code:

521DAE

Please note that registration requires a Microsoft account to register. If you use Hotmail, SkyDrive, Xbox LIVE, or a number of other products you already have a Microsoft Account. Don’t have a Microsoft account? Sign up now to create your profile and save time for future registrations.

Reception Co-Hosted By

clip_image001 clip_image003clip_image005


Details on my Presentation at CES:
January 8, 2014

Session: User Interface Innovation: What’s on the Horizon?

Gesture control has moved from videogame consoles to PCs and TVs and it is setting its sights on your car’s dashboard. Is 2014 the year of gesture? Will kinetics, facial recognition, eye tracking and brain control make the cut or die on the vine?

Location:LVCC, North Hall

Room:N259

Time:2:00 PM – 3:00 PM

Role:Moderator

Text On A Path With Alignment

Click here to download code and sample project

In past WPF projects, design specifications given by artists are sometimes challenging to attempt to implement. One scenario I have ran into multiple times was trying to display custom text around a curved object. Most of the time this problem was avoided by the artist providing the content as images, but, fortunately, this was only feasible because the text was finite and static. Recently I came across this same scenario again except this time the incoming text could be dynamic. The immediate reaction was to simply read the text as images stored in a folder provided by the customer. This solution tends to create problems in the future because:

  • The user must be familiar with some image editing tool
  • If not accustomed to any, then the user has to be trained
  • The user must be aware of the exact font, weight, and color the artist intended
  • The user must also have the same eye for lining up text as the original artist intended (which many tools can aid in)

With all these issues, it would be better to assume that if a user could get something wrong then they will, which will result in an application that seems off. Not happy with this path I decided to look into creating text on a path.

Fortunately, a majority of the work had already been developed by Charles Petzold described in his article Render Text On A Path With WPF.

The article provides a comprehensive description of his algorithm for placing text on a path. It is worth a read to get an in-depth understanding of how the algorithm works. To try and sum it up though, the algorithm uses a PathFigure object to shape the path the text will render and the class comes equipped with a method to help simplify calculations. In sizing the text font onto the path, the text is scaled to fit entirely on the length of the path. For the best performance, we render the text as DrawingVisual objects so they only need to be created once when the text changed. The result comes out as this:

Fantastic! This worked well for what I wanted, except for one problem; the text scaling. I knew the path I wanted my text to render, but not the length of the text since that could change dynamically. When attempting to apply this algorithm to a path I had in mind, the results were less than pleasing (red curve represents the path for the text):

I needed the text to render the same size despite the length of the path, but the current algorithm would require me to resize the path dynamically based on the size of the text. This did not seem reasonable, especially since I would prefer the text to rest on the center of the path.

So, in order to accomplish this the first thing I needed was a Dependency Property of type HorizontalAlignment to set the content alignment. Setting the alignment to Stretch will keep the original behavior of the algorithm by resizing the text to fit the path. Then we need another Dependency Property for font size, which will only get applied if the content alignment was not Stretch. Now, when calculating the text length we need to substitute our font size over the default 100

private void OnTextPropertyChanged()
{
    _formattedChars.Clear();
    _textLength = 0;

    if (!String.IsNullOrEmpty(Text))
    {
        foreach (char ch in Text)
        {
            var fontSize = ContentAlignment == HorizontalAlignment.Stretch ? 100 : FontSize;

            var formattedText =
                new FormattedText(ch.ToString(), CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight, _typeface, fontSize, Foreground);

            _formattedChars.Add(formattedText);
            _textLength += formattedText.WidthIncludingTrailingWhitespace;
        }

        GenerateVisualChildren();
    }
}

Then we move onto our TransformVisualChildren method and make sure the scaling factor stays at 1 since we no longer want the text to rescale to the path

private void TransformVisualChildren()
{
    ...
    var scalingFactor = ContentAlignment == HorizontalAlignment.Stretch ? _pathLength / _textLength : 1;
    ...
}

Since content alignment can be set as Center, or Right aligned, the initial progress will need adjusting to push the text further along the path

private void TransformVisualChildren()
{
    ...
    double progress = 0;

    switch (ContentAlignment)
    {
        case HorizontalAlignment.Left:
        case HorizontalAlignment.Stretch:
            progress = 0;
            break;
        case HorizontalAlignment.Center:
            progress = Math.Abs(_pathLength - _textLength) / 2 / _pathLength;
            break;
        case HorizontalAlignment.Right:
            progress = Math.Abs(_pathLength - _textLength) / _pathLength;
            break;
    }
    ...
}

And that is all we have to do since the scaling factor will be set to 1 if content is not stretched. Here is the result with content alignment set to Center. Also, you can see all the various alignments applied:

Although I was very satisfied with the results, a change in the scope of our project made this solution obsolete. Just another day in the life of a programmer.

Future of Enterprise Software Services

Over the Thanksgiving Holiday I did a lot of thinking about what the future looks like for software as it relates to services provided to clients. I am lucky enough to work at a cutting edge software development firm that constantly looks to innovate what it is that we provide to customers. This notion was again brought to my attention when I read an article on Microsoft’s Quarterly results. In the article, one of the conclusions was, “The company is increasingly focusing on the enterprise’s needs in a more integrated way as the company continues to increase/improve its Cloud and Data Center offerings integration.” To me, I read this as Microsoft is focusing on the enterprises as a whole, and how to fulfill the needs of customers who are shifting from licensing software to hardware neutral solutions and integrating platforms.

Cloud and Data Center integration make it possible for people to work from anywhere, but how does a company make this appealing to their employees and customize that experience? I think the answer is that it is up to companies to develop experiences that is customized to their employees. This service has a large amount of value as it essentially “consumerizes” employees to a point. For example, how many times have you been on a website and a personalized ad pops up on the border of your browser? Those ads are derived from data that you have put on there, i.e. web searches, purchases, internet history, etc. Companies can harness the same power by looking at the work flows of their employees and personalizing their experiences through cloud services such as O365 Home Premium and how they are navigating those solutions. If an employer is able to customize their employees experience while they are working remotely, I believe that productivity would increase and you would have much happier workers.

In the future of providing services to enterprise software, we must tune in and listen to what our customers needs are and how best to deliver these services. Creating an innovative and intuitive experience is paramount but also keeping the end user in mind and their preferences should be integrated as well.

ContentControl “bug” in WinRT

Background

I was recently on a WinRT project that required showing a hierarchy of assets that the user could browse through, ultimately leading to an “asset details” view where they can interact with the selected asset. One of the interactive features was to have a toggle button that would hide/show a details pane with the asset description. Throughout the asset hierarchy, the data templates would bind to Name and ImageUri properties on the assets to display them. When I got down to the asset details level, I needed to wrap the asset in a ViewModel to support the command that I needed to implement the description toggle.

Implementation

After messing around with the built in Transition API trying to get my description pane to animate in, I realized that I needed to expose a separate Asset property on my VM so my description pane could bind to it via a ContentControl with a ContentThemeTransition, and to do the toggling I would just null the object in the VM and let the Transition work its magic. I tested this without the ContentTemplate set on the ContentControl (just bound directly to the extra Asset property I added to my VM), and it worked as I expected…..the description pane was hidden, and when i clicked the toggle button the pane animated in and showed that it was bound to an Asset object.

Problem

The problem started when I added the DataTemplate that was bound to the ImageUri and Name of that Asset property. When I tested it, the description pane was instantly visible before I clicked the toggle button.

Solution

After a lot of breakpoints and head scratching, my theory was that, even though the Content property of the ContentControl was bound to this seperate Asset that I added to the VM, it still looked up the tree to find those properties when the object was null. Since the VM itself had those same properties, the DataTemplate was binding to that and displaying the pane when it shouldn’t have been. Sure enough, I made a separate little class to hold the Name and Description properties, and named them differently, and it worked fine. The surprise for me here was that the ContentControl was looking up the tree for property binding when it’s content was null, and it only did it when a DataTemplate was defined. I’m not sure if this is a bug, or by design, but it can cause a headache if you’re not expecting it.