A family member requested I write them a simple windows program to help them with some medically-prescribed breathing exercises. For the exercise (which is designed to lower blood pressure) you have to breath in for six seconds, and out again for six seconds. In the absence of a commercial timer available to do this, a dedicated timer program on PC is the next best thing. The program simply displays a bar-chart type graphic with the bars appearing and disappearing to indicate the six second intervals.

Screenshot

A tiny project like this was the perfect opportunity to take the newly-released VS C# Express 2008 for a spin. Initial impressions are good, just like Express 2005 almost everything is there for professional development. It offers both Windows Forms and WPF as options on the New Project wizard, but it seems only to offer 3.5. In other words there seems no easy way of targeting 2.0 or other .NET versions from the wizard. I can confirm that 2.0 projects do load though (after running the conversion wizard) so it must be possible.

I like the WPF designer and the massive flexibility that WPF gives the developer in UI development. For this application, it was possible to add geometric shapes to the interface, which would have been hard in the Windows Forms designer. Also it meant that the window can be set to scale when resized. Being able to switch between a massive timer display and a tiny one could be very useful for users of a program like that.

For reference, the way to have WPF content automatically scale is to wrap the content in a tag. Note that for me, this meant the designer no longer shows the embedded content which is annoying. But it does mean it automatically scales nicely at run time.

Installer for One to Six program

I’ve written a simple puzzle game based on an idea I’ve been knocking around. The idea is inspired by slide puzzles and the Rubik’s Cube. Also a lesser-known puzzle called the Rubik’s Clock that I loved as a child.

The objective is to return a grid of numbers to its original form by rotating individual 2 x 2 square bocks by 90 degrees. Hard to explain but give it a go, you’ll work it out quickly I’m sure

Number puzzle grid

The grid starts out straight. You can scramble it yourself or hit the ‘Spin’ button and have it done for you (hit it again to stop the scrambling). You can also experiment with using the slider to create grids of different sizes.

It is worth pointing out something though. When I came up with the idea I thought that it would be about as difficult to complete as a standard slide puzzle. Wrong. It seems very, very difficult. People tend to get very stuck on the last row. In fact, based on a day’s play testing, nobody has yet even completed a 3 x 3 grid.

So give it a try, you could be the first.

Qindar 3.0

I received another request by email to update one of my wordgame programs to use the latest CSW dictionary. This time the program was Qindar for Windows (as opposed to my AJAX website Qindar.net).

As it happened I’d been sitting on an updated of Qindar for Windows for a while. Not only had I modernised the dictionaries I’d also added an analyse mode where the valid games for each turn can be viewed after a game. (They can even be viewed during the game if you turn the option on in the settings).

Not only that you can perform a basic “simulation” on moves to estimate the relative strategic value of each alternative.

Other improvements include a challenge mode other than ‘void’, plus the bots from Qindar.net. As all my wordgame programs use the game logic engine it’s easy to port over the benefits.

I’d not put this version out because I’d put a few bugs in somewhere along the line so I wanted to polish it a bit first. I’ve done that now, so I present to you Qindar 3.0. (click) Please do email me or comment here if you find any bugs with it.

Stressing about standard code appearance in a large team project is fairly low on my list of priorities, but it is on the list.

I’m happy to change my style to fit in, but as every project has a different ‘standard’, it’s annoying to have to keep changing.

“The wonderful thing about standards is that there are so many of them to choose from.” Grace Hopper

Visual Studio has, from VS 2002, offered a facility to ‘format’ some code files. This format actually means convert the whitespace to a standard form. This form is apparently of Microsoft’s own design.

I was delighted to see this feature, however, as it meant that there was an easy way that a common format for whitespace could be set in a large team. Yes there are formatting utilities out there, and VS is just one of the many IDEs available. VS is however a very popular IDE in the world of commercial development.

The actual keypresses and modes vary by language, VS version, and configuration. In some modes it is automatic, in others you can press CTRL-E-D. You can format C++, C#, Visual Basic or XML. The .NET languages have controllable options and seem to format more effectively.

