Singletracker.net – the technology

March 18th, 2013

Just a brief post to quickly call out the technologies I’m using in Singletracker.net. In the coming weeks, I’ll try to put up some more posts that get more into the details.

For starters, It’s running in Windows Azure which so far has been really easy to deal with but is going to get too expensive once my 90 day free trial is up.

On the back end it’s Asp.NET MVC 4 with WebAPI and Entity Framework 5. For authentication, I’m using OpenID with Facebook and Google. I plan to add Yahoo and Microsoft soon. If people actually use this, I will probably re-build the back end with node.js, express, and MongoDB.

On the front end, it’s Twitter Bootstrap for the responsive layout and other goodness. I’m using Font Awesome for the icons throughout – I think there is probably not a single image (except the map tiles of course). For the UI, I’m using Backbone.js and Leaflet.js with OpenCycleMap’s tiles.

Introducing Singletracker – crowd-sourced trail conditions for mountain bikers

March 17th, 2013

So a few weeks ago I wanted to go mountain biking. I wasn’t sure the trails would be fit to ride on so I went to the websites of the various trails looking for current trail condition info. It was either non-existent or hopelessly out of date.

So I got to thinking, it would be great to have a crowd sourced trail conditions web app. So I built it!

It’s a fairly responsive design – intended to be used on mobile phones (recent versions of iOS and Android) but it should work very well on desktop browsers and tablets. Note that it is intended to be used on modern devices/ browsers – I give ielt9 the Heisman.

V1 is now live. I’m representing the trails as points (think of them as the trail-head) because it’s far easier for a whole bunch of reasons. I’m thinking about ways to handle them as polylines but that’s down the road a ways. I want to get it out there, try to get people using it, get their feedback and see where that takes us.

The zen of it is:

  1. You land at the page and get a map centered on your location.
  2. If there are any trails that have been entered nearby, they will appear as points with different symbols for good, fair, poor, or unknown condition.
  3. You can click/ tap on a point to get a popup containing a bit more information and a button that takes you to the trail details page.
  4. You can also click ‘List’ in the menu to get a list of all the trails in the system sorted by distance from your location.
  5. If you click/tap an item in the list, you go to the trail details page.
  6. On the trail details page there is info about the trail and its condition as well as buttons to: update the trail condition, edit the trail info, or view the trail on the map.

Check it out singletracker.net.

Diving in to Backbone.js

December 9th, 2011

We’ve known for a while that there are a number of javascript mvc frameworks out there and that many of the apps we build would likely benefit greatly from using one. Bet we’ve held back mostly because of the learning curve/ time constraints but also partly because it wasn’t clear which one was gonna be ‘best’ for our needs. Well, we’ve got a particular project on our plate right now that just begs for a framework like this so we decided to take the plunge. We settled on Backbone.js mostly because it seems like there are lots of super smart people who are using it (and they still like it!) and also because there seem to be lots of resources available for it (not least of which is the very good documentation).

I don’t really have the time to do a proper Intro to Backbone post but fortunately many others have done so. Some are better than others though, so what I thought I’d do is share some of the resources I found most helpful and mention a few of the additional libraries we’re using.

It’s true that the learning curve is somewhat steep but once you dive in, it’s not really that bad. A good place to start is http://backbonetutorials.com/ which provides a brief introduction to the various backbone components. A very easy to understand and quite good hello world example is at http://arturadib.com/hello-backbonejs/docs/1.html. This one is cool because it starts very simply and progressively adds complexity.

Rob Conery wrote a two part post discussing some of the problems he saw with many Backbone tutorials. I was really happy to see this because I shared some of his objections.

One of the things I missed when I first started this project was model binding. Then I found this awesome plugin for Backbone which provides two-way, convention-based model binding. This was ridiculously easy to use and it allowed me to slim down my views considerably.

