Mar04

Setting Gmail as the Default Firefox E-mail Client

at 8.56am

It has long been one of the few things I have disliked about Firefox that I can’t get the browser’s ‘Send Link’ function to use Gmail instead of the operating system’s default e-mail client. I tend not to use a desktop based e-mail client like Thunderbird or Outlook in favour of Gmail’s web based interface and I find it irritating that I have to copy and paste a URL into Gmail when I want to send a link. Well now I’ve found out that Firefox 3 can in fact provide the functionality that I want!

Firefox has the ability to allow web-based protocol handlers to accept links like mailto: and irc:. This means that as long as the online service accepts the protocol you can pretty much use anything to handle these links. The Mozilla Links blog explains how to set up Firefox to allow Gmail to be the client for e-mail.

Mar03

Site of the Month: February

at 7.43pm

Although a little later than intended due to a skiing trip at the end of February here is this month’s site of the month. This time I want to highlight Smashing Magazine as a fantastic resource for web development. Although not intended as a programming reference (the programming content offered is somewhat light-weight) it is a fantastic resource for graphic design material and inspiration.

The content includes textures, wallpapers, icons, photography, design examples and analysis of design trends, usability and tools. Although the emphasis is on web design most of the content is useful in other areas too, even if just for inspiration. It’s definitely worth subscribing to the Smashing Magazine RSS feed (which has recently changed location) to keep up with their latest content.

Posted in Links, Web | No Comments »
Feb17

Query Profiling with Zend Framework and FirePHP

at 8.47am

My last post was about logging with Zend Framework and FirePHP. This one is similar but, for me at least, just as useful. The Zend Framework can use the WildFire protocol (that allows client-server communication through HTTP headers) to allow the PHP database adapter to report directly to FirePHP about every query that goes through it. Along with a record of the query is the time the query took to execute. This allows you to see where the bottlenecks are in your SQL or simply whether you are running too many queries.

The set-up for this is even easier than before. Again, if you are using Zend_Controller_Front then this needs to be executed before you dispatch, otherwise before you send headers. The variable $db mentioned should be an instance of Zend_Db_Adapter_Abstract.

$profiler = new Zend_Db_Profiler_Firebug('SQL Queries');
$profiler->setEnabled(true);
 
$db->setProfiler($profiler);

As in the last example I normally wrap this in a conditional statement that detects whether profiling is turned on in the config file. This allows for the output to be disabled at the change of a paramter.

if($config->profiling->db == 'true') {
    $profiler = new Zend_Db_Profiler_Firebug('SQL Queries');
    $profiler->setEnabled(true);
 
    $db->setProfiler($profiler);
}

More information can be found in the relevant section of the Zend Framework Reference Guide.

Feb11

Logging with Zend Framework and FirePHP

at 9.03am

If you’re a web developer and you’ve never used Firebug then you really should give it a go - it can transform your work-flow. If you’re a PHP developer and you have used Firebug you should really give FirePHP a go too.

FirePHP is an extension to the Firebug Firefox plug-in. I won’t go into the details of Firebug here as there is plenty of other information around the internet and it doesn’t really need much discussion as to why you should use it. FirePHP on the other hand is a tool that I had never quite appreciated and did not understand its purpose over a debugger or simple echo or print_r statements. Once I started trying to debug Ajax applications it all became clear.

FirePHP allows you to log output to Firebug from PHP. This means that you can send a message from your server-side PHP script and have it appear alongside your JavaScript console messages. What’s the point I hear you say? Well, FirePHP does not receive data from the HTTP body (what you normally see in your browser) but instead uses custom HTTP headers to embed the information that is sent. What this means is that any data sent to FirePHP does not interfere at all with what is sent in the content of the page. This is particularly useful for debugging Ajax applications where any debug statements or extra output can completely corrupt a JSON or XML structure sent from the server. It is also useful for standard web page debugging as well where debug messages may affect the layout or behaviour of the page being loaded. Don’t take my word for it however, to really appreciate it you have to give it a go.

