Coffeescript, Sass and Less Visual Studio extension

The kind folks over at Mindscape have released a nice Visual Studio extension for Coffeescript, Sass and Less which gives it syntax highlighting, intellisense and code collapsing.

Read more about it here or simply go straight to the download page

If you haven’t tried Coffeescript yet, I recommend giving it a shot. It’s a lovely language that feels like it’s based on ruby/python and cross compiles into Javascript.

node.js, expressjs and jsonp example

Here’s a quick and simple example on how to make a jsonp call to a node.js + express server

node.js + express code:

var express = require('express');

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/logget', function(req, res){
  console.log('get to log');
  console.log(req.query.callback);
  console.log(req.param('somedata'))
  
  res.header('Content-Type', 'application/json');
  res.header('Charset', 'utf-8')  
  res.send(req.query.callback + '({"something": "rather", "more": "pork", "tua": "tara"});');  
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Test html page:

<html>
	<head>
		<title>jsonp test</title>
		<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>		
		<script type="text/javascript">
            $(function(){				
                $('#jsonThingLink').click(function(e){
                    e.preventDefault();
                    console.log('jsonThingLink clicked');					
                    
                     $.ajax({
                        dataType: 'jsonp',
                        data: "somedata=blahblah",						
                        jsonp: 'callback',
                        url: 'http://localhost:3000/logget?callback=?',						
                        success: function(data) {
                            console.log('success');
                            console.log(data);
                            console.log(data.more);                
                        }
                    });
                });				
            });
        </script>
    </head>
    <body>
        <div id="jsonThing"><a href="#" id="jsonThingLink">test jsonp</a></div>    
    </body>
</html>

Auto reload/refresh page if html changed

When you are twiddling css and constantly tabbing between your editor and browsers, refreshing the browrser can become a chore.

So let’s do some micro-efficiency-dev-process-hacking.

I threw together a quick javascript library that will auto reload the page you are working on IF the html has changed in anyway.

html-crc-reload

Simply include the .js file in your page.
You’ll need to ensure your page references jQuery and that it’s sitting on a web server.

The script will ajax poll itself, check the crc and if different, reload the page.

I develop with lots of side by side windows on a large screen.
This util allows me to stay in the editor window yet see the page refresh when needed.

UPDATE – 2013-05-04

There have been quite a few developments in auto reloading since I posted this.

Firebug, Firefox dev tools and Chrome allow for some aspect of in-page editing (not locally persisted yet).

Here are a bunch of posts on the subject:

I’m going to give the Sublime Text + LiveReload a go since Sublime Text is the pretty damn awesome.

A paid app called Live reload looks pretty cool. Although I haven’t tried it.
And they even talk about other options if it’s not your cup of tea

And Sam Saffron (a developer of Discourse) also touches on the subject

PetaPoco – a sorta orm

Recently, I got a little frustrated with Entity Framework and linq. The performance feels slow and the voodoo sql it generates could be better.

For high usage web applications, EF is probably not the right tool.

You might have heard of dapper-dot-net – a simple object mapper from the guys at Stackoverflow.
Their page lists some performance figures and one of them caught my eye – PetaPoco.

I really love the simpleness of it.
Here’s an example from the PetaPoco page:

// Represents a record in the "articles" table
public class article
{
    public long article_id { get; set; }
    public string title { get; set; }
    public DateTime date_created { get; set; }
    public bool draft { get; set; }
    public string content { get; set; }
}
Next, create a PetaPoco.Database and run the query:

// Create a PetaPoco database object
var db=new PetaPoco.Database("connectionStringName");

// Show all articles    
foreach (var a in db.Query<article>("SELECT * FROM articles"))
{
    Console.WriteLine("{0} - {1}", a.article_id, a.title);
}

After playing around with it a bit, I’m really liking it. I’m going to start upgrading my personal project, Snowboard Finder, with it.
Luckily Snowboard Finder implements the Repository pattern so it should be cinch… right? 😛

Multiple foreign keys pointing to same table in Entity Framework 4.1 code first

I’ve been upgrading our systems to use Entity Framework 4.1 code first.

I stumbled onto an issue where I had a table with multiple foreign keys pointing to the same table like so:

dbo.Companies can have Seller or Debtor as a CompanyType
dbo.SellerDebtors defines the relationship a Seller Company has with a Debtor Company.

