Development Uncategorized

Packagist & Github – How-To Guide

I’ve got a few PHP libraries and classes that I use regularly and, since making the decision to base all my projects on the Laravel framework, have gotten fairly used to installing packages using Composer.

I battled occasionally with getting my libraries to work with Laravel, mostly because of the way I’d written them, but I figured the smart way forward would be to make them available to other Composer users. For PHP, this means structuring the libraries in a specific way and making them available through Packagist, “The PHP package archivist”. You probably know this already, but when you add a package to your project’s composer.json file, Packagist is where it gets downloaded from.

Anyway, after some searching around, I found a bunch of articles that covered how to do *some* of the things needed to create Packagist packages, but no decent end-to-end guide.

So here we go – I’m going to write one. Hopefully it comes in useful.

Pre-requisites & initial steps

  • Sign up for Github. It’s free until you need to go beyond their basic account limitations. Packagist packages are based on Github repository *releases* (or tags).
  • Get familiar with Semantic Versioning, if you haven’t already.
  • Sign up for Packagist. It’s also free.
  • Decide on your *vendor* name – mine is ‘digitalformula’.
  • Install Composer

It’s an excellent idea to have the same usernames on Github and Packagist, if possible.

Creating the base package structure

Create the directory structure for your package. There’s no “right” way to do this, but I’m following the structure used by almost every Packagist package I’ve installed so far. The structure below is for the package we’ll be creating in this article.

Packagist directory structure

Here’s a basic explanation of what each part is.

  • digitalformula – your *vendor* name, your Github username and your Packagist username.
  • hello-world – the name of the package, following proper directory naming guidelines.
  • .git – Git repository information. This gets generated by git when you run ‘git init’ below.
  • .gitignore – list of files that should be ignored during git adds and commits. Each line should contain a filename, path or pattern.
  • src – the ‘root’ directory for your package. It’s also where we’ll tell the PSR-0 autoloader to look – we’ll get to that in a bit.
  • DigitalFormula – the first segment of the PHP namespace we’ll use. This must match your vendor name although at this point you’re free to use appropriate capitalisation, if you like.
  • HelloWorld – the second segment of the PHP namespace we’ll use.
  • HelloWorld.php – the PHP file containing our package’s code. Obviously more complex packages will have multiple files, but a single file will suit us just fine for now.
  • LICENSE – the license that covers usage of your package.
  • – information about your package. Every Github repository should have one.
  • composer.json – probably the most important file here. It describes your package, what it’s for, who worked on it, dependencies and how PSR-0 autoloading will work. Unless you’re interested in the technicalities (I’m not), don’t worry about how PSR-0 works. It just works, I promise.

For those wondering, the complete PHP namespace will be *DigitalFormula\HelloWorld*.

Hold on … namespace? What’s that? If you’re not already familiar with PHP namespacing, I highly recommend reading Dayle Rees’ excellent PHP Namespaces Explained article.

AJAX Development JavaScript Laravel Uncategorized

Check Laravel user status with AJAX

Like most websites, my current project requires users to login.  For security reasons, user sessions timeout after a while, leaving the user without an authenticated session.  While this is fine for me, it’s not so good for users that may have entered something info a form, hoping to come back to it later.  In some cases, the text may be lost – annoying, no doubt.

Since my PHP framework of choice is Laravel, it was relatively simple to have a background process check the user’s login status and, if their session has expired, show an informative message.

Since this article is just a quick demo, I’m going to check the user’s login status every 60 seconds and show the message if nobody is logged in.  On the production site this will change, although the method will be the same

Step 1 – Setup the JavaScript timer

Here is the tiny bit of JavaScript you need to setup the timer.  Don’t forget to change the element you are binding this to in your application – I’m using <li>, as you can see.

    $( "li#status" ).timer();
}, 60000);

Step 2 – Write the AJAX function that returns the user’s session status.

public function getLoginStatus()
    return Response::json( array( 'status' => Sentry::check() ) );
/* getLoginStatus */

Step 3 – Setup the timer function that will call the associated AJAX function.