One issue I had was that the particular needs of our app called for messaging between various components other than just a model and its view. For instance, I needed my Results view to know when my Criteria model changed so it could update itself with new data based on the Criteria model that changed; but other than that, the Results view needed no knowledge of the Criteria model. I initially used a shared reference to the Criteria model but I didn’t love it because I wanted my components to be more loosely coupled. I now think that would have been fine but my dissatisfaction lead me to this post that suggests using the Event Aggregator pattern. It’s really very simple. Since I already had all my modules namespaced, I just put my event aggregator as a property on my namespace object and all my other modules have access to it:

dts.eventAggregator = _.extend({}, Backbone.Events);

Then you can just do

dts.eventAggregator.bind('fooEvent', fooEventHandler, this);

and

dts.eventAggregator.trigger('fooEvent', {/*event arguments*/});

I found this very good post discussing a good approach to avoiding memory leaks. One of the comments lead me to this StackOverflow post discussing the same issue. I think a combination of these two approaches would work well.

Though I’m new to javascript mvc frameworks, I’ve been using javascript templating for a while now. I’ve mostly been using jQuery Templates which I like just fine, but I took this opportunity to try some other templating engines. I ended up settling on icanhaz.js because it uses the mustache.js template syntax (it actually uses mustache under the covers, I think) which I like very much and because it precompiles the templates into functions (thus improving performance, I assume) and hangs them right on the ich object with the function name corresponding to the id of the template (thus making it very easy to use). I’ll definitely be sticking with icanhaz going forward.

Of course, one of the best things about the MVC pattern is that it lends itself quite well to testing. I found a very nice multi-part post on testing backbone applications – the first part is here. I had used qUnit before so I decided to stay with it to minimize the risk of my head exploding from all the new stuff (though I was tempted to give Jasmine a whirl). The post above lead me to sinon.js (and its qUnit adapter, sinon-qunit) which is a really great little library that provides test spies, stubs, and mocks. Unit testing this stuff was fun and it actually helped me uncover some bugs that I didn’t notice in my ui testing.

I’ve learned a ton this week, which is always fun, and I’m looking forward to building more applications with Backbone.js.

Loading a blog feed on your website

July 29th, 2011

Recently I needed to load recent blog posts onto a website. I discovered the Google Feed API which, as most things Google, is awesome. I also discovered this jQuery plugin which uses it along with what appears to be an old version of their Dynamic Feed Control. This plugin, like all of Mike Alsup’s other plugins, is great. However, I couldn’t get it to work exactly the way I wanted. So I built my own.

I also borrowed and modified some code from John Resig to format the dates. Oh yeah, it also depends on the jQuery Templating Plugin.

It takes an options argument with a required url property and a couple of other optional properties, gets the feed, and loads the items into semantic markup inside the selected element. You can then style it any way you want.

/**
*  Plugin which uses the Google AJAX Feed API for creating feed content
*  depends on jquery template plugin
*  very loosely based on http://jquery.malsup.com/gfeed/
*/

