Using CSS3 On Internet Explorer With PIE

Until a few hours ago some parts of this website used boring old images as buttons, however I’ve now started to bring this website into 2011 and swap them out for something far cooler and semantically better. These are now links styled up with CSS3.

The buttons had rounded corners and a drop shadow, easy to create using tools like Adobe’s Photoshop, but a pain to do before CSS3. With CSS3, we can use the following to add the curved border and drop shadow.

-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-box-shadow: rgba(0,0,0, .5) 3px 3px 6px;
-moz-box-shadow: rgba(0,0,0, .5) 3px 3px 6px;
box-shadow: rgba(0,0,0, .5) 3px 3px 6px;

OK, we’ve had to use a few custom extensions for Mozilla and Webkit based browsers, but it works. However, as always, Microsoft’s Internet Explorer doesn’t want to play nicely and isn’t able to support these features. There are a few work arounds, but at present the best seems to be PIE – Progressive Internet Explorer.

PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features. At present it has full or partial support for border-radius, box-shadow, border-image, multiple background images and linear gradient background images.

It’s easy to add PIE as an HTML Component (HTC), you just need to reference it in your CSS.

behaviour: url(PIE.htc);

As if by magic, those CSS3 features will start working in Internet Explorer.

You will need to download PIE and host it somewhere. You will also need to make sure that your web server is setup to serve HTC files with the content-type header of “text/x-component”. If you use Apache, you can use the following line in your config, or in a .htaccess file.

AddType text/x-component .htc

Access The Bootstrap From A Zend Framework Action Controller

When working with the Zend Framework you often need access to the Bootstrap to fetch resources. The classic way to get the bootstrap in most of the examples for the Zend Framework is like this…

$bootstrap = $this->getBootstrap();

However, this method is not globally available, so from an action controller for example, that method would fail. There is an alternative way to get access to the Bootstrap.

$bootstrap = $this->getInvokeArg('bootstrap');

This works because Zend_Application_Bootstrap_Bootstrap registers itself as the front controller parameter bootstrap, which lets us access it from the router, dispatcher, plugins and action controllers.

So, if I had a twig resource I wanted to access from an action controller, I could use the following code…

$bootstrap = $this->getInvokeArg('bootstrap');
$twig = $bootstrap->getResource('twig');

or by chaining accessors, I could reduce this to one line…

$twig = $this->getInvokeArg('bootstrap')->getResource('twig');

For more information, read Zend Framework’s Theory of Operation.

Using A T-Mobile Web ‘N’ Walk III USB Dongle On A Mac

This post is copied almost word for word from a discussion on the T-Mobile support forums with the original answer supplied by Chris Dobson – FIXED! Web’n’ Walk III stick (Huawei E170) for Mac OS X Snow Leopard. I have copied it here as content on forums has a nasty habit of disappearing, and have tweaked it in a couple of places. I can confirm it works with my Web ‘n’ Walk III stick on my 2011 Macbook Pro with Mac OS X 10.6.7 . Now over to Chris…

I’ve finally found a fix for using your Web’n’ Walk Stick in Snow Leopard. It’s a bit long winded but I’ll try and explain as best I can, but it will do until there is an official fix. Make sure your dongle is not plugged in when you start. Please be aware that t-mobile is not responsible if you mess something up, I am just a customer offering advice. Also you need to be running the 32-bit kernel mode for this to work.

Note: You can check if you are running in 32 or 64 bit mode by clicking the Apple logo on the top left of the menu bar, then More Info…, then Software. If the line “64-bit Kernel and Extensions” says “Yes” you are in 64bit mode, if it says “No” you are in 32bit mode. To change to 32 bit mode, you need to power on your Mac while holding down the 3 and 2 keys. To change to 64 bit mode hold down 6 and 4 during power on.

Download: www.t-mobile.at/officetogoSW/MM_2_0_3.dmg

Double click on the white ‘drive’ icon that will appear on your desktop and look for the package called ‘MM 2.0.3 Intel… Right click this software package and choose ‘show package contents’. Navigate to contents>resources and then double click the file named HuaweiDataCardDriver(2.6)…. Then proceed to install this as you would with any other software.

Plug in your dongle, and you will be prompted to enter the ‘Network Preferences’ utility’. You now have an item added to the list on the left called ‘Huawei Mobile” Click on this to configure it.

Add *99# into the box where it says Telephone Number

