Showing posts with label development. Show all posts
Showing posts with label development. Show all posts

Tuesday, 25 September 2007

OSS vs MS

I know what the problem is - connecting to my databases is unbelievably slow and then hangs when performing any tasks. The problem is that everything is proprietary Microsoft software.

The PC is running a version of Windows that I now know is not legit (it will be soon, but isn't right now). I'm in the process of getting it all sorted but I inherited this computer and it came with a dodgy install that I wasn't initially aware of.

This means that I can't run the latest version of the Microsoft database software (SQL Server 2005) and the previous version is buggy and causing this problem. This is really annoying. I've patched and updated the computer as best I can (in fact the latest update I can make is being installed now) but I'm not sure this will solve the problem. It's really getting on my tits and slowing down my work spending a day getting everything sorted.

I'm building a workaround on another computer but this is all woefully convoluted and a real pain in the arse. To have the separate pieces of software reliant on each other in this way is really annoying and frankly not good on behalf of the software builders.

What's more frustrating is that I've been playing with my new Ubuntu Linux computer and none of this is an issue. Everything's so open and easily updated as well as being free from any costs. Plus I'm not trying to get tied down into any sort of agreements on how (or how not) I'm supposed to use my own computer. There's definitely change afoot in the world of computers in a big way and it's manifesting itself in only 1/4 of the screens in our office now showing Microsoft products (and I'm a MS developer!). The majority are Macs but to be honest I've been looking at them and thinking about installing Ubuntu on one of those as well.

Yesterday I set Windows file sharing on the Macs so now I can switch files between OS X, Windows XP and Ubuntu Linux machines at the click of a button. Happily all the computers are fully integrated now and getting all this sorted has been in the most part really easy. Ubuntu was the easiest, then the Macs a close second but a way distant third was the PC. (Ubuntu uses Samba to share which comes pre-installed and pre-configured, Mac OS X uses its Windows File Sharing utility that you just switch on, with Windows you have to go crawling around network connections and user accounts to get it working as you want). I'm a happy geek.

So now it's time to put the plan to get my Microsoft workaround in place, it's not massively elegant but I've gone past caring - it just needs to work frankly. Hopefully soon the OSS (Open Source Software) guys will build a module that translates proprieatary MS SQL databases into MySQL (OSS) and also a query analyzer that translates MS SQL queries into MySQL queries. This should mean that I can run an ASP emulator like ChiliSoft as well as the proposed module and move all the code and projects onto a non-Microsoft platform. That'll save everyone an immense amount of money frankly.

I hope it gets rid of this rising tension too.

Wednesday, 25 July 2007

Doing the dev

My brain's fried. Proper fried. Was up til 4am trying to pull apart a 56MB MySQL database dump file on 3 different operating systems. Turns out that a combination of shell scripts, Red Hat Linux and nano text editor is the best combination for splitting the file up.



Mailed it into work and retired gracefully to bed ready for loading it into a database this morning. Turns out the data's corrupt in it and so Chris and I have been trying to sift and clean it this morning. Bah!

All this energy on geekiness is because of the contract which we've started recently. We're having to create a full mirrored dev environment from the production servers in the states to be able to work from here effectively. It needs to be done but my word it's really mentally fatiguing. The good news is that it only needs to be set up once - then it's just the fun part of development - building new things, making them work properly and making it look pretty. The bad news is that the rain and storms of late are no longer with us and there's blue skies and bright sunshine. I really want to get out and do some exercise and be in the fresh air but alas - have to prioritise.

Chris has chipped off to a music festival near Geneva this afternoon and after bashing my brains against the computer for another couple of hours, think I might knock work on the head, grab Digby the Dog and my iPod and go for a run up into the thinner air.

P.S. Had refried beans last night - went for mexican food around Brian's with two of his friends travelling around Europe who dropped in to Cham. Was very cool. My dad's given me a penchant for refried beans over the years and these ones imported via Switzerland were very good indeed. Happy days!

Wednesday, 20 June 2007

Now Wash Your Hands (NWYH)

