LINQ: FirstOrDefault without the null check afterwards.

So, I was considering a problem I had that called for a LINQ statement that contains a FirstOrDefault() call. If there was an object returned I wanted a string property from it. If not, then I wanted to use a string.Empty.

I’ve often just caputured the result of the LINQ statement, checked for null, and if I had an object I’d call the property.

e.g.

var number = numbers.FirstOrDefault();
string firstNumberCaption = string.Empty;
if (number != null)
    firstNumberCaption = number.Caption;
Console.WriteLine("The first number is {0}", firstNumberCaption);

However, that code is a bit convoluted, and it occurred to me that there would be a better way of doing this.

The pure LINQ way

What if I called Select before the FirstOrDefault() to get the value of the property that I wanted. That way I don’t have to worry about implementing my check.

var firstNumber = numbers
    .Select(n => n.Caption)
    .FirstOrDefault();

And if I am desperate for the resulting string to be the empty string I can always append ?? string.Empty onto the end, like this:

var firstNumber = numbers
    .Select(n => n.Caption)
    .FirstOrDefault() ?? string.Empty;

If you are not familiar with the ?? (null-coalescing) operator you can find out more on MSDN.

Optimisation

My next concern was that perhaps it will convert every instance in the enumerable that was passed to LINQ before discarding them all but the first one. However, that doesn’t happen. For example, the following code only outputs one thing:

var firstNumber = numbers
    .Select(n =>
    {
        Console.WriteLine("Select {0} / {1}", n.Value, n.Caption);
        return n.Caption;
    })
    .FirstOrDefault() ?? string.Empty;

Filtering

I often put filters in my calls to FirstOrDefault(), and most of the time it is a filter on something other than what I’m returning in the Select part of the statement. Obviously, if we are performing the Select first, then the filter is not going to work if it is looking for data that is no longer there. In this case we just insert a Where statement just before the select to ensure that the filtering does happen.

So, for example, the first number in the sequence greater than 2:

var firstNumberCaption = numbers
    .Where(n => n.Value > 2)
    .Select(n => n.Caption)
    .FirstOrDefault() ?? string.Empty;

Console.WriteLine("The first number is {0}", firstNumberCaption);

Full program

Here is the full program (using the last example) if you want to see everything that is going on.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Number
    {
        public Number(int value, string caption)
        {
            Value = value;
            Caption = caption;
        }

        public int Value { get; set; }
        public string Caption { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Number[] numbers =
                {
                    new Number(1, "One"),
                    new Number(2, "Two"),
                    new Number(3, "Three")
                };

            var firstNumberCaption = numbers
                .Where(n => n.Value > 2)
                .Select(n => n.Caption)
                .FirstOrDefault() ?? string.Empty;

            Console.WriteLine("The first number is {0}", firstNumberCaption);

            Console.ReadLine();
        }
    }
}

Aberdeen Developers – Introduction to Parallelisation

Examples

Here are all the examples from Thursday evening’s introductory talk on Parallelisation at the Aberdeen Developers User Group.

Slide Deck

You can download the slide deck here.

JsRender looping, nested objects, and conditional statements.

So far, I’ve posted a couple of very basic introductory posts on JsRender. In this post, I’ll get a little bit more into the meat of the templating language and show looping, conditional statements, and some other bits and pieces.

In the example, I’ve put together a supermarket receipt. It shows the items bought, their quantities and any savings from offers. Here’s the data:

var theReceipt =
  {
    items:
      [
        {
          description:"800g Wholemeal Bread",
          quantity:2,
          price:1.05,
          offer: {qty_needed:2, price:1.90}
        },
        {
          description:"Kellog's Fruit & Nut",
          quantity:1,
          price:2.69
        },
        {
          description:"2 litres Semi-skimmed Milk",
          quantity: 3,
          price:1.18,
          offer: {qty_needed:3, price:3.00}
        },
        {
          description:"1 litre Pineapple Juice",
          quantity:2,
          price:1.10
        }
      ],
      total: 9.79,
      saving: 0.74
  };

The data contains an array of items, each of which contains the the description, quantity, and price of each item. On some items there is also details of any offer. There is also the precomputed total and the saving that the customer has made.