jQuery.fn.timer = function()
    $.get( "/ajax/login-status", function( data )
        data.status == false ? $( 'li#status').show() : $( 'li#status').hide();

For the functions above, you may need to alter the way they are called if you aren’t using Laravel in your projects (although I recommend it). You’ll also notice that I’m using Sentry::check() – this is how to check a user’s login status while using the excellent Sentry package from Cartalyst.

Here’s what the <li> element looks like.

The element that is displayed when no user is logged in.

That’s really all you need to do, although you may also want to change when the functions are called so that unregistered visitors don’t get shown the message, too.  Easy!

Archived Development Linux Uncategorized

PHP 5.4 + suhosin = FAIL

I recently modified my dev environment to allow PHP 5.4 apps, something that involved adding a bunch of Debian Linux “wheezy” sources to my aptitude configuration. No problem in itself, but it did totally wreck my web server’s ability to load the extension (PHP 5.4 doesn’t support it).

This wasn’t a biggie until I hit up one of my Laravel apps and was greeted with a lovely message that said the following:

 Unhandled Exception Message: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20100525/' - /usr/lib/php5/20100525/ cannot open shared object file: No such file or directory Location: Unknown on line 0 

Not nice. Looking through php.ini, apache2.conf and httpd.conf showed nothing and, since I’m not particularly familiar with suhosin in itself, I couldn’t figure out where the extension was being loaded.

 locate suhosin 

That showed me that there is a file on my system called suhosin.ini located in /etc/php5/conf.d so I fired up nano (I’m not cool enough to use vi) and, sure enough, there at the top was the following line: 

I commented that line, restarted the apache services:

 service apache2 restart 

… and now Laravel doesn’t throw any horrible unhandled exceptions about suhosin being broken.

Sorted. 🙂

Archived Development Uncategorized

JavaScript refactoring, the n00b way

I’m a bit of a n00b when it comes to doing stuff in JavaScript. So naturally, when I find a way of introducing a bit of efficiency into a JavaScript situation, I’m more than happy to throw it into the mix. My only disclaimer for the below ramblings are that if you’re a developer that knows anything more than the basics, everything I’m about to write will be nothing more than a “Yeah, no shit, genius” kinda thing. So, go easy on me, mmmkay? 🙂

So anyway, my current attempt at web hackery requires a bit of JavaScript, AJAX + the usual suspects that often go along with those things i.e. jQuery Core, jQuery UI, Sass … you get the picture. Nothing unusual going on here … did I mention that I love jQuery?

I tend to write stuff, make it work, carry on to other things and then come back later, look at a block code and throw up in my mouth a little bit when I see how freakin’ ugly and inefficient it is. I mean, seriously, why would you duplicate an almost identical block of JavaScript eleven times when you can do what a real developer would do, and write it properly in the first place?

This example is super-obvious and really aimed at people, like me, who don’t do this stuff professionally but like to learn better ways of doing things. Firstly, here’s a snippet of what I had before.

 $('button.delete').button( { icons: { primary: 'ui-icon-circle-minus' }, text: false }); 

I had that bit of jQuery UI a bunch of times and had to add a new one, whenever a new element came up that required button-ifying … like that? It’s new. 🙂

Needless to say, that’s horribly inefficient as it requires copy/paste/edit for every occurrence.

Not too long ago, I followed along all doe-eyed while Jeffrey Way (@envatowebdev) taught my fellow n00bs and I how to do things properly with jQuery. Objects came up, and a revelation happened. For me, anyway.

So now, instead of duplicating that block of code (the one up there a bit) many times over, I’ve got all my buttons in an array of objects which is then processed and the relevant properties turned into the equivalent of the eleven blocks of rubbish I had before. I’m the first to admit that there will definitely be a better way of doing this, still, but for now I’m happy with the changes.

Here’s how it looks now:

 var buttons = { b1 : { id : 'button.delete', icon : 'ui-icon-circle-minus', text : false }, b2 : { id : 'div#password-submit input', icon : 'ui-icon-check', text : true }, b3 : { id : 'div#profile-submit input', icon : 'ui-icon-check', text : false } } for each ( button in buttons ) { $( ).button( { icons: { primary: button.icon }, text: button.text }); } 

Plug a new button-ifiable element into the array and it’ll automatically processed next time the script runs (and isn’t cached – we’ve all fallen into that that trap).

The result is exactly the same as I was getting before, but, in my opinion, could be called more elegant, efficient, easier to read, whatever.


Archived Development Linux Uncategorized

Slow FTP running ProFTPD on Parallels for Mac

My current web development server is a Debian GNU/Linux 5.0.5 machine running under Parallels for Mac (which I’m trialling right now). It was all working great until I tried to access the FTP server running on it from my Macbook Pro over the Airport. It worked but maaaaan was it slow! The Debian server is running ProFTPD, one of the many free FTP server options out there.

Thankfully the solution to the slow FTP access is very simple.  There isn’t a DNS server running here as it’s not something I need for local development (although it would’ve solved this problem, too).  The problem was caused by reverse DNS lookups failing – this is something ProFTPD has enabled by default if you use apt-get install proftpd to install ProFTPD.

Turn off Reverse DNS lookups

Turning off reverse DNS lookups in ProFTPD is as simple as checking /etc/proftpd/proftpd.conf for the following lines.

  • IdentLookups off
  • UseReverseDNS off

The IdentLookups line may already be set to ‘off’ – that’s fine and you can leave it that way.  The UseReverseDNS value may not exist at all – if that’s the case just added it to the proftpd.conf file and set the value to ‘off’ by following the format of the other configuration lines:

UseReverseDNS in ProFTPD

Restart ProFTPD

While logged in with appropriate privileges the following command (from the Terminal) should restart ProFTPD.  Rebooting your Debian GNU/Linux server will also restart ProFTPD but the whole point of running Linux is so you hardly ever have to reboot … right?

Restart ProFTPD:

/etc/init.d/proftpd restart

Obviously your own configuration may differ so only follow these instructions if it won’t break everything – be warned!

Archived Business Development Uncategorized

Microsoft Excel – Count coloured cells

Most companies have some sort of backup strategy in place and that strategy often involves documenting the success & failure rate of the backups on a daily basis. For obvious reasons all the companies I’ve worked with in the past have documented this using a variation of the well-known “backup matrix”, created using Microsoft Excel.

I choose to create my backup matrix documents so that backup results are colour-coded. That way they’re easily visible and it’s easy to see what happened when and to get an overall idea of how good your backups have been. Green coloured cells are successful backups, red cells are failed backups etc.

The first thing I need to do when I create these documents is to make some ‘reference cells’. These cells are coloured with the various colours that will be used in the matrix, e.g. green for successful etc, as listed above. So they don’t look like reference cells I also use them as the key for the matrix so people know what the various colours mean.

How, then, do you work out how good the backups have been if there’s no text in the cells to look for? You need a VBA function that looks for the cell’s colour instead of its contents – easy. Below is the function I wrote for that purpose – you’ll need to make sure you are using .XLSM documents if you are using Excel 2007 for Windows as .XLSX files are, by default, secured so that macros won’t run.

Please note that the code below won’t work in Office for Mac 2008 as VBA is not supported. Office for Mac 2011 will have has full support for VBA – I’m looking forward to see if this code works there. I haven’t tried it there, though.

Microsoft Excel – Count Coloured Cells

Function countColours(colourReferenceCell As Range, cellRange As Range)
    ' countColours
    ' Chris Rasmussen, April 2010
    ' Count occurences of cells that are a certain background colour
    ' E.g. for use in a backup matrix

    Dim currentCell As Range
    Dim colourReference As Long
    Dim vResult

    colourReference = colourReferenceCell.Interior.ColorIndex

    ' reset the total count back to zero to prevent errors
    vResult = 0

    ' go through all the cells in the specified range and look at the background colour
    For Each currentCell In cellRange
        If currentCell.Interior.ColorIndex = colourReference Then
            vResult = vResult + 1
    End If
    Next currentCell

    countColours = vResult

End Function

Once you’ve got this function in place, all you need to do is choose the cell that will show the total of successful backups (for example) and enter the following formula. We’ll assume that cell A1 is the cell that is coloured green for reference. We’ll also assume that the Excel cell range C1:C5 contains the results.


If you have 5 successful backups in your range and they’re all coloured green, the cell containing that formula with contain the number 5. Easy. 🙂

Archived Development Uncategorized

Making the W3C Validator work with ASP.NET

For as long as I can remember I’ve been making sure that the sites I play about with (published or not) produce markup that conforms with w3c specifications. The best-known way to do this is to run the markup generated by the web server through The W3C Markup Validation Service. Unfortunately it’s been difficult to make ASP.NET applications produce 100% valid markup, something that always frustrated me. There may have been ways to make this work before that I’m not aware of but here’s now to do it anyway.

It’s worth noting that the DOCTYPE declarations used throughout this article aren’t valid for HTML5.

I always write my sites to conform to XHTML 1.0 Strict specifications, despite currently making them HTML5-compliant wherever possible. If you’re unsure what this means I would recommend heading over the W3C website about XHTML 1.0. The Strict DOCTYPE is actually the way HTML and XHTML were designed to be used so I’d recommend using them over the older/legacy Transitional DOCTYPE. Depending on where you look or what you read, the transitional DOCTYPE is intended for sites making the transition towards standards-compliant markup. To me that sounds like pretty good reason to stick to the strict DOCTYPE.

Anyway, when you’re making your ASP.NET applications it’s possible to make Visual Studio generate applications that conform to the W3C recommendations and therefore work with the W3C Markup Validation Service. There are 2 things you need to do for this to work properly. Note that this isn’t specific to ‘standard’ ASP.NET applications – it will work with ASP.NET MVC applications, too.

Required steps

Step 1 isn’t strictly (no pun intended) required but it’s good practice. Edit Web.config and use the xhtmlConformance element to configure XHTML 1.0–conforming control rendering. Here’s what is in my Web.config files – this must be placed inside the section.

Web.config contents:

     <xhtmlConformance mode="Strict"/>
     <!-- the rest of the <system.web> section has been removed for the purposes of this article -->
  <!-- the rest of the <configuration> section has been removed for the purposes of this article -->

Microsoft’s MSDN page about the xhtmlConformance element can be found by going to

Archived Development Uncategorized

C# Full-screen application – Complete Source

Yesterday I posted a quick update to an article I wrote back in 2007 entitled “How to make a full-screen Windows app using VB.NET”. Aside from 1 or 2 people saying “Oh man why don’t you be a man and write it using C#?” I reckon it’s a good idea to do that anyway. Thanks Scott for the suggestion. 😉 And thanks Phil for pointing me in the right direction with the DLL import stuff. 🙂

So, without any mucking about here’s the exact same complete application example only this time in C#.

Please feel to ask any questions necessary. Thanks!

Form1’s complete source:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Play
    public partial class Form1 : Form

        public Form1()

        [DllImport (&quot;user32.dll&quot;)]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndIntertAfter, int X, int Y, int cx, int cy, int uFlags);
        private static extern int GetSystemMetrics(int Which);

        private const int SM_CXSCREEN = 0;
        private const int SM_CYSCREEN = 1;
        private IntPtr HWND_TOP = IntPtr.Zero;
        private const int SWP_SHOWWINDOW = 64;

        public int ScreenX
                return GetSystemMetrics(SM_CXSCREEN);

        public int ScreenY
                return GetSystemMetrics(SM_CYSCREEN);

        private void FullScreen()
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
            this.TopMost = true;
            SetWindowPos(this.Handle, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);

        private void Restore()
            this.WindowState = FormWindowState.Normal;
            this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
            this.TopMost = false;

        private void button1_Click(object sender, EventArgs e)

        private void cmdRestore_Click(object sender, EventArgs e)

        private void cmdExit_Click(object sender, EventArgs e)