Since I do most of my development at the moment with the Zend Framework I will utilise the classes required to easily log messages to FirePHP using the framework’s logging classes. It is not really a problem if you don’t use Zend Framework for your application as the library’s loosely coupled design allows you to easily use the components that you need without worrying about the rest of the framework.

If you are using the front controller component from the Zend Framework then you need to set the following up before the front controller is dispatched, otherwise you just need to set it up before the headers are sent.

$writer = new Zend_Log_Writer_Firebug();
 
$logger = new Zend_Log($writer);

Yes, that’s it! This is a very simple case and I normally provide some extra logic and utility functions to allow easy access:

// Check whether logging is enabled in the config    
if($config->logging == 'true') {
   $writer = new Zend_Log_Writer_Firebug();
}
else {
   $writer = new Zend_Log_Writer_Null();
}
 
$logger = new Zend_Log($writer);
 
My_Debug::setLogger($logger);

This checks a config file to see whether logging is enabled; if not it uses the null logger which writes to no output. This is useful when switching to a production environment as it disables all logging output in one go. I also give an instance of the logger to a debug component. This is a simple class with a single static function called log. All this means is that I can call My_Debug::log() anywhere in my code and get it logged to Firebug and it’s just as easy as echo or print_r. The debug class is shown below. The log method just acts as a proxy to the Zend_Log function by the same name.

class My_Debug extends Zend_Debug {
 
    private static $_logger;
 
    public static function setLogger(Zend_Log $logger) {
        self::$_logger = $logger;   
    }
 
    public static function log($message, $priority = Zend_Log::INFO) {
        if(isset(self::$_logger)) {
	    self::$_logger->log($message, $priority);
        }
    }
}

More information on this setup can be found in the relevant section of the Zend Framework User Guide.

Jan29

Site of the Month: January

at 8.53am

My favourite site this month is definitely Stack Overflow. I first heard about the site a few months ago from a friend when it was first in public beta. I remember thinking that it was an excellent idea and that it would probably prove very valuable in the future although, at the time, it was a little immature and lacked much content that I was interested in. Since then, the site has been mentioned in a lot of blog posts, mailing lists and forums so I thought I would give it another look. Sure enough, the site had loads more content and is now an excellent resource.

Stack Overflow is focused very specifically on programming. By that I mean that any questions that are not considered to be programming related, such as those to do with administrator tasks or specific program features, are closed down by the community. I was stung by this in one of my first questions as I asked a question about what the differences between Linux distributions were and why I would use one over another. Within five minutes my question had been closed down and was told sternly that the question was “not programming related”. Whilst I was a little disgruntled at the time I have come to realise that this strict moderation is one of the key factors that makes the site so valuable. There is no spam and no mindless off-topic discussions (except for the ones that the community deem worthwhile and these are normally quite entertaining).

So, apart from the rigorous moderation, what makes Stack Overflow so much better than a normal forum or mailing list? Well firstly the threads are not threads in the forum sense but are, more specifically, questions. The questions are supposed to be clear, concise and should ideally not be subjective; questions on the site should “have an answer”. This means that the site is less about discussion and more about finding the answers to specific problems or queries. Good answers (those with the most votes) bubble to the top of the list of answers whilst good questions (again, those with the most votes) bubble to the top of the list of questions (and may even end up in the prestigious questions of the week and month lists).

The site becomes very addictive due to its clever reputation and reward system. Every time you get a question or an answer you have written voted on you gain or lose points. These points are called reputation and the power you have on the site is determined by your reputation. The more reputation you have, the more of a say you have in moderating the site. It is easier to gain reputation than it is to lose it as you only lose 2 points for a down-vote but gain 10 for an up-vote. Rewards, or badges, are items that appear on your profile for completing certain milestones (e.g. having a question with 1000 views). Whilst they don’t mean anything regarding your status in the community they are little pieces of pride that encourage you to contribute and get involved further.