I feel really sorry for Chris at the moment - client interfacing can be difficult at the best of times and his relationship with his current ones - Now Wash Your Hands (a new media company, here's their website) - has turned really sour. He's written about it on his blog about them not paying him for the work done.



I've got to say - I really like the Eastenders game that is the contract, it plays well and looks very cool. It's written using Adobe (formerly Macromedia) Flash and Flash Server with XML and all sorts of other natty technologies. It has a lot of streaming video, functional animation, scoring and all sorts. I think it's very cool and would slot into the Eastenders section of the BBC website very nicely indeed. Obviously there's a lot of stuff behind the scenes that I don't (and don't need to) know about but the whole thing looks pretty sketchy to me.

I hope it gets resolved soon, the situation's not doing either NWYH or Chris any favours as Chris is out of pocket with the months of work and Now Wash Your Hands are looking like one of the really bad, unreliable new media companies that's only held together by spin and bullshit.

Sounds like everyone needs to feel the love a little more.

Friday, 19 January 2007

The next generation

While I was away, I regularly wanted to check my email, the internet and various news and blog feeds but without all the hassle of finding an internet cafe every time. I already use Opera Mini on my mobile phone as the default web browser and it's damn good. I upgraded to version 3 before I left which supports all the usual suspects such as HTML and (limited but solid) CSS as well as fast searching of google/wikipedia down to the browser's homepage and also some very funky support of RSS and default image compression to reduce page load times of web pages.

I'd highly recommend it as a piece of kit - sure it's not going to be as easy to use as a keyboard for writing lengthy emails, but it's pretty easy to use the inbuilt predictive text feature on your phone to put words down. Gmail looks great in it and feeds are nicely displayed, it's also pretty quick download times and the big benefit of course is that it's available on demand with any connection signal.

I never used to be a big fan of browsers for phones, but maybe there just needed to be that development time to get them up to speed. With the new Apple iPhone (with an implementation of the Safari web browser) and Opera Mini dominating market share currently it looks like there's a shift in the traditional browser wars occurring. In fact a brief search on Google shows that the first result for "Internet Explorer for mobile phones" comes back with the Microsoft Mobile Explorer (MME) a product that was launched some 8 years ago in 1999 and no longer supported. It reminds me of IE where Microsoft always said that they weren't going to update the browser after IE6 and only security concerns really forced them into launching IE7 some years later, but this seems to be a total step away for them from a large browser market.

Maybe they're concentrating on their other areas of business such as their suite of operating systems, or their MS Office products but it seems strange to have the world's biggest software company ignore an entire section of the market almost identical to one they fought so hard to acquire in the 90's. I can understand it from a implementation point of view - IE interacts so much with the underlying operating system (e.g. ActiveX and the JScript engine) that it would be very, very difficult to get a standalone version of IE running. In fact the only one that springs to mind is IE5 for the Mac, a product that stopped being supported many moons ago. So maybe they just don't want the hassle and bad PR?

But it does show a few things that have changed over the years. Consumers are getting more technically savvy by having minimal problems adjusting to the products of the different browser vendors and the various implementations of those browsers. Microsoft is having its software base attacked from many angles with Firefox (side note: it's not going to be long before a mobile phone version of Firefox is released I'm sure) taking chunks of IE's browser market share, IBM's Lotus Notes making a comeback as well as OpenOffice and Google Docs and Spreadsheets taking share from Microsoft Office. Of course Unix and various flavours of Linux are holding their own against the Microsoft Server family, but also more recently Linux distributions such as ubuntu are eating into the desktop OS market - especially in the emerging markets of the developing world.

Microsoft still has an enormous user base and have for years been "under attack" commercially speaking, from smaller software vendors but it does seem that they've been losing the battle recently. There's a movement in progress towards a diverse software base from different vendors governed only by rules of connectivity (protocols) rather than just the one vendor pushing data around its own suite of applications. I like this idea that the rules are being mixed up - Google using the Internet for spreadsheets, there's online file storage in the form of Flickr and free/open source software such as OpenOffice and Opera Mini are competing as equals against proprietary software.

I truly believe that there's lots of business oppertunity out there as this shift takes place. "Web 2.0" (for want of a better description) has shown us data collation and display to be a valid software tool in itself and that self-growing online environments can spawn exponentially, linking to each other and having shared users and user accounts (look no further than blogger.com using Google accounts to login with). For me this is the true Internet - a proper interactive environment where you have access to any and all information you require, as well as the software to propogate this information - software that is free and easy to use.