Archived Development Uncategorized

How to use SQL Server CE with C# 3.5

I’m writing this article because a small project I’ve been working on required me to look for information on using SQL Server CE with C# 3.5. I couldn’t find very many useful articles on the topic so I’ve decided to write my own and summarise some of the useful bits I found.

For starters, why use SQL Server CE? I think it’s an easy way of implementing a high supported and functional database solution for various types of applications although this article will focus on using SQL Server CE in a small Windows forms application. To begin with you’ll need to download SQL Server CE from the Microsoft website.

In the past I think I’ve gone a bit overboard with the length of my posts so I’m going to attempt to keep this one short. The application I used this code in is pretty well split up and uses a number of different layers but you don’t need to go this far to use SQL CE with your applications. The code below is a summary only and covers the key things I think you need to know – feel free to ask any questions you need to.

I’m also aware that the code below *will* need modification before you can just throw it into your own applications but, as mentioned above, please post questions on this post if there is anything you need clarification on.

Creating the database

Connecting to SQL Server CE:

string connStr = String.Format("Data Source = C:tempdatabase.sdf");
using (SqlCeEngine engine = new SqlCeEngine(connStr))

SQL query with no result

Running a SQL command that doesn’t return a result set (note that this is, in some cases, where you would execute SQL to create the database structure after using the code above to create the database file itself).