If you have more than one navigation property of the same type, Entity Framework is not able to determine which navigation properties belong together.

You need to use the attribute InverseProperty to tell EF which navigation properties to use.

The model should be written like this:

public class SellerDebtor
{
    public int SellerDebtorId { get; set; }
    [ForeignKey("DebtorCompany")]
    public int DebtorCompanyId { get; set; }
    [ForeignKey("SellerCompany")]
    public int SellerCompanyId { get; set; }

    [InverseProperty("SellerDebtorDebtorCompanies")]
    public Company DebtorCompany { get; set; }
    [InverseProperty("SellerDebtorSellerCompanies")]
    public Company SellerCompany { get; set; }

    public virtual ICollection<SellerDebtorInfo> SellerDebtorInfos { get; set; }
    public virtual ICollection<SellerDebtorFile> SellerDebtorFiles { get; set; }    
}

public class Company
{
    public int CompanyId { get; set; }
    public string CompanyType { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<CompanyInfo> CompanyInfos { get; set; }
    public virtual ICollection<CompanyFile> CompanyFiles { get; set; }

    public virtual ICollection<SellerDebtor> SellerDebtorDebtorCompanies { get; set; }
    public virtual ICollection<SellerDebtor> SellerDebtorSellerCompanies { get; set; }
}

Error: There is already an open DataReader associated with this Command which must be closed first.

I came across this error while trying to port my code to Entity Framework 4.1

There is already an open DataReader associated with this Command which must be closed first.

To fix this, simply add MultipleActiveResultSets=true to your connection string.
MARS is supported by SQL Server 2005 and 2008

I found some more info on this StackOverflow Article

Entity Framework 4.1 code first composite keys

Do you have a table that uses composite keys?

Well to get those working in Entity Framework 4.1 code first, simply use the [Key] and [Column(Order=?)] attributes like so:

public class ProductSKU
{
    [Key]
    [Column(Order = 0)]
    public int ProductId { get; set; }
        
    [Key]
    [Column(Order = 1)]
    public int AffiliateFeedId { get; set; }

    public bool Publish { get; set; }

    public virtual AffiliateFeed AffiliateFeed { get; set; }
    public virtual Product Product { get; set; }
}

C# Console Application with Asynchronous Looping that listens to Console input

I’ve recently needed to write a Console Application to do some occasional monitoring.

The logic needed to live in a constantly running Game Loop yet the Console needed to be responsive to user input.

If quit (q) was called, the task needs to complete before the application ends.

.NET 4.0’s System.Threading.Tasks helped achieve this.

I based my code off this Stack Overflow post.

Here’s the code:

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

namespace NotifierBot
{
    class Program
    {
        static bool _running;
        static Bot _bot;

        static void Main()
        {
            _bot = new Bot();
            _bot.Start();

            _running = true;

            while (_running)
            {
                // check for user input
                checkInput(Console.ReadKey().KeyChar);
            }

            // wait for the task to finish before exiting
            _bot._task.Wait(); 
        }


        static void checkInput(char input)
        {
            if (input == 'q')
            {
                Console.WriteLine("\nQuit called from main thread");

                _bot.Stop();
                _running = false;
            }
        }
    }

    public class Bot
    {
        // we use Task.Factory to start a gameloop on a different thread. this allows the console to listen to user input events like 'q' 
        // as per
        // http://stackoverflow.com/questions/4576982/are-there-best-practices-for-implementing-an-asynchronous-game-engine-loop        

        CancellationTokenSource _cts;
        public Task _task;

        public void Start()
        {
            Console.WriteLine("\tBot Started");

            if (_cts == null)
            {
                _cts = new CancellationTokenSource();
                
                
                _task = Task.Factory.StartNew(() => Loop(_cts.Token), _cts.Token);
            }
        }

        private void Loop(CancellationToken token)
        {
            // The core loop
            Console.WriteLine("\tLoop started");


            while (!token.IsCancellationRequested)
            {
                Console.WriteLine("\tLoop!");

                token.ThrowIfCancellationRequested();
                Thread.Sleep(2000);
                Console.WriteLine("\t\tdo stuff");
            }

            Console.WriteLine("\tLoop ending");            
        }

        public void Stop()
        {
            Console.WriteLine("\tStop called");

            if (_cts != null)
            {
                _cts.Cancel();
                _cts = null;
            }
        }
    }
}