Tick the checkbox to show modem status in the menu bar (handy for easy connection)

Hit Apply to save these settings.

With any luck, you should now be able to connect using this new connection you’ve created.

A UDP Joke

I can’t claim credit for it, but as someone who’s done a bit of UDP programming lately, it made me chuckle.

“The problem with a UDP joke is that you can’t be sure anyone got it”.

Alternatively…

“If you don’t get a UDP joke, just wait for the next one”.

JavaScript Date, Time And Node.js

JavaScript Dates and times seem to pose a bit of problem to JavaScript developers. Looking at the access logs to my website, one of the most popular popular pages is about Writing a Daytime Server In Node.js. However, most people are actually searching for how to use a JavaScript Date in Node.js.

I thought I’d put together a few notes for those developers struggling use dates and times in node.js.

The good news is that as node.js is just a server side version of Google’s V8 JavaScript engine, node.js developers have full access to the JavaScript Date object.

A date in JavaScript is represented behind the scenes as the number of milliseconds since midnight on January 1st, 1970 (01-01-1970 00:00:00).

Initializing A JavaScript Date

To create a new Date object in node.js, or JavaScript in general, just call it’s initializer.

var now = new Date();
var now = new Date(milliseconds);
var now = new Date(dateString);
var now = new Date(jsonDate);
var now = new Date(year, month, day);
var now = new Date(year, month, day, hour, minute, second, millisecond);

dateString must be an RFC1123 compliant timestamp, I’ll come to jsonDate in just a minute.

Remember that Date objects can only be instantiated by calling Date or using it as a constructor; unlike other JavaScript object types, Date objects have no literal syntax.

Dates In JSON

Node.js offers great native JSON support, and that extends to encoding and decoding dates. Dates were not part of the original JSON specification, so it’s always been down to developers to decide on the best approach in the past. Things have changes, and now the standard is to use an ISO 8601 formatted date string.

To convert a date to JSON format, we can use the toJSON method of the Date object. This is a fairy new addition to the JavaScript language and is only supported in version 1.8.5 and above. Thankfully node.js supports this out of the box.

var now = new Date();
var jsonDate = now.toJSON();

To convert back, we just pass an ISO 8601 date string back into the JavaScript Date constructor.

var jsonDate = "2011-05-26T07:56:00.123Z";
var then = new Date(jsonDate);

Getting Specific Date Details

The JavaScript object provides various getters to extract information from the Date object. These include getDate to get the day of the month, getMonth to get the month (more on that in a minute), getFullYear to get the year (more on that in a minute as well), getHours, getMinutes, getSeconds, getMillisconds, as well several more.

There are a few gotcha’s here. The one that gets most people firt time, is that getMonth returns the current month, but months according to the Date object run between 0 and 11 instead of 1 to 12 as you are probably used to. The second is that the getYear method only returns a two digit date, you really want to use getFullYear as that returns a four digit date.

Setting Specific Date Details

To compliment the getters, there are mirror setter functions. These include setDate, setMonth, setFullYear, setHours. setMinutes, setSeconds, setMilliseconds as well as several more.

Manipulating Dates

You will probably want to manipulate the Date objects you have.

Let’s see what the time is in 6 hours time.

var myDate = new Date();
myDate.setHours(myDate.getHours() + 6);

But what about the time in 100 hours time? No problem…

var myDate = new Date();
myDate.setHours(myDate.getHours() + 100);

The JavaScript Date object is clever enough to change the date correctly.

I hope this has given you a few pointers on how to use dates and times in node.js.

Detecting Retina Displays From JavaScript And CSS

I was looking at how to target Apple’s retina display for high resolution web pages earlier.

My first attempt was to look at the user agent string, but an up to date iPhone 4 sends the same string as an up to date iPhone 3GS.

A quick look around the internet reveals the solution for JavaScript is to actually use the window.devicePixelRatio property.

For a standard browser, this will be 1. However, on a retina display it will 2 – meaning twice the pixels.

For example…

if (window.devicePixelRatio >= 2) {
// retina display
} else {
// standard display
}

You can check your current devicePixelRatio using the following…

<script type="text/javascript">
document.write("Your browser has a devicePixelRatio of " + window.devicePixelRatio + "");
</script>

Apple aren’t the only ones using this in their webkit based browsers, you can read how to target device pixel density on Android. Android defines a density of 1 to be medium density, anything 1.5 or above as high density and anything under 0.75 to be low density.

