Evolution

I’ve been thinking for a while about moving my simple web site and blog to a different platform. I’m currently paying to host everything on a traditional hosting service. Ten years ago, this was really the only option if you wanted buy a domain and put a web site out there (there was also self hosting with dynamic DNS, but I was never brave enough to open up my home network). Now, we have so many options that it would be difficult to list them all. We have “cloud” hosts like Azure and AWS. We have developer-friendly hosts like Heroku. GitHub can even host your static pages (more on that later). Most of these cloud-based options can be utilized for free with limited traffic and processing power.

Back to GitHub. With a combination of Jekyll and GitHub Pages, you can host a static site or blog for free on GitHub. You can even have your custom domain point there. The simplicity of this solution is appealing to me. There is no database, no server-side code, and no server configuration or complexity. You just have a bunch of static files in a special Git repository. For dynamic content (such as a blog), you create markdown files that will get converted to static html by Jekyll. The added bonus is that your site is served up as static content, eliminating time consuming server side processing on each request. Anyway, I’ve yet to pursue this path, but it’s the most appealing option at this time.

As for this blog… Given the rise of social networks in the past few years, I’m not sure that “blogging” things is the best use of time for me. The original intent of this blog was to share things with family and friends, but that function has been replaced by better tools. So, I’d expect that new blog posts will be infrequent.

Using cookies with HttpClient

This simple code snippet shows how to store and use cookies from a web request using the .Net HttpClient. For example, if an API or site sends a token or authentication cookie, you may need to store it and send it on all subsequent requests to show that you are authenticated. This would be for a session-based service. The key is to create a single CookieContainer instance and a single HttpClientHandler instance to hold it. Assume the following class is registered as a singleton.

public class WebClient
{
    private CookieContainer _cookieContainer;
    private HttpClientHandler _handler;
 
    private HttpClientHandler Handler
    {
        get
        {
            if (_handler == null)
            {
                _cookieContainer = new CookieContainer();
                _handler = new HttpClientHandler { CookieContainer = _cookieContainer, UseCookies = true, AllowAutoRedirect = false };
            }
            return _handler;
        }
    }
 
    private HttpClient GetClient()
    {
        // the second param prevents the Handler from being disposed with the client
        var client = new HttpClient(Handler, false);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }
 
    public async Task Get<T>(string path) where T : class
    {
        using (var client = GetClient())
        {
            var content = await client.GetStringAsync(path);
            return JsonConvert.DeserializeObject<T>(content);
        }
    }
}

Trying out Windows Live Writer

Scott Hanselman has been trumpeting Windows Live Writer for some time now.  I’ve been hesitant to try it out because I’m a control freak and I was convinced that Live Writer wouldn’t do things correctly.  Well, he blogged about it again today so I’m giving it a try (with this post).  It was the comments on his post that swayed me.

Live Writer has improved quite a bit since last time I tried it.  It actually pulled down my WordPress theme in order to provide a themed preview, which isn’t perfect, but it’s good enough to get an idea.  Adding categories and tags is really simple, with type-ahead suggestions from previous posts.  It looks like it has some powerful picture, video and map embedding tools, which I will try eventually.

The thing I’m most curious about is embedding code snippets.  It looks like all of the syntax highlighting plugins are 2+ years old.  Update: I tried a couple of them and they both resulted in an awful looking table.

Last.fm Recent Tracks with AngularJS

AngularJS is an MVC framework for javascript. It is best suited for round-tripping resources with a RESTful service. In this post, I will simply get a list of recent tracks from Last.fm, treating each track as a resource. The Last.fm API is documented here. There is no round-tripping in this example. I’ll also be utilizing Twitter Bootstrap for layout.

To start, create the AngularJS application and a controller for recent tracks. Since this is a simple application, there are no routes and views. The controller will be invoked inline on the main page. Routes and views are easily added once you get a handle on the framework.

'use strict';
 
var LastFmApp = angular.module('lastfm-app', []);
 
LastFmApp.controller('RecentTracksController',
    function RecentTracksController($scope, $http) {
        var url = 'http://ws.audioscrobbler.com/2.0/';
        var params = {
            method: 'user.getrecenttracks',
            api_key: 'your_api_key',
            limit: 12,
            user: 'user_name',
            format: 'json'
        };
        $http.get(url, { params: params })
            .success(function (data) {
                $scope.songs = data.recenttracks.track;
            })
            .error(function (data, status) {
                console.log(data || "Request failed");
                console.log(status);
            });       
    });

The HTML (simplified for brevity).

<!DOCTYPE html>
<html lang="en" ng-app="lastfm-app">
<head>
    <meta charset="utf-8">
    <title>Recent Tracks</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-responsive.min.css">