Over the last couple of years I’ve got so familiar with the VS format that I apply the style manually when working with non-VS languages like Javascript, Actionscript and PHP.

I have reversed engineered the default VS style so that you can do the same if you like! These are the basics. The general rule is that all tabs and spaces are stripped with the exception of:

Indentation

Braces appear on a line of their own (controversial!) at the same indentation level as the parent. Block content appears indented.

  1. class MyClass
  2. {
  3.     int Method()
  4.     {
  5.         return 3;
  6.     }
  7. }

Case labels and content are each indented.

  1. switch (name)
  2. {
  3.     case "John":
  4.         break;
  5. }

Comments appear in the first column without indentation.

Indentation is not changed for the second and further lines for any instruction that spills over multiple lines. The default however is that it is indented from the first line.

  1. {
  2.     bool receiveMessage( Stream & stream,
  3.         int & header, int & size );
  4. }

Spaces after keywords

Spaces are placed between keywords (if, switch, for, return, etc.) and the content that follows, unless it is ;. So you have

  1. return (x);

.. which contrasts with no space in a function call such as ..

  1. SomeFunc(x);

Spaces between mathematical operators

Brackets are not followed by spaces, but a single space appears between other mathematical operators.

  1. int y = (3 + 4 / 2 - 6 + (4 + 2 * array[4]));

Spaces after commas and semicolon separators

  1. SomeFunc(4, x, 5);
  1. for(int count = 0; count != 9; count++)
  2. {
  3.  
  4. }

That’s pretty much it. It’s a simple summary, no doubt a more accurate, formal one could be prepared. But that’ll give you the basics

Other aspects of code standardisation such as standard naming conventions are not currently supported by VS. It would be interesting to see an optional scheme where violations of some convention could be flagged as errors.

Recently I looked into some reported problems with my word game site Qindar.net and the Safari browser. This was a bit easier for me since Apple released a Windows version of Safari (which, albeit arguably surplus to requirements, is actually a very nice, usable browser on Windows).I discovered that the technique I was using to work out which method of event attachment to use was flawed and was failing for Safari. So I refined it slightly to fix the problem.

The problem is that Javascript on Firefox, Opera and Safari support the “W3C DOM Level 2 event binding mechanism”, which uses a function on DOM elements called addEventListener. Internet Explorer however uses a technique that was apparently from before that particular standard was drawn up, employing a function called attachEvent. In addition, the names of the events are different. For instance, IE uses events such as “onmousemove”, “onmouseup”, but the other browsers omit the “on” and name these events “mousemove” and “mouseup”.

Curiously, Opera is the only browser to support both styles.

The simplest and safest way of working out which one to use is simply to test for the existence of a function called addEventListener. I quite like this method because it works on the latest version of the big four browsers, and IE 6, without having to do any browser version probing.

For instance, here is how to add focus and focus lost events to a page in a way that will work on all modern browsers:

[Javascript]
if (window.addEventListener != null)
{ // Method for browsers that support addEventListener, e.g. Firefox, Opera, Safari
window.addEventListener(“focus”, FocusFunction, true);
window.addEventListener(“blur”, FocusLostFunction, true);
}
else
{ // e.g. Internet Explorer (also would work on Opera)
window.attachEvent(“onfocus”, FocusFunction);
document.attachEvent(“onfocusout”, FocusLostFunction); //focusout only works on document in IE
}
[/Javascript]

This is how to add mouse events:

[Javascript]
if (document.addEventListener != null)
{ // e.g. Firefox, Opera, Safari
document.addEventListener(“mousemove”, MouseMoveFunction, true);
document.addEventListener(“mouseup”, MouseUpFunction, true);
}
else
{ // e.g. Internet Explorer (also would work on Opera)
document.attachEvent(“onmousemove”, MouseMoveFunction);
document.attachEvent(“onmouseup”, MouseUpFunction);
}
[/Javascript]

To remove the mouse events, I recommend…