With the slow release of end users from Microsoft's business model it gives us all more technical savvy from using a more diverse software base, as well as oppertunity to try and use software for free or very limited cost (OpenOffice, Flickr, ubuntu, blogger.com, etc) using this growing technical knowledge effectively and really pushing software creators to develop what we want and demand.

So that's all pretty chirpy really, everything's cool and funky. But here's the kicker - the software that needs to challenge Microsoft and the global market must be really top notch. The software must be efficient from the outset both in planning and the implementation of that planning. If one thing that has been shown time after time, as in the case with Microsoft's Internet Explorer, a badly conceived and implemented piece of software turns inflexible very, very quickly and this bad planning will come back and bite you in the ass - hard. Of course with IE, Microsoft were pushing a brand new market but because they had not been flexible initially IE7 still had implementation problems that were around since the very first versions. This can be shown by trying to install 2 versions of IE on the same machine without using any extra software. IE has ultimately been shown up to be hugely inflexible and technically very backward in core areas!

So I'm looking forward this year to building efficient, flexible software. Something that's going to challenge and push forward not regress and look backwards. This year sets the foundations for future standards. The aim is to build software that supports users with accesibility issues, it will support modern browsers, it will look to easily support future browsers and be clear and concise and efficient and really, really easy to use. It's time to build the next generation of the Internet and I'm damn proud to be a part of it.

Monday, 18 December 2006

Date reconverter

This is the date reconversion utility that I mentioned in a previous post. It takes similar arguments to the string.toDate() extension posted being in format dmy to represent day/month/year with this one having the optional argument t to denote the time. double a character means the result will be padded (so if the month is april using m will return 4 but mm will return 04). Pretty self explanatory, but I like the slickness of it. It could be better improved to organise times being formatted before dates, maybe something to consider at a later date.

/* Convert a date into a string.
* The format argument denotes the format (including padding zeros) the
* date is returned as. d - day, m - month, y - year, t - time.
* Double characters or quad y for year) will pad/extend that number.
* Optional: argument d_l is the date delimiter, t_l is the time delimiter.
* @param (String) format
* @param (String) d_l (Optional)
* @param (String) t_l (Optional)
*/
Date.prototype.convert = function(format, d_l, t_l) {
    var d_l = d_l || "/",
        t_l = t_l || ":",
        date = [],
        pad,
        d = this;
        
    pad = function(n) {
        return (n < 10) ? String("0"+ n) : n;
    }
    
    format = format.replace(/(m+)|(d+)|(y+)|(t+)/gi, function(s) {
        switch(s) {
            case "d": date.push(d.getDate()); break;
            case "dd": date.push(pad(d.getDate())); break;
            case "m": date.push(d.getMonth()); break;
            case "mm": date.push(pad(d.getMonth())); break;
            case "y": date.push(String(d.getFullYear()).substring(2, 4)); break;
            case "yy": date.push(String(d.getFullYear()).substring(2, 4)); break;
            case "yyyy": date.push(d.getFullYear()); break;
            case "t": date.push(d.getHours()+ t_l + d.getMinutes()); break;
            case "tt": date.push(pad(d.getHours()) + t_l + pad(d.getMinutes())); break;
        }
    });
    
    return (date.length < 3)
        ? null : (date.length == 3)
            ? date.join(d_l)
            : date[0]+d_l+date[1]+d_l+date[2]+" "+date[3];
}


// Usage:
var strDate = "4::13::1976 10.30";

// the previous post String extension to create a date object
var objDate = strDate.toDate("mdy");

// Use this date convert extension
var newStrDate = objDate.convert("ddmmyytt", ".", ":"); // outputs 13.04.76 10:30

Wednesday, 13 December 2006

I need a date!

OK, so the title of the post is catchy, but this isn't about an urgent yearning for the future Mrs Narg - actually there's always an urgent yearning for the future Mrs Narg but let's not go there. This is about converting a string to JavaScript date object.