</head>
<body>
    <div class="container" ng-controller="RecentTracksController">
        <ul class="thumbnails">
            <li class="span4" ng-repeat="song in songs">
                <a class="thumbnail" href="{{song.url}}" title="{{song.artist['#text']}} - {{song.name}}" style="display: block;">
                    <div class="media">
                        <div class="pull-left" href="#">
                            <img class="media-object" src="{{song.image[2]['#text']}}">
                        </div>
                        <div class="media-body">
                            <strong>{{song.artist['#text']}}</strong><br />
                            {{song.name}}<br />
                            <em>{{song.date['#text']}}</em>
                        </div>
                    </div>
                </a>
            </li>
        </ul>
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="lib/bootstrap/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
    <script src="js/main.js"></script>
</body>
</html>

The resulting grid will look something like this:

Recent Tracks

Thumbnail Gallery with Flickr, Bootstrap, and Javascript

I recently created a thumbnail gallery of my latest Flickr photos using the Flickr feeds API, Twitter Bootstrap, and Javascript/jQuery.  There is no server side code for this solution, and the client side code is really simple.  To start, create a blank html page (I like to start with the HTML5 Boilerplate).  Make sure you include the Bootstrap css and jQuery.  I used the Thumbnails component of Bootstrap for the gallery layout.  Here’s the div to hold the thumbnails:

<div class="row">
    <div class="span16">
        <ul class="thumbnails" id="my-photos">
        </ul>
    </div>
</div>

Here’s the javascript to fetch the photos and populate the div. For this example, I’m displaying the pdx group pool photos.

// see the list of feeds here - http://www.flickr.com/services/feeds/
// this is a handy tool to get people and group ids - http://idgettr.com/
$(document).ready(function () {
    var flickrFeedUrl = "http://api.flickr.com/services/feeds/groups_pool.gne?id=35468135854@N01&lang=en-us&jsoncallback=?";
    $.getJSON(flickrFeedUrl, { format: "json" },
        function (data) {
            $.each(data.items, function (i, item) {
 
                // build some elements and then append them accordingly
                var li = $("<li>").attr("class", "span2");
                var a = $("<a>").attr("href", item.link).attr("class", "thumbnail").attr("title", item.title);
                // we want the larger square (150px) thumbnail instead of the smaller one (75px)
                var img = $("<img/>").attr("src", item.media.m.replace("_m.jpg", "_q.jpg"));
                img.appendTo(a);
                a.appendTo(li);
                $("#my-photos").append(li);
 
                // stop at 18 photos (i is 0 based)
                if (i == 17) return false;
            });
      });
});

That’s it. This minimal amount of client side code produces a nice, responsive gallery of thumbnail links to Flickr photos.

Edit 12/31/2012: I am now using mustache.js for templating, which is much more elegant than building the html via js.

Project – La Cocina

I’ve been working on a new Rails application for storing our recipes. It’s at a point where it is being hosted and used by us. Some of the style is borrowed (stolen) from Martha Stewart’s blog.

The big feature of La Cocina is it’s ability to pull in recipes from a number of other recipe sites.  I’m using the nokogiri gem to do screen scraping for recipe data.  There’s an admin interface for creating new screen scrapers (which I call “scarfers”), so it’s easy to add new recipe sites by entering DOM paths (CSS or XPath) and some other options.  With one click of a bookmarklet on a supported site (we have 5 configured so far), the recipe is in our database.

Other stuff in use: kaminari for pagination, paperclip for image attachments (including fetching from a URL, resizing, and generating thumbnails), acts-as-taggable-on for tagging, SASS for CSS, Twitter Bootstrap for some design and layout, MySql as the database, and miscellaneous jQuery for client-side things.

There are a few things left for me to do.  For one, I want to make it a true multi-user site so I can share it or create a demo account for showing it off.

Show SVN revision number in a Rails application

This is a hack to display the Subversion revision in a Rails application using Capistrano to insert the current revision number on each deploy.

Create a partial that will contain the revision number. For example, ~/app/views/layouts/_revision.html.erb. You can put anything in that file, as it will be overwritten by Capistrano on each deploy. The word “Development” or “Current” seems a good choice.

In the page where you want to display the revision number (probably in the application layout), render the partial. In development mode, you’ll see something like “version 1.0.Development”. In your deployment environment, you’ll see the SVN revision number, like so: “version 1.0.504”.

version 1.0.<%=render :partial => 'layouts/revision'%>

To set up Capistrano, edit the ~/config/deploy.rb file (assuming you are already using Capistrano for deployments). Add a task to get the SVN version and write that to your revision partial. For some reason, pointing to the “/current” directory doesn’t work – probably because of the way Capistrano links directories. Therefore, just point SVN to any subdirectory or file to get the version.