(function ($) {
    if (!$.template) {
        alert('You must include the jQuery Templating Plugin script');
        return;
    }

    //feed item template
    var templateHtml = '<div>' +
                            '<div class="feed-item">' +
                                '<a href="${link}" target="_blank">' +
                                    '<h2 class="feed-title">${title}</h2>' +
                                '</a>' +
                                '<div class="feed-snippet">${contentSnippet}</div>' +
                                '<div class="feed-footer">Posted ${publishedDate} by ${author}</div>' +
                            '</div>' +
                        '</div>';

    //from based on code from John Resig
    // - http://ejohn.org/blog/javascript-pretty-date/
    function prettyDate(dateString) {
        var date = new Date(dateString);
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
		            day_diff = Math.floor(diff / 86400);

        if (isNaN(day_diff) || day_diff < 0) {
            return;
        }

        return day_diff == 0 && (
			        diff < 60 && "just now" ||
			        diff < 120 && "1 minute ago" ||
			        diff < 3600 && Math.floor(diff / 60) + " minutes ago" ||
			        diff < 7200 && "1 hour ago" ||
			        diff < 86400 && Math.floor(diff / 3600) + " hours ago") ||
		            day_diff == 1 && "Yesterday" ||
		            day_diff < 7 && day_diff + " days ago" ||
		            day_diff < 42 && Math.ceil(day_diff / 7) + " weeks ago" ||
                    day_diff >= 42 && Math.floor(day_diff / 31) + " months ago";
    }
    new Date().tou
    $.fn.feed = function (options) {
        var opts = $.extend({
            url: '',
            target: this,
            title: 'The latest from our blog',
            max: 5   // max number of items
        }, options || {});

        //show a loading indicator
        opts.target.append('<div id="feed-loading">loading blog feed...</div>');

        //get the feed items
        var feedItemTemplate = $(templateHtml).template();
        var gFeedsUrl = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&num=' + opts.max + '&q='
        $.ajax({
            url: gFeedsUrl + encodeURIComponent(opts.url),
            dataType: 'json',
            success: function (response) {
                //remove the loading indicator
                $('#feed-loading').remove();

                if (response && response.responseData
                                  && response.responseData.feed
                                  && response.responseData.feed.entries) {
                    var feedItems = response.responseData.feed.entries;
                    //map them to format the date
                    $.map(feedItems, function (item, idx) {
                        item.publishedDate = prettyDate(item.publishedDate);
                        return item;
                    });
                    //load the feeds into the dom
                    opts.target.append('<h1>' + opts.title + '</h1><div id="rss-feed"></div>')
                        .find('#rss-feed')
                        .append($.tmpl(feedItemTemplate, feedItems));
                } else {
                    opts.target.append('<div id="feed-error">Unable to retrieve blog feed.</div>');
                }
            }
        });

        return this;
    };
})(jQuery);

Sending javascript dates to Asp.NET

July 29th, 2011

I’ve struggled with this at various times and come up with a number of solutions, none of which were entirely satisfying. Now, thanks to Stackoverflow, I found a really nice solution:

Javascript:

obj.date = new Date().toUTCString();

C#:

DateTime date= DateTime.ParseExact(obj.date,
                                  "ddd, MMM d yyyy HH:mm:ss GMT",
                                  CultureInfo.InvariantCulture);

And now for something completely different…

July 15th, 2011

I’ve been meaning to post about this for years and am finally getting to it.

In January of 2007 we bought our house from Jamestown Builders. When it was about a month out of warranty, we noticed that like some of our neighbors’, our driveway had begun to spall.

I called them to see what they were going to do about it and their response was basically that I shouldn’t have parked my car on it in the winter. Well, I didn’t very often, but IT’S A DRIVEWAY! Can I cook in my kitchen? Can I poop in my bathroom? The rationale is that the freeze/ thaw cycles are exacerbated by the stuff they put on the roads (and then drips off my car) to melt ice and that cracks the driveway. According to my research, while that certainly can happen, it should not happen to properly formulated and installed concrete.

Furthermore, I had a concrete driveway in MINNESOTA that was who knows how many years old when I bought the house and on which I parked my truck every day for the 6 years I lived there. Last time I looked (in 2010) that driveway was fine. By now, The Jamestown driveway is 4 years old and it is quite simply disintegrating. I think it’s outrageous that I’m going to have to spend at least $3000 on my driveway when the house is barely 5 years old.

driveway

The bottom line is that they clearly had a quality problem with their concrete contractor. They know this perfectly well and if they’d just say so but say, “sorry you’re warranty expired”, I could accept that. But it rankles that they claim it’s my fault and that it’s to be expected for a driveway to disintegrate if you use it for it’s intended purpose.

So I do not recommend purchasing a house from Jamestown Builders.

Single finger scrolling in Mobile Safari

June 21st, 2011

We built the BackChannel using the Mobile View Engine I discussed in this post. If you hit the site with a phone we serve a mobile version, but if you hit it with a tablet, we serve the full version, which, of course, we expect to work. For the schedule page, I built a nifty full screen multi-pane interface that works perfectly in all desktop browsers I tried and in the Android 3.1 browser on my Xoom. But yesterday Dave pointed out that the bottom left and right panes wouldn’t scroll on iPad.