The concept is you have a string and you just call this method with the sequence the day/month/year appear in (d, m, y respectively). This is regardless of any delimiters of your date (delimeters being the characters between the numbers) so this will work the same way for dates in formats such as: 13/04/1976, 1976-04-13, 04::13::1976
It's pretty neat, a regular expression just finds the numbers in the sequence and then uses the format (dmy, mdy, ymd or ydm) to find which number refers to what. It then has a look to see if a time has been passed. Again the delimiter splitting the hours from the the minutes is not important, but the order must be hours then minutes (ir hh:mm or h/m or hh-mm). If no time is found, then the time defaults to 00:00 on the date supplied. All this information is then used to create a standard date object and return it - if the process fails at any stage, the method returns null.


/*
Copyright (C) 2006 Martin Rudd

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
*/
String.prototype.toDate = function(format) {
    if(/(\d{1,4})[^\d]+(\d{1,4})[^\d]+(\d{1,4})([^$]*)/i.test(this)) {
        var date;
        switch(format) {
            case "dmy":    date = { year: RegExp.$3, month: RegExp.$2, day: RegExp.$1 };
            break;
            case "mdy": date = { year: RegExp.$3, month: RegExp.$1, day: RegExp.$2 };
            break;
            case "ymd": date = { year: RegExp.$1, month: RegExp.$2, day: RegExp.$3 };
            break;
            case "ydm": date = { year: RegExp.$1, month: RegExp.$3, day: RegExp.$2 };
            break;
        }
        
        if(typeof date === "object") {
            var time = RegExp.$4.replace(/^\s*|\s*$/g, "");
            
            if(time.length > 0) {
                if(/(\d{1,4})[^\d]+(\d{1,4})/.test(time)) {
                    date.hours = RegExp.$1;
                    date.minutes = RegExp.$2;
                }
            }

            date.hours = (typeof date.hours != "string") ? 0 : date.hours;
            date.minutes = (typeof date.minutes != "string") ? 0 : date.minutes;
            
            return new Date(date.year, date.month, date.day, date.hours, date.minutes);
            
        } else {
            return null;
        }
    } else {
        return null;
    }
}


Feel free to have a play. Tomorrow I'll post up a method turning the JavaScript date back into a string in different formats.

Tuesday, 12 December 2006

Joining strings

We've all been there before - concatenating strings of html, but which way is quicker?

1) Recursive concatenation.
var html = "<html>" + "<head>" + "<title>";

2) Append to the variable.
var html = "<html>";
html += "<head>";
html += "<title>";

3) Join the array
var html = ["<html>", "<head>", "<title>"].join("");