desc "Write current revision to app/layouts/_revision.rhtml"
task :publish_revision do
  run "svnversion #{deploy_to}/current/app > #{deploy_to}/current/app/views/layouts/_revision.html.erb"
end

And tell Capistrano to run this task just before restarting the application:

before 'deploy:restart', 'publish_revision'

FizzBuzz one-liner in C#

FizzBuzz: Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Reference

Console.WriteLine(String.Join(Environment.NewLine, Enumerable.Range(1, 100)
    .Select(i => (i % 3 == 0) ? new { n = i, w = "Fizz" } : new { n = i, w = "" })
    .Select(o => (o.n % 5 == 0) ? new { n = o.n, w = o.w + "Buzz" } : o)
    .Select(o => o.w == "" ? o.n.ToString() : o.w)));

jQuery Autocomplete and Rails

This is an example of how I used the jQuery Automcomplete Widget with Rails 3.2 for a recipe search field. Some of the jQuery stuff mentioned below is included out of the box with a new Rails application.

  • Make sure the jQuery gem is referenced in the Gemfile
gem 'jquery-rails'
  • Include the jQuery javascripts in app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ui
  • Download one of the jQuery-ui css files, or a custom one, and put it in one of you asset locations. I put mine in vendor/assets/stylesheets/jquery-ui-1.8.18.custom.css. Include the css file in app/assets/stylesheets/application.css
*= require jquery-ui-1.8.18.custom.css
  • Create a controller action to search and return values for the autocomplete dropdown menu. In my Recipes controller (you could also create a seperate Search controller), I created an Action to return a list of matching recipe titles as a json array. The search can also be applied to recipes in a single category, hence the category_id parameter.
  def search_on_title
    # search_on_title is a method on the model to do a wildcard search on keyword
    recipes = Recipe.search_on_title(params[:term], params[:category_id])
    render json: recipes.map(&:title)
  end
  • Add a route for the search_on_title action.
  resources :recipes do
    get 'search_on_title', :on => :collection
  end
  • The search form is just a normal form.
  <%= form_tag '', :method => :get do %>
	<%= search_field_tag :term, params[:term], :class=> "input-large" %>
	<%= submit_tag "Filter", :name => nil, :class => 'button btn', :id => "search_bn" %>
  <% end %>
  • The javascript to hook up the autocomplete functionality looks like this. Notice the extra parameter to the source url – that’s how you would pass multiple values to your filter.
$("input#term").autocomplete({
    source: '<%=search_on_title_recipes_path%>?category_id=<%=params[:category_id]%>',
    minLength: 2, delay: 500
});

There’s also a Rails gem to make autocomplete easier, but I found this to be easy enough such that I didn’t have to depend on an additional plugin.

WCF Client and the “using” Statement

As I was researching patterns and practices for a WCF client implementation, I came across a bug in the .Net implementation of ClientBase<T> (whether it’s actually a bug is arguable). It’s well documented on the web, but it could cause major headaches if you happened to miss it.

The core of the issue is that ClientBase<T> implements IDisposable. With this knowledge, just about any programmer would naturally wrap its usage in a using{} block. Digging deeper, you’ll find that the ClientBase<T> Dispose() method simply calls Close() on the underlying connection. This is problematic because in certain connection states (such as “Faulted”), the Close() will fail. As I said, this is well documented elsewhere, for example: on MSDN, Stack Overflow, and here.

There are a few different solutions to this issue. I went with a simple Disposable wrapper…

// Get a disposable MyClientWrapper object
using(var clientWrapper = ClientFactory.GetMyClientWrapper())
{
    clientWrapper.Client.DoSomething();
}
 
public class MyClientWrapper : IDisposable
{
    private readonly MyClient _client;
 
    public MyClientWrapper(Binding binding, Uri endpoint)
    {
        // creates an instance of MyClient, which is derived from ClientBase<T>
        _client = new MyClient(binding, new EndpointAddress(endpoint.ToString()));
    }
 
    public MyClient Client
    {
        get { return _client; }
    }
 
    public void Dispose()
    {
        // safe dispose with extension method (below)
        _client.CloseProxy();
    }
}
 
// extension method for safe Close() on ClientBase<T>
public static void CloseProxy(this ClientBase<T> proxy) where T : class
{
    try
    {
        if (proxy.State != CommunicationState.Closed 
                && proxy.State != CommunicationState.Faulted)
        {
            proxy.Close(); // may throw exception while closing
        }
        else
        {
            proxy.Abort();
        }
    }
    catch (CommunicationException)
    {
        proxy.Abort();
        throw;
    }
}