On the client side we can use this to decide if we want to bring in retina quality imags, or standard ones. There is a jQuery plugin called Retina that does this.

If want to to pass display information back to the server to decide what images to render, this is a bit more complicated.

The best way to approach this would be to have a JavaScript set a cookie containing the devicePixelRadio and have the server read this back. A quick Google reveals that Ben Doran is doing just this, Detecting the iPhone4 and Resolution with Javascript or PHP.

Here’s Ben’s example code (slightly tweaked)…

<?php
if( isset($_COOKIE["pixel_ratio"]) ){
$pixel_ratio = $_COOKIE["pixel_ratio"];
if( $pixel_ratio >= 2 ){
echo "Is HiRes Device";
}else{
echo "Is NormalRes Device";
}
}else{
?>
<script type="text/javascript">
writeCookie();
function writeCookie()
{
the_cookie = document.cookie;
if( the_cookie ){
if( window.devicePixelRatio >= 2 ){
the_cookie = "pixel_ratio="+window.devicePixelRatio+";"+the_cookie;
document.cookie = the_cookie;
location = '<?=$_SERVER['PHP_SELF']?>';
}
}
}
</script>
<?php

A different approach could be to use CSS and media types. Webkit browsers like Safari on an iPhone have -webkit-min-device-pixel-ratio, Gecko browsers like Firefox have -moz-device-pixel-ratio.

An example using this approach on webkit could be

<link
rel="stylesheet"
type="text/css"
href="/css/retina.css"
media="only screen and (-webkit-min-device-pixel-ratio: 2)"
/>

Mushroom And Rocket Risotto Recipe

Here is my recipe for a delicious mushroom and rocket risotto.

I’d recommend getting a good selection of different types of mushroom, fresh or dried (if dried, keep the rehydration liquid for stock), though it does work well with common button mushrooms if you can’t get anything else.

You will need the following ingredients…

  • 300g Arborio Risotto Rice
  • 750ml Chicken or Vegetable Stock
  • 150ml White Wine
  • 1 Small Onion
  • 2 Cloves of Garlic
  • 100g Wild Rocket
  • Lemon Juice
  • 50g Butter
  • Splash of Olive Oil
  • Parmesan Cheese
  • Salt
  • Freshly Ground Black Pepper
  • 20 or 30 Mushrooms roughly chopped

The main thing to remember with any risotto is that when you add the stock, the stock must always be hot, else you bring down the temperature of the risotto and the dish doesn’t cook properly. I keep my stock simmering in a pan next to the risotto as it cooks.

  1. Finely chop the onion and garlic.
  2. Melt the butter with the olive oil, and cook the onion and garlic with a good splash of lemon juice on a gentle heat until soft.
  3. Add the rice and cook until the edges start to go translucent.
  4. Turn up the temperature, add the wine and cook for a couple of minutes while stirring continuously.
  5. Turn down the temperature again, and add a bit of stock, stirring until absorbed.
  6. Keep doing this until the stock is used up and the rice soft, probably 20 to 30 minutes time.
  7. Just before the last stock goes into the rice, fry off the mushrooms in a splash of olive oil
  8. When the rice has cooked, add the mushrooms, rocket, a good grating of parmesan cheese, salt, pepper and another splash of lemon. These are all to your taste so add what you like here.
  9. Once the rocket has wilted into the risotto, serve it up.

This dish should serve between 2 and 4 people, depending on how hungry everyone is.

Writing A Daytime Server In Node.js

I’ve previously written about using node.js as a simple UDP listener, now I thought I’d expand on this and give an example of a node.js application that works as both a UDP and TCP server.

A simple service that offers both UDP and TCP connections would be the Daytime Protocol, as defined in RFC 867. It listens to port 13 for both TCP and UDP connections, and returns the current date and time. Your local computer may well have this function enabled, to test the TCP version, you can simply telnet to port 13 and see what is returned.

telnet localhost 13

If you find you don’t have a local Daytime service running, try calling the one at time.ien.it, you should see something like this…

$ telnet time.ien.it 13
Trying 193.204.114.105...
Connected to ntp.ien.it.
Escape character is '^]'.
12 APR 2011 18:51:11 CEST
Connection closed by foreign host.

As you can see it simply returns the date and time before closing the connection.

We could write something like this very easily in node.js. In this case we’ll return the date in JavaScript’s UTC string format instead to keep it simple.

var net = require('net');
var port = 1300;
var now = function() {
  var date = new Date();
  return new Buffer(date.toUTCString() + "rn");
};
var tcpserver = net.createServer(function(c) {
  c.write(now());
  c.end();
});
tcpserver.listen(port);

We can test this by telneting to localhost on port 13

$ telnet localhost 1300
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Tue, 12 Apr 2011 17:17:55 GMT
Connection closed by foreign host.

Let’s take a quick detour into what the code is doing if you’ve not used node.js for any network programming before.

We require('net') so we can use node.js’s network socket support.

The now() function simply returns a Buffer with the current UTC date and time string in. A Buffer in node.js refers to the raw memory used behind the data, in this case our string with the date and time in.

Finally, we create the server, and add a callback function that is called when something connects to the socket. In this case we’re just writing out the contents of the now() function and ending the connection. Last but not least, we tell the socket which port to listen on.

We can see that this code works, but the Daytime protocol also offers a UDP service on the same port that can return the date and time string to a client.

Let’s add in some code to support this. We’ll assume our now() function and port variable are available already.

var dgram = require('dgram');
var udpserver = dgram.createSocket("udp4", function(msg, rinfo) {
  var daytime = now();
  udpserver.send(daytime, 0, daytime.length, rinfo.port, rinfo.address);
});
udpserver.bind(port);

So what is going on here? Well like the TCP code, we have to require('dgram'); to have access to node.js’s UDP support.

Next we create the socket and create a callback function that returns the date and time string back to the IP address and port of the calling computer. Finally we bind this to the port so we start listening for messages.

It’s harder to test a UDP server as we can’t telnet in, we will have to write a simple UDP client to send a blank message to the server and print out any replies to the console.

var dgram = require('dgram');
var message = new Buffer(" ");
var server_ip = '127.0.0.1';
var server_port = 43278;
var client = dgram.createSocket("udp4");
client.on('message', function (msg) {
  console.log(msg.toString());
  client.close();
});
client.send(message, 0, message.length, server_port, server_ip);

When you run this client on the same machine as your server you should get back the current date and time.

Here’s the final code for our Daytime server.

var net = require('net');
var dgram = require('dgram');
var port = 1300;
var now = function() {
  var date = new Date();
  return new Buffer(date.toUTCString() + "rn");
}
var tcpserver = net.createServer(function(c) {
  c.write(now());
  c.end();
});
tcpserver.listen(port);
var udpserver = dgram.createSocket("udp4", function(msg, rinfo) {
  var daytime = now();
  udpserver.send(daytime, 0, daytime.length, rinfo.port, rinfo.address);
});
udpserver.bind(port);

Using PHP To Send A UDP Message

Previously I’ve written about sending UDP datagrams using Perl and JavaScript with node.js.

As I’ve been using a lot of PHP recently, I thought I’d show how to send data over UDP using PHP.

If you’ve not come across UDP before, it’s a simple protocol for sending messages over the internet that aren’t guaranteed to arrive. You just fire them off and hope they arrive.

The previous examples showed sending a simple heartbeat message, a string simply saying “PyHB”, to a server listening on port 43278. I’ll do the same in this example.

Firstly we’ll setup a few variables saying where we’ll be sending the the message to, along with how often we want to send the message and what it should say.

$server_ip = '127.0.0.1';
$server_port = 43278;
$beat_period = 5;
$message = 'PyHB';

Now we have to create the socket, using the socket_create function. We need the domain to be of type AF_INET as we are using an IP4 address for our server, the type needs to be SOCK_DGRAM and the protocol needs to be SOL_UDPas we’re sending a UDP datagram.

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))

It’s time to send the message now, and to do this we can use PHP’s socket_sendto function. This function takes the parameters of the socket to send the message over, the message itself, the length of the message, some flags, the destination address of the message and the port to send it to. We’re not setting any flags so we can just set this field to 0. The following code will do the trick.

socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port);

Let’s wrap this up in a loop that sends the message every $beat_period seconds.

<php
$server_ip   = '127.0.0.1';
$server_port = 43278;
$beat_period = 5;
$message     = 'PyHB';
print "Sending heartbeat to IP $server_ip, port $server_portn";
print "press Ctrl-C to stopn";
if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) {
  while (1) {
    socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port);
    print "Time: " . date("%r") . "n";
    sleep($beat_period);
  }
} else {
  print("can't create socketn");
}
?>

This code is run on the command line, and not via a web server.