Looping

In the previous post I showed what happens when the object you pass JsRender is an array. But what if the data contains an array as some sub-element? In that case you can use the for tag followed by the name of the array to indicate the start of the loop (and which array to loop over). At the end of the loop repeat the tag but with a slash in front of it (rather like HTML). For the data above, it would look like this:

{{for items}}
  Put repeating template here
{{/for}}

The tags inside the for block will be for current element. So, for the items above, I could use tags such as description, quantity, and so on.

Conditional statements

You can render parts of a template conditionally if you like. You can use the if tag to do that. Again at the end of the block, you put the slash in front of the tag to indicate its end.

{{if some_condition}}
  Put template to render if true here.
{{else some_other_condition}}
  Put template to render here if the second condition is true.
{{else}}
  Put template to render here if previous conditions are false.
{{/if}}

In the example, the test is whether the offer object exists or not. However, it acts just like an if conditional statement works in javascript. So if offer evalates to false, zero, etc. then it will be regarded as false, other values are regarded as true.

{{if offer}}
  <tr>
    <td></td>
    <td><em>{{:offer.qty_needed}} for £{{:offer.price}}</em></td>
    <td><em>save:</em></td>
    <td><em>£{{:offer.price - (quantity * price)}}</em></td>
  </tr>
{{/if}}

Nested object

In the looping section you can access the elements of each item being iterated over. The looping mechanism takes care of that for you, so when you are in the loop each tag is an element of the current item.

You can, as you can see in the conditional statements section above, also see that you can use the standard dot-notation to access nested elements. In this case the elements in the offer object.

Calculations

In the conditional statements section you can see some basic calculations.

{{:offer.price - (quantity * price)}}

The result of the calculation will be rendered to the page.

Rendering options

You will have noticed that templating statements are all in two braces. Where something is rendered the initial opening braces are followed by a colon. This simply outputs the results directly on to the page. This is great if the output is safe (or it is HTML), however if you want to ensure that the output is correctly encoded for a web page you can use a right-cheveron.

  {{:some_html_to_be_rendered}}
  {{>some_text_to_be_escaped}}

The example

The example for this post can be found here. You are encouraged to view the source of the example.

JsRender and arrays

Previously, I showed how to very quickly get up and running with JsRender witha very simple hello world demonstation. In this post I’ll be extending things a little further showing you how simple arrays of data are handled.

For this demo I have an array of data representing photos from my flickr account. This is what the data looks like:

var thePhotos =
  [
    {
      "title":"Forth Road Bridge",
      "thumbnail":"http://farm1.staticflickr.com/1/2843652_f542c664ed_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2843652/in/photostream"
    }, {
      "title":"Forth Bridge",
      "thumbnail":"http://farm1.staticflickr.com/1/2843680_58c5c8003b_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2843680/in/photostream"
    }, {
      "title":"Helmsdale",
      "thumbnail":"http://farm1.staticflickr.com/4/5441773_2929a2ebdf_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/5441773/in/photostream"
    }, {
      "title":"Scottish Parliament",
      "thumbnail":"http://farm1.staticflickr.com/3/6340272_0e7ad78251_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/6340272/in/photostream"
    }, {
      "title":"Space Needle",
      "thumbnail":"http://farm3.staticflickr.com/2013/2410201132_356ff1a147_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2410201132/in/photostream"
    }
  ];