There are some weaknesses to the site in my opinion. Firstly, due to the community from which the site was launched I find that the questions are mainly focused around .NET related technologies more than any other topic. This is changing however and hopefully will continue to do so in the future. Also, one side-effect of the voting system is that questions that have universal appeal (general programming or software engineering questions) always end up with more votes than questions on a specific topic. Whilst this makes the site an excellent resource for good general information I find that good questions regarding a particular technology often get lost amongst it all. The tagging system goes a long way towards removing this problem but I don’t feel that the current preferences you can make on the site allow you to filter out topics you are not interested in easily enough. It would be nice to see a more customisable front page and a way of completely hiding questions with specific tags.

I mentioned earlier about the lack of other IT related questions but there are plans for a sister site to fulfill this need. I look forward to seeing the results of that in the near future.

I hope I have tempted you to at least take a look at Stack Overflow (if you already have an OpenID account you hardly have to do anything). The more people that contribute the better the site will be. See you there!

Posted in Links, Web | 2 Comments »
Jan25

Site of the Month

at 11.53am

In an attempt to encourage me to blog more often and actually finish and publish some of the blog posts that I write I am going to start a series that highlights a particular online resource that I use regularly. These sites will probably all be about development of some kind (no, I don’t count Facebook as a resource) and will doubtless reflect my interests at any given time. I hope to highlight some resources that my readers may not have used before or at least trigger some discussion about the strengths and weaknesses of a given site and how others use it. I am also more than happy to take suggestions for sites that might be potential candidates for site of month.

The posts will be starting in January (I promise) so stay tuned for the first item!

Posted in Links, Web | 1 Comment »
Nov13

Google Maps Tutorial, Part 1: A Simple Map

at 7.40pm

Google Maps provides an excellent and powerful mapping solution with some complex features whilst maintaining high usability and a fast user interface. Through the JavaScript API Google have exposed a large portion of the functionality of their maps and data for use in websites and web applications (all of which must comply with their Terms of Use). It may sound difficult but it doesn’t have to be. In fact it is quite easy to produce some quite sophisticated behaviour with relatively little code.

In this series I hope to demonstrate how to build several increasingly complex mapping applications that could have practical uses in a website or application. At the end of each part I will give some ideas for how I think the example could be adapted to a real-life situation. As the examples get more advanced the number of possible applications will increase but so also will the amount of work required to change my code to achieve a specific purpose. I hope to demonstrate to tools and techniques you might need in making these changes. So, of we go!

In the first example I will show how to create a very simple map that can be displayed on a web page with a pin marking a particular point.

Prerequisites

For this part of the tutorial you will need a basic knowledge of HTML, CSS and JavaScript and some web space but not a lot else. You won’t even need any server-side scripting!

Step 1 - Getting a Google API Key

The first step is to obtain a Google API key. This will be required for any Google Maps application that you create and is tied to the domain from which the requests to the API are made. This may mean that you need separate API keys if your development domain is different to your live domain. This is not really a problem however as it is really simple to obtain a key.

Simply go to the sign-up page, read the Terms of Use (or more likely the summary as the full document is rather dull), check the box confirming you understand the blurb, enter your site URL and generate the key.

The next page will give you your key (a really long string of letters and numbers) as well as a snippet of code to get you started. Ignore this for now as we will be recreating something similar in a moment but with more explanation along the way. If you forget your key, don’t worry as following this procedure again should result in exactly the same key as long as domain is the same.

Step 2 - Displaying a Map

Okay, that’s the boring bit over. Now for something more interesting - let’s get a map on the screen. Firstly create a simple (X)HTML file (I’ll assume you know how to do this) and add an empty div element to the body as below.

<body>
   <div id="map"></div>
</body>

Make sure you don’t forget the id attribute as we’ll be using it in a moment.