After a little digging, I found that Mobile Safari doesn’t support single finger scrolling on divs. You have to use two fingers. This is actually documented in the iPad User Guide. Presumably this is because on touch based devices it’s hard to know if you intend to scroll the whole page or just the div. But, like I said, it works perfectly on my Xoom. Now, if I didn’t know this, I certainly can’t expect my users to.

I found that Nick Larson had created a very simple fix to implement single finger scrolling. I took it and rolled it into a jQuery plugin (my first, actually) using Mike Alsup’s plugin pattern. There are other solutions out there but mine has the virtue of being very easy to understand and very light (644 bytes minified).

/*mjuniper 06/21/2011
    based on code from:

http://www.flexmls.com/developers/2011/04/13/

ipad-and-single-finger-scrolling-in-flexmls/
    and http://www.learningjquery.com/2007/10/a-plugin-development-pattern
*/
//
// create closure
//
(function ($) {
    //
    // plugin definition
    //
    $.fn.mobileScroll = function (options) {
        //only do it for iOS devices
        var userAgent = window.navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('ipad') > -1 ||
                userAgent.indexOf('iphone') > -1) {
            this.bind('touchstart', function (evt) {
                var e = evt.originalEvent;
                startY = e.touches[0].pageY;
                startX = e.touches[0].pageX;
            });

            this.bind('touchmove', function (evt) {
                //need the touches property of the native dom event
                // - jquery exposes originalEvent for that
                var e = evt.originalEvent;
                var touches = e.touches[0];
                //cache $(this)
                var $this = $(this);

                // override the touch event’s normal functionality
                e.preventDefault();

                // y-axis
                var touchMovedY = startY - touches.pageY;
                startY = touches.pageY; // reset startY for the next call
                $this.scrollTop($this.scrollTop() + touchMovedY);

                // x-axis
                var touchMovedX = startX - touches.pageX;
                startX = touches.pageX; // reset startX for the next call
                $this.scrollLeft($this.scrollLeft() + touchMovedX);
            });
        }

        return this;
    };
    //
    // end of closure
    //
})(jQuery);

ESRI UC BackChannel is live!

June 15th, 2011

We’re still tweaking but the BackChannel app for the 2011 ESRI International User Conference is live! We’ve had tons of fun building this app; we hope you enjoy it.

Esri UC BackChannel app – localStorage and jQuery deferred

June 10th, 2011

So Dave and I recently put together a BackChannel app for the Esri User Conference next month. For the agenda part of it, we wanted to use localStorage to store the data so that after the initial page load, it would be snappy (the session data is several hundred kilobytes). So I built a little repository class that wraps all that up using jQuery deferred. Below is the getUcSessions method. Basically, it checks to see if the sessions are in local storage and, if so, returns them, if not, it requests them with an XHR, returns a deferred, and resolves the deferred when it’s got them. That way my calling code doesn’t need to know anything about localstorage or the XHR or anything.

getUcSessions: function (sessionsJsonPath) {
       //if we've got it in localStorage, return that
       var data = localStorage.getItem(_sessionKey);
       if (data) {
           console.debug('got sessions from localStorage.');
           _ucSessions =JSON.parse(data);
           return _ucSessions;
       }

       //otherwise, load the json and stuff it into localstorage
       //here we return a promise that will be resolved when we've gotten and processed all the data
       var dfd = new $.Deferred();
       $.getJson(sessionsJsonPath, function (sessions) {
            _ucSessions = sessions;
            console.debug('got sessions via XHR.');

            dfd.resolve(_ucSessions);
       });
       return dfd.promise();
}

Then to call it, you just do:

$.when(_repo.getUcSessions(args.sessionDataUrl)).then(function (ucSessions) {
    //Do stuff with the sessions...

});

Collapse the iPad Keypad in Javascript

April 26th, 2011

I recently built a web application with a search field which geolocates whatever you typed into that field and zooms you to the results. We were severely constrained on UI space so we went without a search button and we just do the search when the user hits the enter key.

This worked fine on the iPad except that the keypad didn’t collapse. Of course, you can’t directly control the keypad in Javascript but I had a hunch that if I just removed focus from the search field, it would collapse. And it worked! Code (jQuery) below:

$(this).blur();