Smart engines such as SpiderMonkey (the basis for Netscape's original JavaScript engine - leading to Netscape, Firefox, etc) would use exactly the same underlying code for examples 1 and 2 - no speed difference at all. JScript in example 2 however would look up the html variable each time and use an intermediary to store the new values before discarding the old ones. So there would be a speed differential in JScript where example 1 is quicker than example 2.

The fastest string concatenation is using option 3 - this is down to the array's internal string builder facility which allows for much faster string manipulation. Of course it's only going to make a big difference when contactenating strings over many iterations - such as creating a large html table. Over a very small number of iterations the difference is so negligable as to be inconsequential.

Friday, 8 December 2006

Texty texty

Texty texty

Was reading Simon Willison's Weblog and he posted up about an really simple full-screen, auto-saving, free text editor called WriteRoom. It looks really nice - really classic. It's definately going on my mac at home.



Further down in the comments left was a post by a certain Steve Ballmer about a similar editor for Windows called Dark Room. I'm actually using it to write this blog post and it really is sweet. For a start it's got an opacity filter to the background so you can see what's happening on your desktop. I'm sorry but that's just like geek porn. Ironically you could actually run a movie in the background and watch it through the editor whilst working on a document. Mmmmm. Coupled with the auto-save feature that it uses means that this thing is actually making Narg breathe a little deeply and wriggle in his chair. Of course there's the small matter of the CEO of Microsoft posting comments on your blog - cause for celebration.



I'm a big fan of these small software apps that people write and release freeware or under OSS licenses - they really do push the larger tech companies with the ideas they promote. Much of the underlying architecture of really famous bits of software has been pushed by small ideas over the course of software history. Look no farther than Internet Explorer - the current most widely used web browser was actually developed primarily from the Spyglass Mosaic browser around 1995. Spyglass Mosaic actually licensed technology from the National Center for Supercomputing Applications (NCSA) - technology which was designed for a UNIX web browser and released under very generous licensing. This is why there's a credit to NCSA Mosaic in Internet Explorer. You can find this for yourself by going to "Help --> About Internet Explorer" in Internet Explorer itself. Very funky.

This does go to show that small teams of developers can have large impacts farther down the line. I'd like to think that at some stage I'll write a piece of software - a website, an interface or an appliation - that will have this impact. I think that would be a real sense of satisfaction. I believe in my heart that this is going to happen with the Chamonix Valley website. There are some really sound ideas coming forward and oppertunity to realise these things. Earlier this week the first nerves about moving to a foreign country were felt - the first butterflies in the stomach, but in reflection it wasn't apprehension of the unknown, but the realisation that there's the chance to do something to have a positive impact on a lot of people. Awesome. Bring it on. Feel the love baby.

Further reading:
Mosaic web browser
History of Internet Explorer
Internet Explorer Homepage

Monday, 27 November 2006

The Changingman

Written Friday 24th November

Decided to head home to the country to see my folks and take part in the Lytham Yacht Club annual dinner. It's a pretty traditional affair - dinner jackets, speeches, port and the like. It's pretty crusty too. Junior members are those under 30 and the president of the club is in his 90's. As I said - traditional! The funny thing is not one of the (all-male) members actually owns a boat/yacht/ship - it's purely social.

Another reason for coming up to the dinner is to take a break from the big smoke. I've been in London for a several years now, working for a capital management company and then for a financial betting company. A radical change in life is due. So yesterday the formal resignation went in and it became time to start shaping the future of the boy Narg.

Today I find myself on a Virgin train piling through central England heading from Euston to Preston listening to Nina Simone's greatest hits flowing through the headphones from my iPod with the same subtle, blended, sinuous feel of looking out of the window watching the scenery roll past. It truly does feel like the beginning of an adventure - one that potentially could shape life for many years to come.

I've decided to move out to Chamonix - the town that sits in the valley at the bottom of Mont Blanc in France. It's a mecca for skiiers and snowboarders due to the high, steep peaks, as well as being one of the best places in Europe to go climbing for the same reason. Timings look like to move out there mid-January after spending a month in New Zealand over christmas and new year. The more cynical out there will think this is purely a ruse to go out and play in the snow for a few months, but in fact it's going to provide the oppertunity to finish writing a piece of software that's been rolling around my mind for some time now. Also there's a particularly talented friend out there who runs the Chamonix valley website - chamonix-valley.com - and we've talked a bit working on a few bits on that together in a trade for using his offices to work from.

There's a heightened sense of freedom and happiness now that's not been felt for far too long. It's too easy to get bogged down in monotony and the negative aspect of life and that's debilitating. There's too much oppertunity to make your life wholely fulfilling and happy out there. The big adventure of life is an exciting miracle of a challenge and I've always felt that if you feel like life is passing by and you aren't living to the apex of the fun, happiness, joy and peace you can have then it's time for a change. Life is beautiful - even the chapters that are difficult or you don't like provide the lows for the highs to be high. Once again, it's been easy to wake up in the morning and jump up and down on the bed with excitement about what the day will bring, the utter joy of knowing that this one day is unique and there will never be the chance to live it again. That for me is the most special feeling, to share that with someone else - especially your partner and children - has to be the great gift of life.

There is an element of sadness leaving work - there is a plethora of amazing, incredible people there. Especially one guy who stuck up for me when times were hard and I just hope one day that he'll see the loyalty and honesty he showed me was reciprocated at every oppertunity that arose - he deserved it and much more. For that and his ability to teach and share knowledge selflessly, I thank him. I wish him and the other guys all the very best. Before leaving it also feels fully right to make peace with the very few people who there was any sort of friction with. It just feels correct in order to look back at this chapter in life with a whole heart full of happiness at having those people around as influential characters.

So the main plan of action now is to move to Chamonix and:

1) Write an exciting, challenging, clever, sellable piece of software (then sell it!).