Next, you’ll need to load in the API file. Add the following code to the HTML head tag replacing the key for this site with the key for yours.

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAv5cMnGZ5zeb1SlRlW91GkBStkTdrHPl7LrMl77V0klQxRUcDRBSy-WJLTWS8O7_n3a6dBXQ0xp7Jqg" type="text/javascript"></script>

Now that’s the preparation done so we can add the map itself. Create a new JavaScript file called map.js in a directory called js and add the lines

function load() {
   if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(0, 0), 1);
   }
}
 
window.onload = load;
window.onunload = GUnload;

So what’s going on here? Well the load() function is the bit doing all the magic and is creating a new Google Map object (if the browser can display it) and attaching it to our map div. The centre point of the map is set to longitude 0 and latitude 0 which is the point on the equator on the Prime Meridian (which runs through Greenwich). The last argument sets the zoom level of the map which is set to the minimum value to display a world map. We will change this centre point and zoom level later. We attach this function to execute when the page is loaded so the map gets displayed as soon as the user visits the page.

The GUnload() call destroys any Google JavaScript objects left around when the user navigates away from the page. This is important as in some browsers those objects would stay in memory until the whole browser is closed unless explicitly destroyed.

Okay, just a few more bits left to get the map on the screen. Firstly you will need to load in your newly created JavaScript file into the HTML page.

<script src="js/map.js" type="text/javascript"></script>

You may be wondering why I’ve separated the JavaScript into another file whereas the Google example has it all in the one HTML file. It is good practice to separate markup (HTML), behaviour (JavaScript) and presentation (CSS) into different ‘layers’ or groups of files as it helps separate your code into more maintainable and readable chunks. It also means that browsers can cache your JavaScript and CSS files independently and therefore decrease loading times. For a further discussion into these techniques see Understanding Progressive Enhancement from A List Apart or the Wikipedia article on progressive enhancement.

We need to set the size of the map on the page otherwise it will not display properly. To do this, create a CSS file called styles.css in a new directory called css. Insert the following code.

#map {
   width: 500px;
   height: 300px;
}

Now link the style to your HTML page by adding

<link href="css/styles.css" type="text/css" rel="stylesheet" media="screen, projection" />

to the head of the document.

If you now open your HTML page in a web browser you should see a lovely world map displayed on the page.

Step 3 - Centering the Map

That’s the hard work done now lets change where the map is focused. Google Maps requires location information to be passed to it in terms of its longitude and latitude. Unless you think in these terms you will need to convert an address, location or postcode into this format in order to use it in a Google Maps application. The process of converting an address or other human readable location into its longitude and latitude is called geocoding. We will discuss this topic in a later tutorial but for now we will use the Google’s own Maps application to do the work for us.

Go to Google Maps and search for the location you want to be at the centre of your map. Check that the map is centred around the correct point and that the marker is pointing to the right place. Now, right click on the marker and select the option ‘Clear search results’. The marker will disappear but the map should stay centered on the same place. Now go to the top right and click ‘Send’. A box will pop up containing a link. The longitude and latitude are in the ‘ll’ fragment of the url. This is the data you will need.

For example, I searched for Downing Street, London and the URL I have is

http://maps.google.co.uk/maps?hl=en&ie=UTF8&ll=51.503093,-0.128124
&spn=0.010205,0.027895&z=16

I have highlighted the relevent fragment. In this case the longitude is 51.503093 and the latitude is -0.128124.

With these values we need to add a few lines to the beginning of the map.js file.

var latitude = -0.128124.;
var longitude = 51.503093;
var zoom = 13;

Now alter the script that sets the centre location to the following.

var location = new GLatLng(latitude, longitude);
map.setCenter(location, zoom);

Now when you load the map it should be centred around the point you specified.

Step 4 - Adding a Marker

Adding a marker is very simple. Just add the following code to your JavaScript file at the end of the load() function. This will add a marker at the same location as the map is centered.

var marker = new GMarker(location);
map.addOverlay(marker);