using (SqlCeConnection conn = new SqlCeConnection(connStr))
  using (SqlCeCommand cmd = new SqlCeCommand())
     cmd.Connection = conn;

     cmd.CommandText = "SELECT * FROM table_name";

Getting a record from the database

using (var conn = new SqlCeConnection(connStr))

  string query = "SELECT * FROM Applications WHERE id = @Id";

  using (var cmd = new SqlCeCommand(query, conn))
     // appId is a variable passed to the method that uses this code sample
     cmd.Parameters.AddWithValue("@Id", appId);
     var reader = cmd.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable);
     if (reader.HasRows)
        while (reader.Read())
           int Id = Convert.ToInt32(reader["Id"]);
           // more code here to deal with other columns in the record that was selected from the database, if any

That’s about as basic as it gets but I’m also in the process of writing another article about a basic application that uses this code in a “real-world” situation.

Archived Databases Development Software Uncategorized

SQL Server 2008 Express Unattended Install

» If you’re looking for instructions on how to do an unattended install of SQL Server 2008 Express R2, please use the search function on this site – the other article is easy to find, I promise.

On the previous version of Digital Formula I wrote an article called "How to perform an unattended installation of SQL Server 2005 Express". With the release of SQL Server 2008 it’s time to write another one about how to do the same but for SQL Server 2008 Express. So, let’s get started …