[Javascript]
if (document.removeEventListener != null)
{ //e.g. Firefox, Opera, Safari
document.removeEventListener(“mousemove”, MouseMoveFunction, true);
document.removeEventListener(“mouseup”, MouseUpFunction, true);
}
else
{ //e.g. Internet Explorer (also would work on Opera)
document.detachEvent(“onmousemove”, MouseMoveFunction);
document.detachEvent(“onmouseup”, MouseUpFunction);
}
[/Javascript]

I personally pray there comes a time when these kinds of workarounds are not required. In the mean time, this will have to do.

Wikipedia has grown from one of many interesting websites to being one of the most famous sites on the Internet. Millions of volunteer years have been invested over the years, and the pay off is what we have today – a wealth of factual data in one place.

When Wikis were a new concept, many predicted they would descend into chaos as they grew. In the case of Wikipedia the reverse is true. It seems to become increasingly well organised as the site develops. Rather than becoming more jumbled, the natural development of article conventions and the more planned use of standardised templates has created an increasingly neat and consistent structure.

This careful organisation of the prose leads to the interesting possibility of extracting more structured data from Wikipedia for alternative purposes, while staying true to the letter and spirit of the GFDL under which the material is licensed.

There’s the potential for a kind of semantic reverse engineering of article content. HTML pages could be scraped, and pages scoured for hints as to the meaning of each text fragment.

Applications could include loading articles about a variety of subjects into structured databases. Subjects for this treatment could include countries, people, chemical elements, diseases, you name it. These databases could then be searched by a variety of applications.

I’ve knocked up a simple page that gives a kind of quasi-dictionary definition when a word is entered. It looks at the first sentence of the Wikipedia article, which typically describes the article topic concisely.