2) Settle into doing two things that I love unconditionally - programming and snowboarding.

3) Fall in love again. OK now this isn't quite so urgent, but it's definately part of the main life plan thingy so it's included here.

Related links:
Chamonix valley website

Listingslab blog

Thursday, 23 November 2006

Number fun

Numbers are pretty interesting things, as well as the obvious mathematical use people also attribute emotional, psychological, mythological and religious reactions to certain numbers. Everyone has numbers they like and don't like, history and superstition show that westerners perceive the number 7 as not only lucky but also there are associations with cognitive psychology whereas the chinese see the number 8 as especially fortuitous. Funky stuff. In fact numerology explores this relationship between numbers and other systems (religious, physical, living, etc). My study into this is fairly limited, but it's always been interesting playing around with numbers and I've a stack of JavaScript number object extensions that I carry around in an html file wherever I go to work.

So here they are. I can't take full credit for all of these, I've based some of them on other snippets of code I've found around the place. Notably from codingforums.com so thanks to all who have contributed. I should point out that there's not much explaning that will be done as to why they work - they've been chopped right down to the bare minimum of overhead in most cases and work beautifully, but often look complex. I may well post up another time how they work in more detail.

1) First up is a classic. Rounding a number to a specified number of decimal places. It takes an optional argument n for the number of decimal places to round to. If no argument is supplied, the number will be rounded to 2 decimal places.

Number.prototype.toDecimals = function(n) {
  var n = (isNaN(n)) ? 2 : n;
  var nT = Math.pow(10, n);
  function pad(s) {
    s = s || '.';
    return (s.length > n) ? s : pad(s + '0');
  }
  return (isNaN(this)) ? this : (new String(Math.round(this*nT) / nT)).replace(/(\.\d*)?$/, pad);
}


Usage:
var intNumber = 9.23423;
var intRounded = intNumber.toDecimals(); // output: 9.23
var intRoundedToFourPlaces = intNumber.toDecimals(4); // output: 9.2342

2) Make an ordinal string (eg 1st, 2nd, 3rd) from a number. I use this a lot in date formatting. The argument n is just a locally declared variable, this function does not need any arguments passed to it.


Number.prototype.toOrdinal = function(n) {
  return ( this + ["th","st","nd","rd"][(!(((n = this % 10) > 3) || (Math.floor(this % 100/10) == 1))) * n] );
}


Usage:
var intNumber = 13;
var intOrdinal = intNumber.toOrdinal(); // output: "13th"

3) Convert a decimal number (also known as base ten or denary number) to hexidecimal (base 16 or hex) string. Hexidecimal is the numeral system that computers use. This is very useful for html colour codes which use 3 pairs of hexidecimal values to dictate the red, green and blue mix of the colour (so #CC130F is actually - CC 13 0F).

Number.prototype.toHexidecimal = function() {
  return this.toString(16).toUpperCase();
}


Usage:
var intNumber = 28;
var intHexidecimal = intNumber.toHexidecimal(); // output: "1C"


4) Convert a decimal number to binary. This is used the least out of the previous 3 number extensions, but it's included because it's elegant!

Number.prototype.toBinary = function() {
  return this.toString(2);
}


Usage:
var intNumber = 13;
var intBinary = intNumber.toBinary(); // output: 1101

You can also use these by putting parentheses (round brackets) around the number and calling the method. For example (13).toBinary(); outputs 1101, (40).toOrdinal(); outputs "40th", etc.

You may well notice that the 3rd and 4th number extensions (toHexidecimal() and toBinary()) use the native JavaScript object toString() method. When used with JavaScript numbers, this toString method allows you to pass an argument called a radix. In pretty much every numeral system we use, a radix refers to the number of unique digits that the chosen numeral system can use (including 0). So in the case of toBinary() we pass a radix of 2 because there are two digits that binary can use 0 and 1. In the case of decimal there are 10 they are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and in the case of toHexidecimal() there are 16 which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. The letters A-F are used in hexidecimal to complete the number of unique digits for that numbering system (the decimal equivelant would be 10-15 but as all those numbers (0, 1, 2, 3, 4, 5) have been used previously, they need to be replaced with unique digits).