Load up your map in your browser and you should see you map focused on and marking the location you specified. Magic.

As you can see the amount of code involved in this is quite small considering the visual complexity of the effect. The Google Maps API allows you to tell it what you want it to do in simple terms while it does all the hard work in the background.

This example map would be perfect on a company website to show the location of an office or shop or simply to point out a landmark or a place you have visited. A picture (or map) is worth a thousand words! In future tutorials we will look at more advanced techniques like information bubbles, multiple points, interacting with the server and geocoding.

Nov05

Upgrading to Ubuntu Intrepid Ibex

at 6.53pm

The latest version of Ubuntu, 8.10 (also known as Intrepid Ibex), has been out for a few days now and I was waiting for the update manager to tell me the upgrade was available. When this didn’t happen I tried to find out why.

It turns out that version 8.04 (Hardy Heron) was what Ubuntu call a Long Term Support release which is why you often see 8.04 followed by the acronym LTS. For this reason, by default, Hardy Heron will not by default offer the new version as an upgrade in the update manager. This can be fixed of course and here’s how:

  1. Go to the Software Sources item in the menus:
    System -> Administration -> Software Sources
    
  2. Now select the Updates tab and change the option at the bottom called ‘Release upgrade’ from ‘Long term support releases only’ to ‘Normal releases’ and then accept the changes.
  3. Now go back to the Update Manager in
    System -> Administration -> Update Manager

    and the option to upgrade will be present and you can upgrade as normal. Simple.

Nov02

.local Domains on Ubuntu Desktop

at 7.43pm

My web development environment usually consists of an Ubuntu machine set up with a LAMP stack using Apache virtual hosts and a simple DNS setup. I tend to use a .local extension to the domains to make them easy to access and to compare to their online counterparts. For example I use oneangrydwarf.local for the testing environment for this site.

The problem comes when I set this up on an Ubuntu Desktop installation (as opposed to an Ubuntu Server installation) which I prefer simply for ease of use. Unfortunately a program called Avahi stands in my way by hijacking the top-level domain and overriding the DNS records. Apparently Avahi is used for “service discovery on a local network” and is an integral part of Ubuntu Desktop (attempting to remove it also removes the desktop environment) but personally I don’t need it and it gets in my way. For anybody else having this problem here’s how to fix it, firstly temporarily (if you need Avahi normally but just want a quick fix) and secondly a more permanent solution.

  1. Stop the Avahi daemon by typing
    sudo /etc/init.d/avahi-daemon stop

    This will only solve the problem until the server is rebooted as the process is integral to Ubuntu Desktop. Attempting to uninstall Avahi will also uninstall the Ubuntu Desktop.

  2. Tell Ubuntu to check the DNS server first by editing /etc/nsswitch.conf and changing the line that reads
    hosts:  files mdns4_minimal [NOTFOUND=return] dns mdns4

    to

    hosts: files dns mdns4_minimal [NOTFOUND=return] mdns4

    Now restart Avahi with the command

    sudo /etc/init.d/avahi-daemon restart

    See Avahi and dot-local addresses on Ubuntu Gutsy from The Fifth Wheel of andrewg for more details.

Posted in Ubuntu, Web | 1 Comment »
Oct20

Syntax Highlighting with Wordpress

at 7.43pm

No programming blog is complete without decent syntax highlighting so it seemed reasonable to expect there to already be a good plug-in available to provide the functionality I need. Sure enough, a quick search resulted in finding WP-Syntax. The plug-in is based on GeSHi which started as the syntax highlighter for phpBB and is now a fully independent project with support for most major languages.

As a demonstration (and a test) here’s some PHP:

public class Foo {
   public function __construct($bar) {
      echo 'Hello World!';
   {
}

and some CSS (with line numbers):

1
2
3
4
   .foo {
      color: #FFFFFF;
      height: 100px;
   }

I think that’s enough of a demonstration and promotion of the previously mentioned projects but expect to see some code related posts in the not-to-distant future.