I’ll show here how the basic page scrape works, which is actually very easy with PHP, its HTML reading abilities and the power of xpath.

  1. $html = @file_get_contents(“http://en.wikipedia.org/wiki/France”); will pull down the HTML content of the Wikipedia article on France.
  2. $dom = @DOMDocument::loadHTML($html); will read the HTML into a DOM for querying.
  3. $xpath = new domXPath($dom); will make a new xpath query.
  4. $results = $xpath->query(‘//div[@id=”bodyContent”]/p’); will find the first paragraph that is a direct child of the div with the id “bodyContent”. This is where the article always starts in a Wikipedia article page.

I then perform some more processing on the results including contingencies for if any of the steps fail. For instance to make the definitions snappier reading I strip any text in brackets, either round or square. There’s also some additional logic to pick the first topic in the list if the page lists multiple subjects (a “disambiguation” page). Predicting the Wikipedia URL for a given topic also involves a small amount of processing.Anyway, when you ask the page “what is France”, it will reply..

France, officially the French Republic, is a country whose metropolitan territory is located in Western Europe and that also comprises various overseas islands and territories located in other continents.

Can’t argue with that!

Edit, 1st March: By request, here is the source of the WhatIs application. It will work in any LAMP environment but the .sln file is for VS.PHP under Visual Studio 2005.

Source of WhatIs

In my web wordgame Qindar.net I wanted to allow the players to use the keyboard to place words on the game board. This included use of the arrow keys to navigate, and the backspace key to ‘delete’ wrongly placed letters.

The problem is that even when this is handled in JavaScript, most browsers still catch the backspace key and interpret it as a user request to go back to the previous page. Boom! There goes your game page, and one annoyed user.

I did find a way of masking the backspace key that works in all the browsers I have tested it against. The trick for most browsers is to override the onkeydown event, check for event number “8” and return ‘false’ from that event. This signals to the browser not to process that key.

As often happens one particular browser is troublesome, in this case it was Opera, that needed “onkeypress” overriding rather than “onkeydown”.

Yesterday I had an email query recently asking how this was done so I’ve detailed it here.

There’s a demo here. Select ‘View Source’ in your browser to see how it’s done.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" >
  3. <head>
  4.     <title>Backspace Browser Trap Demo</title>
  5.  
  6. </head>
  7. <body>
  8.  
  9. <p>Try pressing backspace on this page.</p>
  10. <p>Note you can still go 'back' with Alt + Left</p>
  11. <p id="keypressed"></p>
  12.    <script type="text/javascript" language="javascript">
  13.    
  14.     // function to possibly override keypress
  15.     trapfunction = function(event)
  16.     {
  17.         var keynum;
  18.        
  19.         if (window.event) // eg. IE
  20.         {
  21.             keynum = window.event.keyCode;
  22.         }
  23.         else if (event.which) // eg. Firefox
  24.         {
  25.             keynum = event.which;
  26.         }
  27.  
  28.         if (keynum == 8) // backspace has code 8
  29.         {
  30.             document.getElementById("keypressed").innerHTML = "Backspace pressed";
  31.             // display a message
  32.  
  33.             return false;
  34.             // nullifies the backspace
  35.         }
  36.         return true;
  37.     }
  38.    
  39.     document.onkeyup = function(event)
  40.     {
  41.         document.getElementById("keypressed").innerHTML = ""; // clear the message
  42.        
  43.         return true;
  44.     }
  45.    
  46.     document.onkeydown = trapfunction; // IE, Firefox, Safari
  47.     document.onkeypress = trapfunction; // only Opera needs the backspace nullifying in onkeypress
  48.    
  49.     </script>
  50.  
  51. </body>
  52. </html>

Two of my hobbies are programming, and trying to improve my Scrabble performance by cramming all the playable short words into my brain. It seems natural that I’d try to combine the two activities.

About five years ago I wrote a program to combine these and my shiny new Palm OS-based Sony Clie. It was a game to test my knowledge of the three letter words. It fires potential three letter word combinations at the player, who has to determine if the words can legally be played, according to the dictionary de jour.Tapping out guesses and trying to get a good run is bizarrely hypnotic. Particularly as the definitions are supplied after each guess. I used it constantly for about a year, whenever I was on the move, banging away at the screen as I stumbled down the street. Hopefully passers by would think I was “texting”, rather than learning Scrabble words which is of course terribly sad. I beamed it on to a few other players at Scrabble meets (PalmOS devices are popular among Scrabble players).

wquiz for PalmOSFive years on my Clie isn’t so shiny any more (in fact it finally died about a year ago after many years fine service). I’m still a Scrabble player, but this time I use a Windows Mobile smart phone for learning on the go. That’s nice because I can use a common .NET library for my dictionary utilities. On that subject, the Scrabble community has changed the official word list to CSW (Collins Scrabble Words) which required every word tool or game to be updated.

So wquiz has become obsolete. Which leads me on to the point of this post. Having given the program to a few people here and there it appears to have developed a miniature but vocal following. One good friend of mine in particular has been politely asking me to update it for him for a while. I declined because I don’t have the Clie any more and I lost the SDK. But when he started offering to pay me I knew he was serious.

Anyway I dusted out the SDK (Metrowerks for PalmOS), fired up the emulator, got the dictionary list out and viola, here is the mighty “wquiz”, 2007 style, for CSW. I’ve linked it here as a .prc file, I think the PalmOS software will install it for you if you open it from your browser. Enjoy.

wquiz for PalmOS .prc file

If you’re developing web applications for inexpensive hosting there’s really only one option. LAMP stands for Linux, Apache, MySQL and PHP. It represents a set of technology that’s reliable, battle-tested and totally ubiquitous in the world of web hosting.

Bit like lots of developers you might be working on a Windows computer, using Microsoft software like Visual Studio. This doesn’t feel like the most natural environment for developing for a LAMP setup. There’s a definite draw towards IIS, ASP and MSSQL, the Microsoft alternative to LAMP. This Microsoft tech has a different set of strengths to LAMP, but look for compatible hosting and you’ll find it’s typically twice the cost.

WAMP menus

Fortunately you can and it’s not too difficult if you know what to install. A great free package called WampServer will set up and integrate Apache, MySQL and PHP in one go. What’s WAMP? It’s Windows Apache MySQL PHP. The bastard lovechild of two different schools of technology? Or a pragmatic way of combining the most common hosting technology with the most common desktop technology. You decide.

WampServer is ideal for developing on Windows before uploading your site to your Linux-based host. WAMP also comes with some nice configuration menus and the phpMyAdmin web console for MySQL. Get it here, and you can get started by putting the following index.php file in c:\wamp\www and pointing your browser at http://localhost.


<?php echo "hello world"; ?>

Visual Studio

How about using Visual Studio to develop and debug? I can recommend a product called VS.PHP that allows development of PHP applications within Visual Studio. It’s commercial, but it’s relatively cheap and there’s also a free trial available here. VS.PHP has its own Apache service and works very nicely out of the box. However you can configure the system to use WAMP’s Apache if you want to run your application alone or with other tools such as Dreamweaver.

Once you’ve installed VS.PHP and set up a project, this is how to set up debugging to use WAMP 1.7.3. These instructions assume that you store the project files and Visual Studio project files in a location such as c:\wamp\www\myproject, where myproject is the name of your project.

  • Download the php_dbg modules.
  • Copy the version for PHP 5.2.4. to C:\wamp\php\ext and rename it to php_dbg.dll.
  • In the WAMP system tray menu select PHP setting, PHP extensions, Add extension, and type php_dbg.dll.
  • From the WAMP menu Select Config files, and then php.ini.
  • Put the following lines at the bottom of your php.ini:
  • [debugger]
    debugger.enabled = true
    debugger.profiler_enabled = true
    debugger.JIT_host = clienthost
    debugger.JIT_port = 7869

  • Under the Resource Limits section of php.ini change memory_limit = 8M for memory_limit = 32M. (Debugging needs more memory).
  • Save your modified php.ini and restart WAMP from the system try menu.
  • In the properties of your VS.PHP project, select Debug then change Debug mode to External mode.
  • Change the Start Url to http://localhost/myproject/index.php, changing myproject to the name of your project.

You should now be able to set breakpoints and step through your WAMP-based PHP applications with Visual Studio.

Design

Adobe Dreamweaver is a very popular package for web design and also offers some nice visual tools to create simple data enabled pages. Unfortunately it defaults to use IIS on Windows. However if you’ve installed WAMP you can configure Dreamweaver to use its services. Combined with the previous approach this will give you a combined LAMP-ready debugging and design environment on a Windows computer. These instructions are for Dreamweaver CS. Again, I assume that you store the website files in a location under c:\wamp\www such as c:\wamp\www\myproject.

  • Select Manage Sites
  • In the HTTP Address box type http://localhost/myproject/index.php, changing myproject to the name of your project.
  • Select Next, and under the server technology select PHP MySQL.
  • Select Edit and Test locally.
  • Under the file location type C:\wamp\www\myproject\ (again, changing myproject ).
  • Select Next. Under the Root URL type http://localhost/myproject/ (again, changing myproject ).
  • Select Next twice, and then Done.

In Dreamweaver you can make use of the WAMP MySQL service to develop MySQL integrated Recordsets. You can also make use of the simple wizards in Dreamweaver to create HTML/PHP/MySQL log in services. Use the phpMyAdmin web admin under WAMP to set up a database, tables and a user for Dreamweaver to connect to. Then copy these details – alongside “localhost” as the MySQL server – in the Recordset configation windows in Dreamweaver.

In conclusion

So that’s it. You should be good to go for LAMP development on your Windows PC. Remember that your host is likely to have a different configuration of Apache and PHP with different versions, modules enabled and so on. Fortunately WAMP makes it quite easy to configure your local setup to match your host. Also look out for the fact that Windows isn’t cASe SenSItiVE at all on filenames, and this extends to Web hosting. Linux services generally are case sensitive by default. So if the live version of your application has problems locating files, that might be why.

Happy WAMPing!

FastGallery

Fast Gallery
I’ve recently published a Windows application that I wrote in .NET 2.0 (WinForms) to simplify the creation of HTML photo albums for putting on the web. I call it FastGallery, and it can be found … here.

I know there are a lot of similar apps out there, but I really wanted something that was very fast and simple to use. It also makes use of some of the special .NET controls I’ve been developing.

Newer entries »