Tuesday, 2 July 2013

Oh Twitter...

I just realised, that the code in my previous posts about Twitter plugins is broken.
This is because Twitter has switched off the API v1. This means, all applications using it (and using my example code) have stopped working.

There is a relatively easy solution using the great TweetSharp package. It works very well (apart from a very minor formatting issue) and is pretty easy to use, which you will see in this post.

1. What you need

First of all you need a few keys from Twitter. Namely a ConsumerKey, a ConsumerSecret, an AccessToken and an AccessTokenSecret. You can get all this in your Twitter developer login area. I'm not sure, why it has to be quite so complicated, but that's how it is.

Next, you need the TweetSharp package which you can install via your NuGet package manager.

2. Get some tweets

The complicated part is over, the rest is smooth sailing. This is the code to get some tweets:
var api = new TwitterService("myConsumerKey", "myConsumerSecret");
api.AuthenticateWith("myAccessToken", "myAccessTokenSecret");

var tweets = api.ListTweetsOnUserTimeline(
  new ListTweetsOnUserTimelineOptions()
    ScreenName = "tkglaser",
    Count = 3,
    IncludeRts = true
This retrieves the last 3 Tweets (including Re-Tweets) from my timeline.

3. Display them

All that is left to do is stick the Tweets into your MVC model and display them in a view. This is quite easy as well:
  @foreach (var tweet in Model.Tweets)

4. Done

That's it, hope it all works for you as easily as it worked for me. I'll put up a little example as well at some point, or at least repair the old examples.

Sunday, 23 December 2012

Conway's Game Of Life in 3D (version 2)

Following up on my previous post, I've had another play with three.js, trying to push it a little more. I've allowed the organism to grow into a 3D grid, added some random cube colours, lighting and shadows:

You can:
Run the demo
View the complete source

1. Take Conway to the 3rd dimension

First, I wanted to allow the Conway organism to grow into the 3rd dimension. There are many suggested rule sets for this throughout the internet. But in order to see a continuously growing organism, I left the 2D rules unchanged. The grid has been extended to 20x20x20.

2. Advanced lighting and shading

In order to add some more interesting lighting, I've added some spotlights:
light = new THREE.SpotLight(0xff170f, 1);
light.position.set(0, 500, 2000);
light.castShadow = true;

light2 = new THREE.SpotLight(0xffcf0f, 1);
light2.position.set(0, -400, -1800);
light2.castShadow = true;
A spotlight is a point-light that can cast a shadow. I've also enabled shadows in the renderer:
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.sortObjects = true;
renderer.setSize(window.innerWidth, window.innerHeight);

renderer.shadowCameraFov = camera.fov;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapDarkness = 0.5;
renderer.shadowMapWidth = renderer.shadowMapHeight = 2048;

renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;

3. Done

That's it, feel free to have a look at the demo or read the code. This demo will only work in WebGL browsers as I couldn't get the lighting to run in a HTML 5 canvas.

By the way there is another example of this on chromeexperiments.com.

Friday, 21 December 2012

Conway's Game of Life in 3D using HTML 5 canvas and ThreeJS

This article looks at implementing Conway's Game Of Life in 3D in your browser. If you're not too interested or already familiar with Conway's Game Of Life, feel free to skip ahead to the 3D section. Here is a screen shot of the finished version:

Or go to the demo page to see it in action.

1. Conway's Game Of Life

Conway's Game Of Life is one of the most fascinating mathematical games I know. It demonstrates, how a simple starting point and simple rules can create a very complex scenario. Also, it is great for demos, as it is fairly easy to implement.

This tutorial demonstrates, how to implement a version of Conway's Game Of Life using JavaScript and visualise it in 3D using a HTML 5 Canvas and ThreeJS.

ThreeJS is an open source JavaScript library that can be used to render 3D scenes in most HTML 5 compatible browsers. At the end of this tutorial, we will have something like this (select WebGL or Canvas version):


Conway's Game Of Life (CGOL) in JavaScript

As I said above, the implementation of CGOL is manageable even for a JS newbie like me.

First, we need a grid:
var grid;
var gridold;
var gridmax;

function initGrid() {
  gridmax = 100;
  grid = new Array(gridmax);
  for (var i = 0; i < gridmax; i++) {
    grid[i] = new Array(gridmax);
    for (var j = 0; j < gridmax; j++) {
      grid[i][j] = false;
This initialises a 2-dimensional array of 100x100 booleans.

Next, we seed the initial fields on the grid. I'm using the F-Pentomino, but feel free to use any shape you like.

function seedLife() {
  var h = gridmax / 2;
  grid[h][h - 1] = true;
  grid[h][h] = true;
  grid[h][h + 1] = true;
  grid[h - 1][h] = true;
  grid[h + 1][h - 1] = true;
All that remains is the function, that calculates the next "generation" on the board. The rules are:

  • A cell survives if it has 2 or 3 neighbours
  • A cell is born if it has 3 neighbours
  • Otherwise, a cell dies or remains dead

function stepConway() {
  gridold = grid;
  for (var i = 1; i < gridmax - 1; i++) {
    for (var j = 1; j < gridmax - 1; j++) {
      var neighbours = 0;

      if (gridold[i - 1][j - 1]) neighbours++;
      if (gridold[i][j - 1]) neighbours++;
      if (gridold[i + 1][j - 1]) neighbours++;

      if (gridold[i - 1][j]) neighbours++;
      if (gridold[i + 1][j]) neighbours++;

      if (gridold[i - 1][j + 1]) neighbours++;
      if (gridold[i][j + 1]) neighbours++;
      if (gridold[i + 1][j + 1]) neighbours++;

      grid[i][j] = (neighbours == 3) || 
        ((neighbours == 2) && gridold[i][j]);

2. Visualisation using Three.js

This is the slightly more difficult step. I wanted to have a 3D view onto a slowly rotating board, where the CGOL "creature" evolves. One way of doing this is using Three.js. This allows us to define a scene in a very general way and leave the rendering to the library. At the end of this, it will look something like this (select the appropriate version for your browser):


Initialising three.js and preparing the scene

Let's start by referencing and initialising three.js:
<script src="~/Scripts/three.min.js"></script>
var container;
var camera, scene, renderer;
var directionallight;
var cubegeometry;
var cubematerial;
var linegeometry;
var linematerial;
var ambientLight;
var lastStep = Date.now();
var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

function preInit() {
  container = document.createElement('div');

  camera = new THREE.PerspectiveCamera(
    45, window.innerWidth / window.innerHeight, 10, 5000);

  camera.position.x = 200;
  camera.position.y = 500;
This creates a perspective camera and places it at a point above the grid I am about to create.
// Grid
  var size = gridmax * 25, step = 50;

  linegeometry = new THREE.Geometry();

  for (var i = -size; i <= size; i += step) {
    linegeometry.vertices.push(new THREE.Vector3(-size, 0, i));
    linegeometry.vertices.push(new THREE.Vector3(size, 0, i));

    linegeometry.vertices.push(new THREE.Vector3(i, 0, -size));
    linegeometry.vertices.push(new THREE.Vector3(i, 0, size));

  linematerial = new THREE.LineBasicMaterial({ 
    color: 0x000000, 
    opacity: 0.2 
The grid is a series of horizontal and vertical black lines.
// Cubes
  cubegeometry = new THREE.CubeGeometry(50, 50, 50);
  cubematerial = new THREE.MeshLambertMaterial({ 
    color: 0xffffff, 
    shading: THREE.FlatShading, 
    overdraw: true 

Here, a cube is defined. This cube will be the template for all cubes in the scene. The cube itself is white, so the colour it appears in is determined entirely by the light source(s).
// Lights

  ambientLight = new THREE.AmbientLight(Math.random() * 0x10);
First, some ambient light. This illuminates all cubes evenly and has a random but very dim colour.
directionalLight = new THREE.DirectionalLight(
    Math.random() * 0xffffff);
  directionalLight.position.x = Math.random() - 0.5;
  directionalLight.position.y = Math.random() - 0.5;
  directionalLight.position.z = Math.random() - 0.5;
A directional light is comparable with sunlight. It arrives at a scene from a specific direction which is equal throughout the scene. Much like a light source that is very far away. The colour of this directional light source is random and so is the initial direction.
Now, all that is left to do is to create the renderer. In this example, I'm using a CanvasRenderer, which is the most compatible solution. There are other renderers available but they are less widely supported.
renderer = new THREE.CanvasRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);


    'mousemove', onDocumentMouseMove, false);

    'resize', onWindowResize, false);

As you can see, the last snippet registers some event listeners.
function onWindowResize() {
  camera.left = window.innerWidth / -2;
  camera.right = window.innerWidth / 2;
  camera.top = window.innerHeight / 2;
  camera.bottom = window.innerHeight / -2;


  renderer.setSize(window.innerWidth, window.innerHeight);

function onDocumentMouseMove(event) {
  mouseX = (event.clientX - windowHalfX);
  mouseY = (event.clientY - windowHalfY);
These event listeners are not very exciting, they simply adjust the camera if the browser window is resized and record the current mouse position.

Let's get rendering

First we need a function that creates our Three.js scene. A scene is the object passed to the renderer later and contains everything to be rendered.
function buildScene() {
  scene = new THREE.Scene();
  var sceneline = new THREE.Line(linegeometry, linematerial);
  sceneline.type = THREE.LinePieces;
  for (var i = 0; i < gridmax; i++) {
    for (var j = 0; j < gridmax; j++) {
      if (grid[i][j] == true) {
        var cube = new THREE.Mesh(cubegeometry, cubematerial);
        cube.scale.y = 1;

        cube.position.x = i * 50 - gridmax * 25 + 25;
        cube.position.y = 25;
        cube.position.z = j * 50 - gridmax * 25 + 25;

This function creates the scene object by bundling up all materials, geometries and light sources we created earlier. Int also iterates through the Conway grid and adds a cube for every living cell at the appropriate position. Now, this scene needs to be rendered.
function render() {
  if (Date.now() - lastStep > 200) {
    lastStep = Date.now();
  var timer = Date.now() * 0.00005;

  timer += mouseX * 0.001;

  camera.position.x = Math.cos(timer) * 2000;
  camera.position.z = Math.sin(timer) * 2000;
  camera.position.y += (-mouseY - camera.position.y) * 1 + 1000;

  directionalLight.position.x = camera.position.x;
  directionalLight.position.y = camera.position.y;
  directionalLight.position.z = camera.position.z;

  renderer.render(scene, camera);
The render function does a number of things.

Firstly, if 200ms have passed, buildScene() and stepConway() are invoked. This moves the conway grid one generation forward and rebuilds the scene.

Secondly, a timer variable is created based on the current time and mouse position. This timer variable is then used to rotate the camera around the centre of the scene. The camera moves on a circle of 2000 units radius around the scene, always looking at the centre. As time moves forward, the camera's angle changes accordingly.

Thirdly, the directional light source uses the camera's position as it's direction. This creates the effect of the light source moving with the camera, so all faces of the cubes are the brightest, when they directly face the camera. The last thing to do is to request an animation frame, so the render function is called continuously.
function animate() {


Now you should have a spinning grid with a Conway life form evolving on it.

Full code listing on Github

If you have any questions, notes, or corrections, please feel free to leave a comment below.

Wednesday, 19 December 2012

Keep your Appharbor site alive using your old Linux box

Appharbor.com is a great service. It allows you to create an ASP.NET web app using MVC 4 or other versions of ASP and configure it, so that a simple commit to a github(*) repository automatically compiles and deploys your app to appharbor. I might write up an article on how to do this at some point.

One thing I noticed is that after 20 minutes of inactivity, your application is being stopped on the server and the next access can take a bit longer as it needs to be restarted. With my demo app tkglaser.apphb.com the initial load time could be up to 20s. This is normal IIS behaviour.

One possible solution is to continuously ping your app to simulate activity. As the linked article suggests, this can be done by using paid services such as Pingdom or StillAlive.

If you have (like me) a little Linux box at home, which is running all the time, there is a much simpler and cheaper solution. You can set up a cron job and use curl to retrieve a page from your app every minute. Here is how to do it:
  1. Become root: 
    sudo su -
  2. Edit your crontab: 
    crontab -e
  3. Add this line: 
    * * * * * curl mywebsite.apphb.com
  4. Save and close

You can check that it's working by watching the syslog:

tail -f /var/log/syslog

Disclaimer: Some commands might be subtly different depending on your flavour of Linux. I'm using Ubuntu.

Pinging the app every minute might be a bit of a brute force solution but it worked perfectly for me, no more waiting times after some inactivity.

(*) Appharbor supports other services as well, not just github. Go to appharbor.com to learn more.

Sunday, 16 December 2012

Custom Twitter Feed on your MVC 4 Layout Page

As a follow-up to this post, I needed to get the home-made Twitter feed onto the layout page of our MVC 4 app. Like this:


The problem is that the layout page has no model and no code-behind. Since the Twitter feed is populated in code-behind on the server, this is a problem.

The answer is a PartialView populated by a ChildAction.

1. The Model

The Model remains unchanged from the original implementation.

2. The Controller

Change the Action that retrieves the tweets and populates the model to be a ChildAction returning a PartialView.

public PartialViewResult Tweets()
  RestClient client = new RestClient("http://api.twitter.com/1");
  // [...] see original post for full implementation
  model.Tweets =

  return PartialView(model);

3. The View

For the View, create a new partial view displaying the tweets.
@model net.tkglaser.demos.Models.TwitterFeed.LandingModel

  @foreach (var tweet in Model.Tweets)
      <img src="@tweet.user.profile_image_url" />
Now, you can simply insert the tweets into the layout, or anywhere else using this line:

This enables you to put your Twitter feed into the layout so every page will display it.

As always, please feel free to leave a comment if you find this useful or have a suggestion.

Friday, 7 December 2012

A Simple Twitter Feed in MVC 4 Using The RESTful Twitter API

If you want to include a Twitter feed into your web site, one option is to use the standard Twitter widget, which looks something like this:
In many cases, this will be good enough. But you might want to embed your Twitter messages more organically into your page so it fits in with the overall look and feel. In that case, you would want to call the Twitter API and display the tweets yourself. This little tutorial shows, how to do exactly that in ASP MVC 4.    Here is a demo app that shows the finished result:


1. The Model

As always in MVC, it starts with the model. The model reflects the Twitter API model for a tweet, which is not as straightforward as one might think.

Note: I am using the Twitter 1.0 API although it is deprecated. This is because you don't need an API key and I was too lazy to get one for API 1.1.

Here is my C# model for a tweet. It only contains the fields I'm interested in for this particular demo.
public class User
  public string profile_image_url { get; set; }

public class Url
  public string url { get; set; }
  public string expanded_url { get; set; }
  public string display_url { get; set; }

public class Entity
  public List<Url> urls { get; set; }

public class Tweet
  public string created_at { get; set; }
  public string text { get; set; }
  public User user { get; set; }
  public List<Entity> entities { get; set; }

public class LandingModel
  public List<Tweet> Tweets { get; set; }

2. The Controller

Next is the code to call the Twitter API. To do this, I've installed the RestSharp nuget package into my project.
RestClient client = new RestClient("http://api.twitter.com/1");
JsonDeserializer jsonDeserializer = new JsonDeserializer();
var model = new LandingModel();

var request = new RestRequest(Method.GET);

request.Resource = "statuses/user_timeline.json";

request.Parameters.Add(new Parameter() { 
  Name = "screen_name", 
  Value = "tkglaser", 
  Type = ParameterType.GetOrPost });

request.Parameters.Add(new Parameter() { 
  Name = "count", 
  Value = 10, 
  Type = ParameterType.GetOrPost });

request.Parameters.Add(new Parameter() { 
  Name = "include_rts", 
  Value = true, 
  Type = ParameterType.GetOrPost });

request.Parameters.Add(new Parameter() { 
  Name = "include_entities", 
  Value = true, 
  Type = ParameterType.GetOrPost });

var response = client.Execute(request);

model.Tweets =
Most parameters are probably self-explanatory. The include_entities one is important for expanding shortened links in tweets, but I'll get to that.

3. The View

Now that you have the data, you can render and format it any way you like. For instance like this:
<h1>My Latest Tweets</h1>
  @foreach (var tweet in Model.Tweets)
      <img src="@tweet.user.profile_image_url" />
This should compile and work. There is just one little thing, links in the text are not links:
  • Microsoft expands social network http://t.co/AhMIaE6D

4. Repairing the links

This is where the url entities come in. If you expand the tweet model like this:
public class Tweet
  public string created_at { get; set; }
  public string text { get; set; }
  public string GetTextWithLinks()
    var result = text;

    foreach (var entity in entities)
      foreach (var url in entity.urls)
        result = result.Replace(
          string.Format("<a href='{0}'>{1}</a>",

    return result;
  public User user { get; set; }
  public List<Entity> entities { get; set; }
Then, slightly adapt the view:
  <img src="@tweet.user.profile_image_url" />
The tweet should now look like this:

That's it, you can now style and embed your Twitter feed in any way you like. It should look something like this:


As always, please leave a comment if you found this useful or have improvement suggestions.

Tuesday, 4 December 2012

Twitter Bootstrap MVC 4 remove body padding in mobile view

Just a little pitfall I came across today. If you are using Twitter Bootstrap in ASP MVC 4, you might have the same problem.

The Problem

If viewed in desktop mode, my page looks something like this:
Nothing unusual, there is a top nav bar and it is where is should be. Now, if I resize the browser, the page goes into mobile mode and looks like this:
Suddenly, there is a 60px high white space above the nav bar, which looks very much broken.

To complete the picture, here is the code in the layout:
  body {
    padding-top: 60px;
The body padding is required because otherwise the top nav bar covers a portion of the body in desktop view.

As you might have guessed by now, the body padding is also the culprit for the ugly white gap in mobile mode.

Bootstrap has a solution for this by providing a separate responsive css file which overrides the body padding in mobile mode. You need to reference the responsive css after your body padding. Unfortunately, the nuget package bundles the two css files together:
  .Add(new StyleBundle("~/Content/bootstrap")
This means, you can't call the css files separately using the MVC 4 @Styles.Render() command.

The Solution

This is only one possible solution. If there is a simpler one, please drop me a comment below.

First, rip the bundle apart in BootstrapBundleConfig.cs:
  .Add(new StyleBundle("~/Content/bootstrap")
  .Add(new StyleBundle("~/Content/bootstrap-responsive")
Then change your layout to reference the css files in the correct order:
  body {
    padding-top: 60px;
That should do the trick, the white padding in mobile mode is gone and the nav bar does not cover a part of the body in desktop mode.

As always, please feel free to leave a comment if you find this useful or have an improved solution.