Unattended installations of SQL Server can be as involved as you want – pretty much every option can be specified in the configuration file. For this example I’m going to perform a relatively basic installation with minimal customisation so you can see the process at work. The installation will specify most of what I think are the critical options you’ll be interested in. Note that for this example I’m using the x86 (32-bit) version with advanced services.


Required Files

  • Run the executable you downloaded with the /x parameter (e.g. C:InstallSQL2008SQLEXPRADV_x86_ENU.exe
  • Choose a location to extract the installation files to.
  • Create a new text file that will become the unattended installation configuration file. Leave it empty for now.

Configuration Files

So, you can now create your own configuration file using Microsoft’s documentation or you can use the version I’ve included in this article.

Be careful with the Microsoft documentation as there is an error on the page called How to: Install SQL Server 2008 from the Command Prompt. It mentions a parameter called /BROWSERSVRACCOUNT but this should be /BROWSERSVCACCOUNT. If you get this wrong the installation WILL fail.

You can download the configuration file I’ve made below. The changes I’ve made are as follows (you may need to change these to match your settings).

  • Set the QUIETSIMPLE parameter to “True”.
  • Set the MEDIASOURCE parameter to the appropriate installation path.
  • Added a parameter called SAPWD and set it to the strong ‘sa’ password.
  • Set the INDICATEPROGRESS parameter to “True”.
  • Set the SQLSYSADMINACCOUNTS value to “MYPCAdministrator”.

Once you have your answer file all nicely setup and ready to use you’ll need to tell the setup program how to use it.

Run the script

From a command prompt (or Start > Run if you’re into that) run the following command. Remember to change the file and path names to the ones that match your system.

Run the install:

C:InstallSQL2008setup.exe /CONFIGURATIONFILE=C:Installsql-2008-express.ini

If you’ve done everything right this will start the installation process and you’ll end up with a SQL Server 2008 instance called SQLExpress running on your system. Easy!