The template defines how to render a single element in the array. There is also a special token available {{:#index}} which allows you to get the index value into the template. In the example below, I’m adding one to it in order to put a sensible number next to the photo.

As you can also see, you can place template placeholders in many places, includeing inside attributes in HTML elements.

The template looks like this:

<script id="photosTemplate" type="text/x-jsrender">
  <div class="photoFrame">
    <span class="index">{{:#index+1}}</span>
    <a class="photoLink" href="{{:url}}">
      <span class="photoTitle">{{:title}}</span>
      <img class="photo" src="{{:thumbnail}}" alt="{{:title}}"/>
    </a>
  </div>
</script>

The code to render the template and add it to the page is pretty much the same as last time.

I’ve also put together a full example to look at, feel free to look at the source of this page.

JsRender …. starter for 10

I was going to look at jQuery Templates recently, but then I discovered they have been discontinued. Which is a real pity as I saw a demonstration at a conference about a year ago and they looked rather promising. However, there are other similar projects out there that do similar things. So instead, I’m going to look at JsRender and JsViews.

At the moment there is very little documenation out there for either JsRender or JsViews, so this is some of the bits I’ve been able to piece together. Some of the simpler demos actually only use JsRender. And, of course, at this stage the project is still pre-beta so some of this may change.

To get going you need to add a reference to the JsRender javascript library. You can find that on github. Although you don’t need jQuery for JsRender, it can take advantage of jQuery to make some things easier. I’ll be showing JsRender with jQuery as I happen to think it makes things easier.

Hello World!

To start with the template is rendered in a script block with a type of “text/x-jsrender”. The templated parts themselves are made up of two sets of braces with an expression inside. For example:

<script id="helloTemplate" type="text/x-jsrender">
  <p>Hello, {{:name}}!</p>
</script>

Next, we need some javascript to wire up the template with some data

<script type="text/javascript">
  $(function(){
    // Set up the data
    var thePerson = { name: "Colin" };

    // Render the template to a string
    var renderedHtml = $("#helloTemplate").render(thePerson);

    // insert the rendered template into an existing element
    // In this case it is a span.
    $("#container").html(renderedHtml);
  });
</script>

To see the example in action, click here and view the source of the page to see the underlying code.

Private members in coffeescript and the query string

Because coffeescript is really just a thin veneer over javaScript there are, in my opinion, a few lost opportunities. For example, when you create a class all members (properties or functions) are public. However, there are work arounds.

I created a class to help me work with query string parameters. Actually, I ended up creating two classes, one an implementation class that did most of the hard work, and another to act as the public interface to the rest of the world. The “public” class is attached to the window object to make it globally available within the browser, the implementation class will only be available to other code inthe same script as the script as a whole will be wrapped by the coffeescript compiler in an anonymous function.

The publically available class, the one attached to the window object exposes three functions, yet it doesn’t expose its association to the implementation class. I achieved this by making the the association to the implementation class inside the constructor and then definining all the other functions in the construtor too. Each method I wanted to make public I prefixed with the @ symbole (the equivalent of this. so that it would be available to users of the class

# Define the queryString class, attaching it to the window object,
# effectively making it globally available.
class window.queryString
  constructor: (url) ->
    # The constructor defines a local variable to hold the reference
    # to the implementation class. This acts as a private member variable.
    __qsImpl = new queryStringImpl(url)

    # The public methods are defined on "this" by using the @ prefix
    # They can access the local variables in the parent scope because
    # they are closures.
    @getValue = (key) ->
      result = __qsImpl.params[key]
      if not result?
        result = __qsImpl.canonicalParams[key.toLowerCase()]
      return result

    @count = () ->
      __qsImpl.count

    @hasKey = (key) ->
      return key of __qsImpl.params || key.toLowerCase() of __qsImpl.canonicalParams

The implementation class also detects when the url is null or undefined and automatically finds the url and extracts the query string information for you. With this you can then get access to the query string parameters by using code like this:

# Create the query string object
qs = new queryString()

# Get a value from the query string
theValue = qs.getValue("SomeQueryStringKey")

# Work out if a value is available on the query string
isAvailable = qs.hasKey("SomeQueryStringKey")

# Find the number of query string parameters
numberOfParams = qs.count()

Classes, static properties, and inheritance in Coffeescript

I fear the documentation for coffeescript does not really explain the way that static and instance members work terribly well. So, I’ve put together this rough guide to classes in coffeescript

For this set of examples, I’m going to use my standard class diagram that you may have seen on other blog posts:

Creating a class

To create a class you simply write

class Animal

However, the way coffeescript works is that class will only be accessible to other things in that script. The command line utility does allow lots of files to be joined together so that may not be such an issue for the most part. However, if you want your class accessible on the page you are going to have to make it globally available in which case you will need to attach it to the window, like this:

class window.Animal

The class constructor

At its simplest the constructor can be as simple as this:

class Animal
  constructor: ->

The above construct takes no arguments and doesn’t do anything. There is no body. Note, that since coffeescript has significant white-space the constructor method has to be indented. To ensure that it is empty, don’t put the next line of code in at a greater indent depth that the word “constructor”

If the constructor doesn’t need to do anything you can leave it out. If you do need to initialise things then you can. For example, let’s say we want each animal to know its date of birth, we can do this

class Animal
  constructor: (dateOfBirth) ->
    @born = dateOfBirth

The @ symbol is a shorthand for this. However, there is an even quicker way of doing this. If your argument is simply going to be assigned to an instance variable, then you could do this instead:

class Animal
  constructor: (@born) ->

Static members

This is one area I find somewhat confusing. If you want to declare a static field on a class, you prefix it with the @ symbol, as if you are creating a short hand for this. Which is, in fact, what you are doing.

class Animal
  @population : 0

In the context of the class, the use of this is correct. You are operating int he context of an object of type class. Not an object of an instance of that class. If that makes sense. Essentially, the class itself is an object.

So, if you want to use this static variable on the class you could do something like this

class Animal
  @population : 0

  constructor: (@born) ->
    Animal.population += 1

And from outside the class, you similarly reference the class itself. For example:

(new Animal 'Today') for count in [1..10]
currentPopulation = Animal.population

Similarly, static methods on the class are prefixed with the @ symbol. For example

  @resetPopulation: () ->
    Animal.population = 0

And called on the class, rather than an instance. Also remember that if the method has no parameters, you need to include the parenthesis in the call, otherwise it gets itself in a bit of a twist. e.g.

Animal.resetPopulation()

Inheritance

To inherit from a class you simply extend the base class. For example:

class Mammal extends Animal

If your base class has a constructor then it will be called automatically when you instantiate the derived class. However, if you need to add a constructor of your own to the derived class you must remember to call the base constructor manually otherwise the base construction won’t happen as you expect.

class Animal
  @population : 0

  constructor: (@born) ->
    Animal.population += 1
    @isMulticellular = "no"
    console.log 'Animal constructor called. Population is '+Animal.population

class Mammal extends Animal
  constructor: (born) ->
    super(born)
    @isMulticellular = "yes"
    console.log 'Mammal constructor called.'

If you note, the call to super (to call the base constructor) happens first. This is generally what happens in many object oriented languages when constructing classes that have inheritance. The base parts of the class are constructed first. This gives the derived class access to the fully constructed base parts before it does its part. However, you are free to put the call to super anywhere in the derived class’s constructor.

Loading coffeescript unit tests from separate files

In my previous post I showed how to create unit tests for coffeescript. I also included a link to Eli Thompson’s coffeescript unit testing runner which allows you to easily gather all the .coffee files and the unit tests together in one place thus allowing you to keep your unit tests in separate files (rather than in-lining it in the test-runner as I showed in my previous example).

So far, so good. However, you cannot run this from the local file system as the browser’s security will complain (see the console panel in the screenshot below). The files are loaded using jQuery’s get method.

So, in order to get it to run you need to run it from within the context of a web server. You can use IIS if you are running windows, however for this example, I’m using Linux so I’ll use Apache.

Getting Apache up and running on Linux

To install Apache, in a terminal type:

sudo apt-get install apache2

By default, the newly installed server will serve from the /var/www/ which will contain an index.html already.

In order to create a new site that points to your development environment so that you can run the unit tests locally you need to modify apache.

Start by opening the /etc/apache2/apache2.conf file. (You’ll need to use sudo or run as root in order to write this back as your user won’t have the permission by default.) And add the following to the end of the file:

NameVirtualHost 127.0.0.1:80

This tells Apache that you’ll be creating named web sites on the IP/port specified. This is most useful if you have a server that hosts multiple sites. In our case we are simply using it to create a development site on our local machine. Because we’ve specified the loopback address it won’t be visible outside of the machine it is running on. (More info on NameVirtualHost)

Next we have to create a file in /etc/apache2/sites-available/ directory. As far as I can see, the convention is to use the host name as the name of the file. So a site running a www.example.com would have a file of the same name. In this case, as it is a development site running only on localhost I like to name it something along the lines of myproject-localhost so that it is obvious that it is running on the loop back address.

For this example, I’ll create a file called /etc/apache2/sites-available/coffee-tests-localhost with the following content:

<VirtualHost 127.0.0.1:80>
ServerName coffee-tests-localhost
ServerAlias www.coffee-tests-localhost
ServerAdmin colin.mackay@example.com
DocumentRoot /home/colinmackay/hg/blog-and-demos/three-of-a-kind
</VirtualHost>

Since this file is in sites-available that means it is not yet enabled, so the server won’t be serving it up. In order to get it served up there needs to be a duplicate in /etc/apache2/sites-enabled/. You don’t need to create a duplicate in Linux as you can create a symbolic link to the original file. To do that, type the following at a terminal:

cd /etc/apache2/sites-enabled/
sudo ln -s ../sites-available/coffee-tests-localhost .

(Note the dot at the end of the second line!)

Since the host name does not really exist, no DNS will resolve it, this is the point that you need to edit the /etc/hosts file so that your local browser can go to the web site. Add the following line to the hosts file:

127.0.0.1     coffee-tests-localhost

Finally restart the Apache server:

sudo /etc/init.d/apache2 restart

You should now have your web site up and running and displaying the tests to you now.

The running tests

When we go to http://coffee-tests-localhost/tests/test-runner.htmlall the tests now run and there is no error in the browser’s console:

More information

Unit testing with Coffeescript

I’ve recently started  looking at Coffeescript. And to get going with that I’m jumping directly in with unit-testing. I figured that it would be an interesting way to learn the language.

Since coffeescript compiles to javascript, you can use a javascript unit testing framework such as QUnit which can be downloaded from github.

Getting to grips with QUnit

Before we delve into coffeescript part, let’s have a very quick look at QUnit.

In order to run unit tests create an HTML page that will contain the runner. In this page you need to include jQuery, and QUnit (http://code.jquery.com/qunit/git/qunit.css and http://code.jquery.com/qunit/git/qunit.js). The body of your test runner needs to contain elements that QUnit will update during the tests. You also need to include the tests themselves.

I won’t go much further in to QUnit as there is already ample
information about getting going with QUnit over on the jQuery website.

Running coffeescript in the browser

Normally coffeescript is pre-compiled into javascript before being sent to the browser, however it is possible to have the browser compile coffeescript itself. This would not be recommended for production code, but does make life easier for running unit tests as the browser handles the compilation step for you.

You can run coffeescript in the browser by using the script located at http://jashkenas.github.com/coffee-script/extras/coffee-script.js. Then
any subsequent script blocks that are marked with the text/coffeescript type will be compiled on-the-fly. e.g.

<script type="text/coffeescript">
    // Your coffee script code here
</script>

One annoyance I’ve found is that coffeescript relies on “significant whitespace” which means that I’m forced to format my code the way coffeescript likes. In general thats not necessarily a bad thing, especially when you are editing coffeescript files, but with inline script blocks it can be irritating. Your script block may already be indented (and I tend to go for indents of two spaces for HTML files, as opposed to 4 for C#) which coffeescript doesn’t seem to like.

Running some tests

First of all this is what a test looks like in javascript using QUnit.

  <script type="text/javascript">
    $(function(){
        module("My javascript test");

        test("Assert 1 not equal 0", function(){
          ok(1!==0, "One expected to not equal zero");
        });
    });
  &lt/script>

What’s happening above is that the tests run when jQuery is ready. In other words, once the DOM is loaded. (See also: $(document).ready()).

The module method is simply a way of segregating the tests in to groups. All tests that follow a call to module will be grouped into that “module”.

The test happens in the call to test which normally takes a string which is the text to display each time the test is run, and a function containing the actual test. The second test that I have is written in coffee script.

<script type="text/coffeescript">
$(()->
    module("My coffeescript test");
    test("Assert 1 equals 1", ()-> ok(1==1, "One expected to equal one"));
);
</script>

While in coffeescript you don’t need the brackets around the function parameters, I prefer them. Nor do you need the semi-colon to terminate each statment, and again this is personal preference. You’ll see lots of coffeescript that won’t use brackets and semi-colons in the above situations.

Here is the result of the two tests above:

Test 	    runner with passing tests

In both tests above there is a call to ok which asserts that the condition passed in as the first argument is true, if not it fails the test. When a test fails the text in the second parameter of the ok function is displayed. For example, a test designed to deliberately fail:

    test("Assert 2 equals 3", () -> ok(2==3, "2 expected to equal 3"));

And the result in the test runner:

Test runner with failing test

Unit testing with .coffee files

Eli Thompson has an example of how you might want to put together unit tests for a
system written in coffeescript
. The core of his example is to define a list of coffeescript files and a list of tests and have a bit of coffeescript dynamically load them in order to run the tests.

In that example, scriptsToTest contains a list of coffeescript files that contain the code to test, and a list of tests which reference the files that contain the actual tests. The code then loads each coffeescript file, compiles it to javascript and loads it into the DOM so that the browser can execute it. The code that does all the hard work is a rather elegant 9 lines of
coffeescript (not including the declaration of the files involved).

More information

This was a very quick introduction to unit testing with QUnit and
using coffeescript. Here are links to more resources to continue
with:

PHP for ASP.NET Developers (part 5 – Object lifetime)

Following from my last post on the basics of object orientation in PHP, what about object lifetimes. How long does an object hang around for?

Class Diagram

In PHP you have a __destruct method on a class. This is like the finaliser in C#. For example, here is a HomoSapien class (a natural extension from the object model above).

class HomoSapien extends Mammal {

    public function __construct()
    {
        echo("Hello World!");
    }

    public function __destruct()
    {
        echo("Goodbye, cruel world!");
    }

    public function Vocalise()
    {
        echo "To be, or not to be...";
    }
}

When an object is create the __construct function is run (as we saw in the last post). The __destruct function is run when the object is unset, like this:

$human = new HomoSapien();
echo("n");
unset($human);
echo("n");

The output shows that the __constuct and __destruct methods were run.

Like the __construct function, the __destruct function does not automatically call the parent (as it would in C#). You have to do that explicitly with code like this:

public function __destruct()
{
    parent::__destruct();
}

Similarly, when the object goes out of scope the __destruct method is run:

function doStuff()
{
    $human = new HomoSapien();
    echo("n");
    $human->Vocalise();
    echo("n");
}

doStuff();

outputs:

Hello World!
To be, or not to be...
Goodbye, cruel world!

The destructor will also be run at the end of a script, so if the objects have not yet gone out of scope by that point they will be run. Any statements that output to the page will be run after the page has rendered. For example, the following script:

<html>
 <head><title>My little test PHP script</title></head>
 <body>
  <pre>
<?php

include_once('HomoSapien.php');

$theMother = new HomoSapien("Caitlin", null, null);
$theFather = new HomoSapien("Iain", null, null);

$theChild = new HomoSapien("Douglas", $theMother, $theFather);

?>
</pre></body></html>

Outputs the following:

<html>
    <head><title>My little test PHP script</title></head>
    <body>
  <pre>
Hello, I'm Caitlin!
Hello, I'm Iain!
Hello, I'm Douglas!
</pre></body></html>Douglas is no longer in the building!
Iain is no longer in the building!
Caitlin is no longer in the building!

And for completeness, here is the HomoSapien.php mentioned in the last example:

<?php
include_once("Mammal.php");

class HomoSapien extends Mammal {
    private $name;

    public function __construct($name, $mother, $father)
    {
        parent::__construct($mother, $father);
        $this->name = $name;
        echo("Hello, I'm {$this->name}!n");
    }

    public function __destruct()
    {
        echo("{$this->name} is no longer in the building!n");
    }

    public function Vocalise()
    {
        echo "I think, therefore I am.n";
    }
}
?>

Mammal.php:

<?php

include_once('Animal.php');

abstract class Mammal extends Animal {
    protected $mother;
    protected $father;

    public function __construct($mother, $father)
    {
        $this->mother = $mother;
        $this->father = $father;
    }

    public function displayParents()
    {
        echo ("Mother=".$this->mother."; Father=".$this->father);
    }
}
?>

Animal.php:

<?php

abstract class Animal {
    public abstract function Vocalise();
}

?>