So go, have fun with the numbers, be nerdy and spread the word!

Tuesday, 21 November 2006

CSS image flickering solved in IE

There has been a problem for many years that most of us have come across developing for Internet Explorer with background images "flickering" when the cursor is hovering over them. (here's an example). This is due to to Internet Explorer checking for a new version of the background image declared in the background-image css attribute when the mouse hovers over the tag. The flicker issue may also be accompanied with the hourglass flicking on or even no image flicker, but the hourglass flickers!

<script type="text/javascript" language="javascript">
/*@cc_on @*/
/*@if (@_jscript_version >= 4)
document.execCommand("BackgroundImageCache", false, true);
/*@end @*/
</script>

Essentially, if you include this script somewhere in your page (best towards the top) then it will resolve this problem. Banzai!

The comments with all the @ symbols are actually JScript (Microsoft's version of JavaScript) conditional commenting. In simple terms, only IE will see and execute this code. In more complex terms it means only the IE compiler will read and compile this code. This means that should you have large forks in your script - one to deal with IE and another to deal with any other browsers - you can often get large performance returns from using conditional compiling. There's a good article on javascriptkit.com about conditional compilation of JScript.

I can't take credit for this solution - MisterPixel came up with the goods looking into DHTML behaviours in IE with regards to another problem (a bit like Fleming discovering penicillin!).

Thursday, 16 November 2006

Registry hacking

Note: This is Internet Explorer only as it deals with ActiveX and modifying the system registry.

Recently I've been writing a few scripts to change values in the system registry. In actual fact, you use a few different technologies to achieve something that looks very simple. This script reads then sets the home page for Internet Explorer via the registry. However you can edit any registry value you wish to using this method.

Background
Firstly what is the registry? In simple terms, the registry is a database that stores settings and options for Windows and contains information for all the hardware, software and preferences of the PC (http://en.wikipedia.org/wiki/Regedit). This script uses a combination of JScript and ActiveX in a Windows Script host environment to edit those bits of information in the registry. JScript is Microsoft's Active Scripting implementation of ECMAScript (http://en.wikipedia.org/wiki/Jscript). Basically it's their version of JavaScript, but with lots of add-on features. These "add-ons" also rather nattily work in any Windows Script Host environment - and that's been shipped by default with every version of Windows since Windows 98 or with Internet Explorer 5+. Further information: http://en.wikipedia.org/wiki/Windows_Script_Host. We can use this JScript to create an ActiveX control to pass information from our script into the registry. ActiveX is simply as mechanism for passing information around a Windows computer. All in all, pretty neat eh?

Here's my script:
<script type="text/jscript" language="jscript">
var objShell = new ActiveXObject("WScript.shell");

/* Get the current home page */
var strRegKey = "HKCU\\Software\\Microsoft\\Internet Explorer\\Main\\Start Page";
var strCurrentHomepage = objShell.RegRead(strRegKey);

/* Set a new homepage */
objShell.RegWrite(strRegKey, "http://nargster.blogspot.com/");

</script>

Let's go through it.
The script attributes
<script type="text/jscript" language="jscript">

These are set to jscript because this script is only to work in IE it's not vital, but it's good a good habit to get into.

Create an Windows Script Host (WScript) shell object
var objShell = new ActiveXObject("WScript.shell");

OK, so we're going to ask the script to create a new ActiveX object (as mentioned, this is just an information carrier) to pass information to a particular target - in this case the Windows Script Host (WScript) shell. The shell is simply interface that enables access to the inner workings of the computer - we need to create this shell object in our script to access the registry.

Accessing the registry
var strRegKey = "HKCU\\Software\\Microsoft\\Internet Explorer\\Main\\Start Page";
var strCurrentHomepage = objShell.RegRead(strRegKey);
objShell.RegWrite(strRegKey, "http://nargster.blogspot.com/");


Now we've created a shell object, we can access the properties and methods of that object. Two of its methods are called RegRead and RegWrite - they read and write the registry respectively. The example shows the arguments required for these two methods. In both we pass the registry path of the registry item we wish to edit, making sure that we replace any single backslashes \ with a double backslash \\. This is because the backslash character in JScript is special - it's an escape character. The strRegKey string is the path to the value we want to change, you can find more information about how this string is built by looking through the registry using regedit, explained below. It's easy to see how the string relates to the structure of the registry, it's like a filesystem folder path.

Regedit - the registry editor
So you want to find out what the registry looks like to browse through. I'll not kid you - it's massive. You can use regedit, the registry editor (Start Menu --> Run, then type regedit and hit enter or run regedit.exe or regedt32.exe in your Windows directory) to have a look around and adventure. The registry structure is too detailed to go into here, but Wikipedia do an excellent job of it: http://en.wikipedia.org/wiki/Regedit

A last word just on security
It does seem incredible that Microsoft would create a web browser that could run scripting to read and write the system registry, but that's what they've done. They've tried to correct this problem in IE7 by not allowing the creation of ActiveX controls by default - users must enable this manually (with accompanying nasty messages about potential insecurities). In other supported versions of IE (IE3 - IE6) the default behaviour is that this simply runs with an ActiveX warning message. You can get around these warnings by saving the html file with an hta extension, turning the html file into an HTML application (MSDN). This .hta file only runs locally on a machine and runs without the strict security model the browser uses - no nasty error messages!

Play around with the registry - you could potentially damage something, but stick to the simple stuff and work your way up and it should all be good. Using .hta files is good because it opens all sorts of potential for html/scripting without security restrictions, so you can make cross-domain AJAX calls - something which is not allowed in a webpage) as well as other funky HTML applications to change the settings and tailor your computer.

Windows Script Host programming reference
There's loads of methods and properties of the shell object - you're not limited to reading and writing stuff to the registry - you can set/retrieve/delete user information, network and printer settings, read and write files and much more. You can find details of this at devguru.com in their Windows Script Host reference:
http://www.devguru.com/Technologies/wsh/quickref/wsh_intro.html

Tuesday, 14 November 2006

Garbage Collection

Thought I'd post up a bit I wrote at work discussing differences in memory handling and garbage collection in different browsers.

Background
Microsoft's implementation of ECMAScript is actually called JScript (not JavaScript), and it's behaviour with regards to garbage collection differs from the original implementation of JavaScript in SpiderMonkey (SpiderMonkey is the name for the first JavaScript engine written by Netscape, Firefox is based on this engine). It's worth noting that the JScript/JavaScript engine does not itself provide a host environment for the DOM - they are two separate structures that exist together, but can logically exist apart.

The main difference
IE uses non-generational mark and sweep garbage collection versus SpiderMonkey's generational mark and sweep garbage collection. The "mark and sweep" bit means that each object (either JScript or JavaScript) has an attribute that is set to 1 if it is to be collected and 0 if it is not. As the generational/non-generational bit of the name implies, what it means is that SpiderMonkey will find older objects first and clean them out (generational), whereas IE will do this fairly indiscrimately and just find JScript objects in memory and check to see whether to garbage collect them (non-generational). Simply put SpiderMonkey will push the objects to be collected to the bottom of the memory heap (http://en.wikipedia.org/wiki/Heap_(programming)) and then knows to grab the bottom of the pile to free memory, whereas JScript will throw objects (relatively) randomly onto the heap and then pick through all of them individually checking to see if that object needs collecting. As you can imagine there's an impressive performance lean towards generational garbage collection.

Implications
Because of the relationship between the DOM and the JScript/JavaScript engine, stacking objects in memory becomes very important. As you can imagine, keeping less objects in memory now has real performace implication in IE - especially circular references between the engine and the DOM such as an array of nodes - an example of this problem would be memory leaking through event handlers in the DOM (http://www.jibbering.com/faq/faq_notes/closures.html#clMem) - in fact this problem surfaces with any sort of large numbers of data types/objects held in memory at one time. It also should promote forced memory handling when resources can become free, rather than simply waiting for automatic garbage collection to be initiated (statements such as "myArray = myString = myNumber = null") to make sure the object has the least memory allocated to it after use and the automatic garbage collection then becomes much quicker.

Links to more info
Garbage collection: Wikipedia Garbage Collection
SpiderMonkey: Wikipedia SpiderMonkey
Garbage collection models: North Eastern University