Monday, 12 October 2009

Train Toilet Design Flaw


There’s a lot written about good, bad and quite frankly appalling design in software. Having worked in software for a while I’ve got a degree of sympathy of how it occurs. Software developers aren’t evil misanthropes with a complete loathing of people in general and users in particular. OK, ok – some are exactly like that but that’s not why poorly designed software happens. Pressure to ship, corners cut on usability test and a design to focus on cool new technologies all contribute. But at least software can be patched, upgraded and fixed. What I find it harder to understand is when major pieces of real world kit have bizarre usability issues.

The worst offender is the new train toilets that are popping up in newer trains. Rather than a boring old mechanical lock that has served mankind well over the last 300 years the new toilet are locked by a series of flashing buttons. The sequence is


  1. Enter toilet
  2. Press flashing button to close
  3. Wait till door shudders shut
  4. Press a second button to lock it. There’s no indication that the door is locked so just cross your fingers and hope it is
  5. Then pants down and away you go.

For God’s sake though don’t add an additional step of pressing the lock button again to make sure that it is locked. This has the amusing effect of reopening the door with no warning whatsoever. It’s design flaw of the year surely.

A Polish woman did exactly this when I was waiting my turn outside of a train toilet recently. I was rapidly faced with an alarmed looking Eastern European woman with her pants round her ankles. A special moment for us both I felt. The ties between Eastern and Western Europe become ever more intimate.

Saturday, 30 May 2009

Podcats

I love a good podcast as I’ve previously alluded too. But even more I’m a big fan of pod cats and these are some of my favourite feline podded wonders.

Suburban Pod

Here Tiddles is modelling a modern stylish lightweight pod. Sleek, sophisticated, urban with a discrete pouch for the current murdered rodent du jour.

Travel Pod
A portable, practical self assembly pod for the busy feline about town. Scratch resistant with a wipe clean surface for those little kitty accidents.



Hygienic Pod
Felix is modelling the latest in robust, white porcelain pods with a kitty lid. Securely fixed to the floor of the littlest room in the house with a white plastic rim to facilitate easy entry and exit. We are please to announce that these model come with a handle activated Jacuzzi swimming pool. Just what your cat needs after a busy day at the office.


World War 2 Fighter Pod

Baron von Feline, scourge of the airways, models the latest in WW2 fighter pods. Features include three-blade constant-speed propeller, triple ejector exhaust manifolds and X80 HP Rolls-Royce Merlin II engine. Lethal in the wrong paws. Achtung Tiddles!!

Sennheiser Headphones and the Fire Brigade

I’ve recently purchased my second set of Sennheiser CX300 Eco Ear Canal Headphones so I thought it was about time I gave a little shout out for these headphones. I’m no audiophile but they’re the best headphones I’ve ever bought. Good sound reproduction, comfy, last a fair length of time and a nice eco wrapping rather than hermetically sealed in 15 layers of non-biodegradable nuclear plastic.

However simultaneous my most and least favourite quality is their oh so too good sound blocking. When I first bought these I was more used to less superior sound cancelling characteristics from my headphones. So much so, that when wearing them and letting myself into my old office I accidentally rearmed the security alarm system. Two bleeps instead of one are easy to miss with Sennheiser’s sound cancelling. I wandered nonchalantly upstairs to the office and couldn’t understand where the strange continuous siren was coming from. Cue anti-criminal smoke gushing out of some previously innocuous looking boxes and the entire office was in total whiteout.

One fire engine, four industrial fans and 60 minutes later and the office was final fit to be reoccupied. Thankfully I was working my notice at that company otherwise I would have had to resign in shame. Not my finest hour.

Saturday, 16 May 2009

Crazy Cool Sci-fi Covers: The Wanderer

I’m slightly obsessed with old science fiction books. I find the old stories charming but the real obsession comes from the covers. They’re often wild, wacky and bizarre. Spaceships, winged dinosaurs and scantily clad female aliens are all there – it’s like one of my more juvenile dreams.

One of my faves is this cover to Friz Leiber’s The Wanderer. Which cat owner hasn’t wished that their cat was looked a bit more like a girly, had breasts and was seemingly as big as a planet? It’s certainly the dream of a fair few male cat owners I know.

And what tell of the contents of the book? Well, although this book is supposedly a classic and is published by the reputable Penguin books – it is quite frankly a stinker. There is a tradition in sci-fi books of the cover having nothing to do with the story itself. Sadly in this instance the cover is an alarming representation of this “classic” piece of fiction. It’s giant cats with breasts causing havoc with the planet Earth. For God’s sake! The climax (literally) of the tale comes when the giant sexy cat makes beautiful love to the scientist hero. Blllurrrgggeeeee!!!!!! Thankfully both giant cat and scientist regret it the morning after.

Wednesday, 13 May 2009

JobStats


A quick shout out for a revamped favourite site of mine – JobStats. JobStats has been tracking the IT job market for over 10 years now and plotting in on an exciting graph. Sadly the site was moribund since early 2003. The graph still automatically plotted itself though so it was always worth a check.

Good to see then that someone has updated the site and made it a bit flashier. The exciting graph is still there and there are more locations, a personalisation bit and predictably more adverts – Oh well. So if you’re like me and have a morbid fascination with the IT job market I recommend that you check it out.

Saturday, 9 May 2009

Repeater NamingContainer Gotcha

Here was an odd thing. Take one repeater
<asp:Repeater runat="server">
<ItemTemplate>
<asp:CheckBox ID="chkBox1" AutoPostBack="true"
OnCheckedChanged="CheckBox_Click" runat="server" />
<asp:TextBox ID="txtBox1" runat="server" /><br />
</ItemTemplate>
</asp:Repeater>


Bind it up to something and get a list of textboxes and checkboxes. Like so



The task is to wire up the Checkbox click event so that when it is clicked the corresponding textbox is disabled i.e.

Easy peasy I thought and wired it up with this code
protected void CheckBox_Click(object sender, EventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
TextBox textBox = (TextBox)Page.FindControl("textBoxId");
textBox.Enable = !myCheckbox.Enable;
}

The surprising result is that no matter which checkbox is clicked it is always the first textbox that is disabled. The problem is with finding the control. The line fourth line has changed -
protected void CheckBox_Click(object sender, EventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
TextBox textBox = (TextBox)myCheckbox.NamingContainer.FindControl("textBoxId");
textBox.Enable = !myCheckbox.Enable;
}


I suddenly realised what a NamingContainer was. Previously I just thought it was a piece of arcane .Net knowledge – defined in MSDN as

Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same ID.

Yeah right whatever. Well apparently it’s actually important stuff.

In the first example the code finds the first textBox called “textboxId” in the page. This is always the first one hence my code doesn’t work. In the second, corrected code – the control is searched for within the NamingContainer of the event sender – in this case it’s the RepeaterItem. So in the repeater there are any number of texboxes called “textboxId” but the don’t clash and can be accessed because each one exists in it’s own NamingContainer – i.e. unique naming space.
I appreciate this will be obvious stuff to many people but I felt like a super-brained coding rock star when I found this out. Then again I’m easily impressed.

Saturday, 2 May 2009

10 Great Podcasts


I’ve been listening to podcasts for over 3 years now. Most of my knowledge of the wider world seems to come from them these days. I LOVE them. Sooo, it seems about time that I share with an (almost certainly un)eager world what my favourites are. My faves are obviously skewed by my nationality (British – so there is a number of BBC ones) and interests (there’s no sport – I’m a geek for God’s sake) but caveats and disclaimers not withstanding – here’s the 10.

Mark Kermode and Simon Mayo’s Film Reviews
Film Reviews from the BBC
My favourite of them all. Dr Mark and Dr Simon argue and bicker give vitriolic opinions on this week’s film releases. Often controversial but never dull.

Stuart Maconie’s Freakzone
Alternative Music from the BBC
I’m a big music fan but not a big music podcast fan. Due to licensing restrictions you only get snippets of songs so it’s a bit frustrating. Even so – this is a podcast worth a listen. Full of freaky, bizarre obscurest artists that no-one’s ever heard. And if that’s not enough to whet your whistle then Justin Spear’s University of the Strange surely will. What’s not to like.

Money Talk from fool.co.uk
Personal Finance
I’ve a deep dark secret. I’ve a genuine interest in personal finance. For others with a similar affliction this is a great podcast. Informative and lively chat from the highly engaging David Kuo. A variety of topics means that even though you might not be interested in credit cards, the following week’ topic on mortgages might be just up your street.

Guardian Tech Weekly
Technology from the Guardian newspaper
I find a lot of technology podcasts very unsatisfying. They are dull or amateurish or juvenile or all three. This is one of the exceptions. A lively interchange from the current pod members – Aleks Krotoski, Bobby Johnson et. al. It’s got quite a big focus on gadgets but covers the current affairs and business stuff too.

Dilbert Animated Cartoons
Cartoons of course
The only video podcast (vodcast??) I subscribe too. Daily 10 second bursts of Dilbert, Dogbert and Wally. Nuff said.

Slate Political Gabfest
US Politics from Slate Magazine
My only US podcast. The ever liberal Slate team discuss American politics. I got into this for the election but it’s got a shelf life past that. Emily Bazelon is the star of the show here. It can get a bit low key if she isn’t there to liven things up but she’s a regular contributor so that hardly ever happens.

Wake Up To Money
Business News from the BBC
20 minutes of business news 5 days a week. I love it. Andy Verity and Micky Clarke present. Well balanced and informative even if Micky C is a bit of a 4 wheel drive loving right winger (as I’m sure I will be in the years to come). It’s been a bit gloomy recently since near total collapse of the capitalist system so a strong stomach is required at the moment. It will cheer up eventually I’m sure.

Dr Karl and the Naked Scientist
Science from the BBC
I don’t bother with the Naked Scientist bit but Dr Karl is great. Dr K answers late night science questions from various insomniac scientist wannabees. The questions range from the highly insightful to the deranged but Dr K answers them all with genuine good humour. Worth the listen for the inevitable loon who rings in claiming to have disproved the theory of relativity, gravity or evolution.

Philosophy: The Classics
Philosophy
From Plato to John Stuart Mills – it’s the history of western Philosophy delivered in 15 minutes bite sized chunks by Nigel Warburton. Why would you ever wade through 500 page 18th century philosophical tomes when Mr Warburton will summarise for you.

In Our Time
History of Ideas from the BBC
Take three professor types, add a spoonful of Melvyn Bragg and throw in a History/Science/Philosophy/Literature topic, mix around and deliver 40 minutes worth of cerebral chat. Intense cleverness in a pod – Lovely.

Saturday, 25 April 2009

Dark Star

I’m going through a bit of a phase of rewatching/reading sci-fi that I’ve got fond memories of. Often things aren’t quite as good as I remember. However I recently watched the little known, ubercheap sci-fi classic Dark Star (1974) and if any thing it has improved with (my) age.

Dark Star is John Carpenter’s first opus – his magus opus. Mr Carpenter is better known for horror such as Halloween and the brilliant Thing. Strangely through this, his first film is sci-fi comedy. Imagine a group of early seventies hippies stuck together space and the depressed, sniping they engage in. Throw in a vague cryogenically frozen captain, a philosophical bomb and the most brilliant ending of any film. Mix it up and serve with retro Star Trek like effects and a John Carpenter synthie soundtrack and you’ve got a cult classic. And the cost of all this – to you sir it cost $60,000 to make. Fabulous – I’ll have ten.

What really impresses is that it’s downbeat without becoming dystopian like the admittedly brilliant Blade Runner or Brazil. This gives it a very particular vibe – that I can’t recall been replicated in any other film. And if all that isn’t enough reason to watch then everybody must witness the beach ball alien which bizarrely was the inspiration for the much less beach ball like and far more scary 1979 Alien.

Wednesday, 22 April 2009

The Human Clock


I’ve not worn a watch for years for reasons too dull to mention. For similarly dull reasons I’ve recently needed to embark on a dull shopping trip to various dull watch vendors to look at various overbig, overstrappy overpriced, dull as ditchwater watches before electing to purchase the least offensive of the bunch. Dull, dull, dull. Dull and pointless indeed when you consider the timekeeping excitement which is the human clock.


Rather than a boring old circular watch face with some numbers and pointy hands the human clock tells the time through the medium of well … humans. Every minute of every day is displayed by a new piccie that someone has sent it. From the routine street numbers, to birthday cakes, to patterns in the snow to car registrations – every field of human endeavour is used to tell the time. It’s a humanist marvel.

So throw out your watches people and tell the time through the medium of the human clock. In fact in these wireless times it wouldn’t be too much of a stretch to fashion a watch type device that would display the human watch where ever you are - the iHumanClock. Come on Apple, make it happen.

Saturday, 18 April 2009

The Power of (C# Keyword) As

I’ve been coding in C# now for 5 years. Other than with my wife, C# is my longest standing relationship. While I don’t celebrate my anniversaries with C# (yet – though I might on our 10th) I did think that I was familiar, maybe even intimate, with the language. Why then had I never heard of the as keyword.

Previously I would cast object like so
try
{
Checkbox myCheckBox = (Checkbox)strangeObject;
//do some clever stuff
}
catch(Exception)
{}
- which works fine. My niggle with this that you’re getting towards using exceptions to manage the flow of code and the seven circle of hell is reserved for coders that indulge in this satanic practice. Enter the angelic keyword as

Let’s do the same thing, this time with our new friend.
Checkbox myCheckBox = strangeObject as Checkbox;

if(myCheckBox != null)
{
//do something clever
}
The as casts the object but instead of spewing out an exception it gracefully nulls it. Therefore it’s same code but with no exception unpleasantness. I like this a lot better – it’s like wholemeal fibre vs. saturated fats. It’s just a lot better for you.

Saturday, 11 April 2009

Visual Studio Short Cuts

I would like to urge all .Net coders to follow my new one a day program. Following it will guarantee health, well-being and popularity (possibly) and will be the beginning on a new phase in your life. It’s nothing as mundane and tawdry as one piece of fruit a day, one session of exercise or one kindly action to a stranger. It is a commitment to learn one new Visual Studio shortcut a day for the next two weeks.

Trivial, perhaps. Overstated, almost certainly. However a few more decent shortcuts under your belt will make it seem you’re directly interfacing with your IDE in a scarily symbiotic way. You’ll be faster, more efficient and far more popular with the opposite sex. Particular if the opposite sex is your project manager to whom you’re delivering software to that bit faster.

Wednesday, 8 April 2009

.Net Control Collection Gotcha

Making puff pastry is something that sounds like it should be easy but when you’ve got the butter, flour and mixing bowl out it turns out to be excessively difficult. In the same vein – iterating through a collection of .Net controls and finding all the ones that are checkboxes sounds straight forward but is in fact a bit of a pen chewer.

My first attempt. This is a winner surely.
foreach (Control control in thisPanel.Controls)
{

if (control.GetType() is CheckBox)
{
//never going to work
}

}
Nope – the compiler complains straight away that ‘Control control’ will never be of type checkbox. OK sounds reasonable. After some discussion with colleagues a fellow programming minion suggested that it’s the foreach that’s the problem – so try the following.

for (int i = 0; i < thisPanel.Controls.Count; i++)
{
if (thisPanel.Controls[i].GetType() is CheckBox)
{
//won’t get here either
}
}
Looking good – but sadly again won’t work. The problem is that the control collection has already been downcast to a generic control. Therefore it doesn’t ‘know’ anything of its original type. What’s a boy to do? The best 4 programmers could come up with a combined amount of programming experience of over thirty years was –
foreach (Control control in thisPanel.Controls)
{
CheckBox checkBox = control as CheckBox;

if (checkBox != null)
{
//now we can do something
checkBox.Enabled = false;
}
}
This solves the problem so hurray. I have a nagging feeling that there is a better solution. It seems a simple request that should be achievable without guessing what types are in there. It’s probably something wildly clever with generics/delegates/lambda expressions or some such. Further pondering required I think.

Saturday, 4 April 2009

Spelling and Software Quality


In Charles Dickens' Hard Times, the severe Mr Gradgrind teaches children “Facts. […] nothing but Facts. Facts alone are wanted in life”. In a similar vein I would like to teach computer programmers “Spelling, nothing but spelling. Correctly spelt words alone are wanted in computer programs”.

I may well be a pedantic, mean spirited, weasel coder of a man but badly spelt words in software code drives me crazy. There is more to it then my love of order, rules and finding any old stick to beat other coders with. Spelling mistakes in code have the half life of plutonium. If some one spells a word wrong in an email it doesn’t matter. It’s sent, it’s read and it’s gone in an ephemeral puff of cyber smoke. If someone spells a variable name wrong in code it will lay around in that app like a bad smell for years. And if some creature of great evilness spells a database table wrongly – the universe will undergo its final heat death before anyone gets round to correcting it.

It’s more evil still then just poor use of the English language offending me on a daily basis. It’s a software maintenance nightmare. At a minimum the poor maintenance coder has too remember exactly which variant of the word “category” is been used this time. At its worst seemly innocent typos cause redundant code to proliferate like rampant triffids.

As a recent example I came across are these stored procedures

usp_GetPersonelDetails
usp_GetPersonnelDetails

OK – which one is the correct one to use? Either, both, neither? Which one can I delete to tidy up? Which one is the most recent version? Which one will cause the app to fall into a smoking heap if used? Aaahhhhhhhh!!!!!!

So as well as unit tests, regression tests and usability tests, I prescribe spelling tests to push back the ever encroaching waters of crappy code.

Wednesday, 1 April 2009

Rapid Development

Of all Steve McConnell’s books, Code Complete gets the attention. People quote it, name websites after it, publish photographs of themselves kissing it and generally froth and foam about it. And quite right too because it’s great. However for my money his book Rapid Development is even better.

Although called Rapid Development, its name is something of a misnomer. It’s not about rapid development techniques per say, rather it’s about excellent project management techniques that as a side effect will enable your project to proceed as quickly as possible. To me it feel’s like its project managers written for developers.

If you don’t want to read it cover to cover (what’s wrong with you – read it all) then software estimation, the sections on motivation and team structure and classic mistakes are worth reading as standalone chapters. I love the estimation tables provided to measure your own schedules against. It’s illuminating to measure your own projects against them. So next time an impossible deadline looms, you’ll have the facts to back you up. Marvellous.

Saturday, 28 March 2009

Hard-Coded Passwords Gotcha

Everyone agrees we should give to charity but not that many people do. In the same way everyone agrees we should write secure software but I’ve seen again and again web applications that you could break with a Swiss army knife and a bent paper clip. I think part of the problem that security advice seems overwhelming and hectoring. Reading the recent list of CWE/SANS Top 25 Most Dangerous Programming Errors is like been nagged at by your office manager. I can’t disagree but I can’t take in anymore.

The best way to know and appreciate something is to see it. CTW-259 warns of hardcoded passwords. It was only when I downloaded reflector that I realised how much of a problem this was.

Consider this fragment of a class
public class TestClass

{

private string _password = "supersecretpasswordnoonecansee";

private int _testInt;



/// <summary>

/// Test Int

/// </summary>



public int TestInt

{

get { return _testInt * 6; }

}



//etc....

}
That password is secure as houses when complied. Well once it’s loaded into Reflector and disassembled then probably not


That took me about 30 seconds to break. Reflector is a free download so it’s not even costly for the hacker. Bit more costly for the victim though.

Wednesday, 25 March 2009

IT Demographics: Finger Length, Gender and IT


There’s an awful lot more male software developers than women. It’s a truth so self-evident that it would take some-one of delusional levels of political correctness to deny it. Therefore counting the number of ladies of a coding persuasion in your office will lead to blinding obvious results i.e. there ain’t that many. However counting the number of man brains in your office may well be of more importance to the nascent science of IT demographics.

Logic would dictate that if you’re a man then it’s a man brain for you and visa versa for women. Not so Horiatio. A significant minority of men have lady brains and the converse for women.

You will be gladdened to know that there is no need for radical surgery to identify a man brain. A none-invasive technique is available. Simply look at a person’s hand and measure the relative lengths of their forefinger and their ring finger (nearest to the little finger).


  • If the ring finger is bigger than the forefinger – you are a proud owner of a man brain.

  • If the ring finger is shorter than the forefinger – then you are well endowed with a fashionable ladies’ brain.

So get out there and do it. Seize the hands of all the coders in your office and get measuring. I won’t sully the scientific endeavour by speculating on the result however I wouldn’t be surprised if coders of either gender orientation excel at tasks such as reading maps and putting together flat pack furniture.

Saturday, 21 March 2009

The Sad Deletion of Jeff Atwood

It’s a modern day tragedy. I was browsing wikipedia this week when I just happened to check out the entry for my favourite blogger Jeff Atwood. I was shocked and dismayed to discover that the entry has been deleted - Mr Atwood has been deemed as being too trivial. In the tawdry old real world Jeff’s star seems very much in the ascendant with the release of the programmer’s wiki-portal stackoverflow (very much worth a browse). Sadly things appear not to be going so well for him online.

So whatever next for Jeff? Will all his blog posts be erased? Will his facebook account be defaced? Will his twitter tweets be expunged? Will all signs of his online life be purged from the Internet? It will be worse than online death. It will be obliteration. It will be extinction. It will be like he never existed at all. He will just be left with that shallow, dreary existence we have come to call the real world. What a truly tragic fate for a truly geeky man.

Monday, 16 March 2009

Reflector: Disassemblement for the Masses

I appreciate it’s probably an unpopular pastime for many of us geeky developer types but sometimes talking to colleagues does have its benefits. Once we’d finished discussing the latest BattleStar Galactica episodes and reminiscing about tabletop war gaming our conversation turned to tools of a cool nature, particularly reflector.

Reflector is a disassembler for .Net provided by the lovely people at Redgate. It’s so good that it seems almost magical in its power. Previously if I wanted to poke around in a dll then I’d use MSIL disassembler (ildasm.exe) and then feel all manly that I was interfacing directly with the intermediate language code. Since I was feeling all scientific I whipped up a quick test class to compare the two.

The test class
using System.Collections.Generic;
using System.Text;

namespace TestProject
{
/// <summary>
/// Test Class
/// </summary>
public class TestClass
{
private int _testInt;

/// <summary>
/// Test Int
/// </summary>
public int TestInt
{
get { return _testInt * 6; }
}

private string _testString;

/// <summary>
/// Test String
/// </summary>

public string TestString
{
get { return _testString; }
set { _testString = value; }
}

/// <summary>
/// Test Class
/// </summary>

public TestClass()
{
_testString = "TechSplurge";
_testInt = 99;
}

/// <summary>
/// Test Method
/// </summary>
/// <param name="maxCount"></param>
/// <returns></returns>
public void TestMethod(int maxCount)
{
for(int i=0;i<maxCount;i++)
{
Console.WriteLine(_testString + i.ToString());
}
Console.WriteLine("End");
}
}
}
With Ildasm

It’s a bit cryptic in there. Let’s look at the manifest






OK I can see namespaces but the rest is mysterious


With Reflector



Wow – the scales have fallen from my eyes and I see real code buried in the dll.

In fairness it’s a little like comparing apples with oranges. Ildasm.exe is for looking at what the code actually does once it’s been compiled - useful when really going for performance tweaks. Reflector is for seeing what the programmer intended and for seeing how on earth that third party dll works.

Saturday, 14 March 2009

Star Wars Interviews


There’s all kinds of theories about how to get good programmers. You could separate Sheep from Goats with Jeff Atwood or experience the madness which is Interview 2.0 with extra riddles. Alternatively you could trust yourself to the force with Tech Splurge.


The methodology is simple but breathtakingly effective. When you contact a candidate with perhaps some direction to the interview or a pre-screening test simply append this simple line to the end of the mail


Use it wisely and only for good.


Any true geeky tech spod will immediately recognise the Star Wars-ness of the statement and will not be able resist replying in the same vain. So if the response is a boring old “Thank you for your response and I look forward to seeing you in due course” then I’m sorry you haven’t passed the test and we won’t be pursuing your application. However if the response is permeated with references to light sabres, X-wings and Princess Leila then you’ve found your ideal candidate. Employ immediately.


I’ve already done the ground work and test ran the phrase with developer colleagues and we are talking an impressive 100% hit rate. Every one of them replies with a Darth Vader image, a Yoda impression or some other Star Wars ephemera. It’s eerily effective.

Saturday, 7 March 2009

Sony Reader


A few weeks ago Mrs Tech Splurge and myself were have a coffee in Waterstones when I happened upon a stand of Sony’s new eBook – Sony Reader. Against all expectations I was impressed. It felt good in the hand, the screen was attractive and very like a book and the battery only appeared to drain on page refresh so would last for ages. However even though I’m a technology fan, was impressed by the product and I like a good book I still didn’t buy it. Why on earth not?

I believe that eBooks themselves are fundamentally flawed particularly as compared to MP3 players which must be the business model that Sony is trying to follow.

The Flaws


  1. You need earlier adopters and tech evangelists to push your product. While geeky nerdy types will get excited about audio systems or home cinemas the enthusiasm for a home library system surely would be more muted

  2. With music I’ve maybe got 20-30 CDs that I would regularly listen to. I can’t carry them all around with me so an MP3 player is the ideal solution. With books I’ve only maybe got 2-3 on the go at any one time. So picking one and carrying it round with me isn’t a fantastic hardship that cries out for a technological solution.

  3. I would imagine that demographics of book readers includes a lot more older readers than music fans or film buffs. A decent proportion of these would be late adopters and outright refusers of new technologies.

  4. If I was an author I wouldn’t licence my work for electronic distribution. As soon as it’s out there then I’ll be in the Peer2Peer copyright hell that musicians are currently dwelling in.
Even though the idea has flaws I don’t think it’s a stinker. It’s just more niche than Sony would probably want. There are a couple of circumstances when it would have real value.

Niches


  1. I spend inordinate amounts of time deciding which books to bring on holiday. With an ebook reader – no problem, bring them all.

  2. I like to have an IT book or two on the go but I’m not going to carry them round with me. However if they were nestled inside an ebook reader I might.

  3. There is probably a good model for magazine subscriptions buried in the ebook reader. Throw in a bit of wireless connectivity (i.e. Kindle) and you could get an update of your favourite publication when you’re in Café Nero enjoying your mocha chocca double expresso latte.
Overall, I reckon that ebooks will never be the killer app and disruptive technology that MP3 players were. No matter how cutesy, leather bound and easy on the eye they become they’ll always remain a solution looking for a problem.

Friday, 6 March 2009

Lab Lit


I’m a bit of a frustrated scientist at heart. Never mind that I spent my final year at University sulking over Petri dishes, leaving expensive reagents out of the fridge to spoil and breaking centrifuges. There is still a part of me that truly believes that my natural environment is in a lab surrounded by poisonous chemicals and glassware. So I was fascinated by the LabLit site.

As a may have mentioned before (ad nauseum) I’m a bit of a science fiction geek. So LabLit is a new concept for me. It’s fiction about science Jim but not as we know it. Lablit doesn’t concern itself about spaceships, killer robots and little green men. Rather it is literature with realistic depictions of science. Sometimes this is the same as science fiction but often it is not. It turns out that as a frustrated scientist my sci-fi faves are often also LabLit.

My lablit recommendations are

Contact – Carl Sagan. Lab coats, spectacles and radio astronomy
Timescape – Gregory Benford. Lab coats, environmental disaster and worried looks
Speed of Dark – Elizabeth Moon. Lab coats, clever maths and autism
Blood Music – Greg Bear. Lab coats, nanotechnology and quantum freakiness

And to prove I’m a well rounded individual (I’m not) here’s a lablit recommendation that isn’t sci-fi

Thinks – David Lodge. Lab coats, psychology and academic flirting

Saturday, 21 February 2009

JavaScript Collapsible Links

Coding in JavaScript used to be like loving a naughty child. OK, it’s not strongly typed, the debugging is terrible and the cross browser issues are pretty unpleasant but look at his cheeky face. Awwww – he’s so cute running round and setting fire to dogs and he makes my web pages look all clever and interactive.

Over the last few years the naughty JavaScript child has grown up a bit. The The prototype project has swept away a the cross browser unpleasantness, extended the DOM and made the entire thing a lot more like a proper grown up coding language. So in the spirit of playing with an adult I whipped up a collapsible link control using the prototype library.

I’ve published a demo of the collapsible links and the images are a plus and a minus and can be grabbed from the above link. The code uses divs to construct the tree

The code uses divs to construct the tree. Css is used to show and hide the div panels and swap the plus and minus images. Prototype enabled JavaScript is used to wire it together

<html>
<head>
<script src="scripts/prototype.js"></script>
<script>
function setupGrid()
{
arrLinks = $$('#JsGrid a');

for(var i=0;i<arrLinks.length;i++)
{
arrLinks[i].observe('click', togglePanel);
}
}

function togglePanel()
{
var clickedLink = Event.element(event);
var panel = clickedLink.up().next();

if(clickedLink.className == "linkOpen")
{
clickedLink.className = "linkClose"
}
else
{
clickedLink.className = "linkOpen"
}

if(panel.className == "panelClose")
{
panel.className = "panelOpen"
}
else
{
panel.className = "panelClose"
}

}
</script>
<style type="text/css" >
.panelOpen
{
padding: 0px 0px 0px 20px;
display:block;
}

.panelClose
{
padding: 0px 0px 0px 20px;
display:none;
}

.linkOpen
{
padding: 0px 0px 0px 20px;
background:url('images/minus.gif') no-repeat center left;
}

.linkClose
{
padding: 0px 0px 0px 20px;
background:url('images/plus.gif') no-repeat center left;
}

</style>
</head>
<body onload="setupGrid();">
<div id="JsGrid">
<div><a href="#" class="linkOpen">Test 1</a></div>
<div class="panelOpen" >Test content 1</div>
<div><a href="#" class="linkOpen">Test 2</a></div>
<div class="panelOpen">Test content 2</div>
<div><a href="#" class="linkOpen">Test 3</a></div>
<div class="panelOpen">Test content 3</div>
<div><a href="#" class="linkOpen">Test 4</a></div>
<div class="panelOpen">Test content 4</div>
</div>
</body>
</html>

The setupGrid method wires the togglePanel method to the click event of each link. The $$('#JsGrid a'); is prototype cleverness to pick up all the links under the JsGrid element. The togglePanel function does what it says on the tin – shows and hides the panel giving the collapsible tree structure its collapsibility. The only prototype sprinkle is clickedLink.up().next(); which shows off the prototype DOM navigation rather than the old document.getElementById unpleasantness.

All in all I was surprised how little code it took and how readable the code was. Mmmm, tasty and virtually calorie free.

Friday, 20 February 2009

70-431 Hints and Tips

I passed 70-431 (TS: Microsoft SQL Server 2005 - Implementation and Maintenance) a while ago and it’s shamefully taken months to get round to blogging the tips. As ever, the general tips are read a book, do some sample exams, fill the gaps from MSDN, do the exam and good luck. More specific tips are

The Book
As I’ve said before the Microsoft Press books are of an extremely variable quality. In this case the book is pretty good and covers the right stuff. You’ll still need to plug the gaps from MSDN.

The Simulation
This is the big tip. Unlike every other MS exam I’ve done this one has a simulation of some typical database tasks at the end. The simulation mocks up the Database Management console and asks you to click around to complete the different tasks. Make sure you can do the simple stuff such as
  1. Perform a full backup.
  2. Perform a differential backup.
  3. Perform a transaction log backup
  4. Restore a database
  5. Create a login and user for a database
  6. Access and run a profile

This list isn’t exhaustive but is the type of things that could be on the sim.

The Links
Below are the links that I used to supplement the Microsoft books. Some of these are pretty dry reading and again this isn’t exhaustive.

Installing and Configuring SQL Server 2005
Returning the login name associated with a security identification number (SID)
Ownership Chains

Maintaining Databases
Backup T-SQL
DBCC CHECKDB
Creating full DB backup
RESTORE T-SQL
Dedicated Administrator Connection

Creating and Implementing Database Objects
Creating Certificates
Rollup T-SQL
Xml Indexes
Auto Mode for Xml Queries
User Defined Types T-SQL
Indexed Views

Monitoring and Troubleshooting SQL Server Performance
Sp_addmessage

Supporting Data Consumers
SQL Server Browser Service
Server Broker Contract
Service Broker Endpoints
Service Broker Endpoints with Kerebos
Endpoint authentication

And of course best of luck if you’re taking the exam.

Wednesday, 18 February 2009

Geek Pin-ups

In the course of general office chit-chat it was asked “who was your favourite childhood pin-up?”. Being a bit of a geek I struggled for any kind of answers and muttered something vague and non-committal. As a mini-child geek I didn’t do pin ups of pop-stars and other such normal, healthy juvenile obsessions. I was too busy sticking paperclips in the back of my Commodore 64 just to see what it would do.

So I got to thinking - what would be the pin-ups of geeks. What should adorn the grey walls of our work pods?

ZX Spectrum
It’s every geek’s first love. Squishy keys, the size of a postage stamp and graphics that give migraines. Hours wasted with our Jet Set Willys. If you’ve every wondered why the average geek doesn’t have a girlfriend until they’re 25 then this probably goes a long way to explaining why.


Space Invaders
Big as a refrigerator, monochrome graphics and 10p a go to you, young fella my lad. If you have just floated your new Web 2.0 company for millions on the NASDAQ then you’ll have a whole room full of these kind of machines. For everyone else, it’s a poster on your cubicle wall and some warm, fuzzy memories of summers spent in darkened rooms playing this. Sunlight, pah, that’s not for geeks.



Mandelbrot Set
It’s like maths but it’s beautiful. It’s numbers with colours. It’s algebra with swirls. Pin it up and then spend hours explaining to colleagues the bizarre recursive mathematics that generates it. Everyone loves a maths whiz (possibly).

C-3P0
The golden translator droid of Star Wars surely deserves a place on every geek wall. The more rebellious geek may opt for the more edgy R2-D2 but I think everyone will agree that hours spend staring at C-3P0 in wonder are hours well spent.



Blog Hero
What geek wall would be complete without a picture of an IT blog hero doing his thing. Mmmmmm – a step to far maybe.

Friday, 13 February 2009

Web Development Tool Freebies

Even though I work day to day creating software I find it very hard to pay for it. I know that I should but when it comes to entering the credit card details I have an almost physical reaction then have to lie down for a while in a darkened room and sip some weak tea. It could be because I was born in Yorkshire (in the UK) and Yorkshire folk although fine and upstanding people are not known for their free spending ways. In any case I gravitate time and time again to freebies are here are my favourites for web development.

IE Developer Tool Bar
http://www.microsoft.com/downloadS/details.aspx?familyid=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en
I’ve never subscribed to the Microsoft is evil school of thought so with that in mind this is one of my favourite freebies. Lots of extensions to ease the web development process. Particular favourites of mine include changing the screen size without messing found with the control bar and isolating html elements by click. And the price – well no money need change hands but Microsoft will obviously pump pro-Vista propaganda directly into your skull as soon as you press the download link. Aww – those guys!!!

NotePad++
http://notepad-plus.sourceforge.net/uk/site.htm
A must for all amateur developers. Lots of colouring coding for your code in formats from Ada to YAML with some macro stuff and a decent find and replace thrown in. What’s more it doesn’t take 4 days to install and 3 hours to load up like some other IDEs that will remain nameless (Visual Studio).

Regulator
http://sourceforge.net/projects/regulator/
Like most developers I’ve an ambivalent attitude to regular expressions. They are super useful but once you’re doing anything more complicated than finding a word then they might as well be written in hieroglyphics. So some kind of tool is essential. This one is a bit buggy on the last release I snaffled but still does the job. Lots of handy prompts and highlighting of your latest regex attempt. I think out of all of the recommends this would be the one that I would most consider spending some money on to upgrade to a more reliable product (probably Regexbuddy). Still it works well enough and it’s nought pounds and nought pence to buy. Great.

Filezilla
http://filezilla-project.org/
So once you’ve finished created you’re latest website of sheer brilliance then you’ll be wanting to get it straight up on the Internet so that all and sundry can marvel at your genius. No problem – Filezilla is the FTP client for you. Nice intuitive interface and does exact what’s needed - gets your files onto the server lucky enough to host your work of art. I was using SmartFTP for a while for this but it needed patch after patch and then churlishly they suddenly wanted to be paid for it. Can you believe it – developers wanting to be paid. I was quite frankly appalled.

Paint.Net
http://www.getpaint.net/download.html
This is something I thought I’d never see – a great image manipulation package for nothing at all. Wow! I’m sure that if I was a graphic designer and divided my time between snowboarding, wearing garish T-shirts and refusing to use PCs because Macs are sooo much better – then I might turn my nose up at this. But I’m thrilled if I can resize and image and do a fill with a gradient so this one is for me. My favourite out of all the recommends and the one that I would be most likely to donate money to if I wasn’t so mean.

Monday, 9 February 2009

Trivalent Logic

My two favourite posts on DailyWFT is the Brilliant Paula Bean and What is Truth. Whereas the Paula Bean post is just, well, brilliant the What is Truth post I’ve started to feel is a tad harsh.

The post describes the most bizarre enum – a custom Boolean with three values – True, False and FileNotFound. Hahahahaha – how dumb. However the Infragistics Excel component I’ve been using recently also has a three part Boolean

ExcelDefaultableBoolean.True
ExcelDefaultableBoolean.False
ExcelDefaultableBoolean.Default

Mmmm – less dumb. And it doesn’t take much to dream up circumstances that you may need more parts to your Boolean

True
False
Default
Unknown
Not Specified

We seem to expect that because computers work with 1s and 0s we should too and any attempt to extend Boolean logic is just wrong. However, while jamming file not found into a bool may well be a little odd, I’ll certainly be liberating my Booleans this week from the tryanny of binary logic. 10 part Booleans anyone. You know you want to.

Saturday, 31 January 2009

Testing for Database Nulls in C#

Things I always forget

  1. Mother’s Day (sorry mum)

  2. My mobile phone telephone number

  3. The 7 times table

  4. How to test for Database nulls

There’s not much hope for the first three – however maybe a quick blog might help with the last one

How I always try to test for database nulls


If(drDataRow["FieldName"] == null)

{

//Nope this never works. I won’t hit this

}

How I should test for database nulls


If(drDataRow["FieldName"] is DBNull)

{

//It works! Shirt off and do the victory dance

}

Now if I can just work on those times tables ………

Wednesday, 28 January 2009

Which Building is your Software?

It’s been (excessively) often noted that software is like a building. We do software construction, there’s software architects, we all wear hard hats at work (maybe that’s just my office though) and so on. So, which building exactly is your software most like?




The Pyramids
Software of great age built with ancient technologies (probably COBAL). Everyone admires it but no-one dare touch it and certainly no-one would every dream of extending it. It’s stood for years but for God sake don’t mess around with it.





Humber Bridge
An impressive feat of engineering. Ahead of its time but built for all the wrong reasons. Looks great but is an enormously over engineered solution to a problem that never existed in the first place.


The Gherkin
An impressive feat of architecture that is the top of its class. Has rapidly become iconic and sets the benchmark for all other endeavours in that field. Makes everyone one else feel a tiny bit anxious and inadequate.








The Sears Tower
Built by men, for men for a man’s reason. Huge, thrusting, enormous but pretty much bankrupts any company involved in it. If the project survives and doesn’t bring everyone involved down with it – it will be truly amazing. Brilliant but at great human cost.







Lumiere Tower (Leeds, UK)
Ambitious, stylish and visionary. All the design work done and the foundation laid but then suddenly cancelled. Like the Sears Tower but someone took a brave decision before it bankrupted everyone involved.





The Towering Inferno
A fantastic project. State of the art and impressive. Everyone wants to be associated with it. However fatal construction flaw comes to light too late and the entire thing bursts into flames. Sticking plasters required.






Grove Pub (Leeds, UK)
The tiniest end of terrace pub next to the biggest building in the city. A well established but minor project much loved by a small user base. Operates in same field as a new behemoth who desperately wants to squash it. However against all expectation the minor projects thrives more that ever. The value of user loyalty.

The above pciture shows the Grove Pub while Bridgewater Place (biggest Leeds building) was under construction. Now that Bridgewater Place has been completed it really does look like David and Golaith. Picture was provided by Russell J Smith on Flickr

Saturday, 24 January 2009

Estimating Lines of Code

I’ve always been a bit puzzled on why people would use lines of code to estimate projects. It seems that estimating (more realistically guessing) lines of code (LOC) to estimate effort and schedule is way harder that splitting the project into jobs and undertaking an estimate for each job. However reading Steve McConnell’s Rapid Development book has changed my mind.

In it he has charts linking lines of code to effort over a range of criteria. So if you know the LOC for your projects you can plug them into the tables and see how you projects measure up. Moreover you could get lines of code for a project to build a historic set of data tailored to your team to take some of the guess work out of that blackest of all arts – software estimation.

Which got me thinking of how you would quickly get non-commented, non-whitespace lines of code for a Web Application written it ASP.Net



C#
Count the semicolons C#.

CSS
I would count the number of {

HTML
LOC are more difficult here. Possibility to count open angled brackets (<) and maybe divide by 5 – making the assumption that there is 5 tags per line JavaScript and VB.Net
Semicolons doesn’t work so well here as they are optional in the code. You’d need to be a bit cleverer and count the number of carriage returns without comments and with a length of more then one when been trimmed

OR

Quick and dirty: arbitrarily estimate the number of characters per line then whip through all the files and could the characters and divide by the per line estimate.

SQL stored procedures and functions
Like JavaScript you’d be looking at using carriage returns or using the quick and dirty method

Other elements.
For example SQL reports, Data extract components etc…
Can’t do anything with these so get the back of the envelope out and estimate what fraction of the project was spend on these activities. Multiple the LOC by this ratio.



In the best of all worlds we would all use function points or some kind of automated formula based approach but I moved out of the best of all worlds sometime ago and sadly my software development occurs in the dirty old real world. In this world one frequently doesn’t have time to spend half a day calculating historical effort but you’ll always have the opportunity to spend a sneaky 15 minutes seeing how many LOC were wrote and how long it took. It’s always good to marvel at how much work you’ve done and it may even make software estimation a slightly less black art in the future.

Wednesday, 21 January 2009

It’s a BUG


The other day I was merrily exporting a SQL Report to Excel when I came across this cheeky little message where some tables should have been

"Data Regions within table/matrix cells are ignored"


A quick search on forums reveals the following solution


This is a known issue in the reporting services. It is caused by the limitation of the Excel rendering. So you may redesign the report or export to other formats.


Well that’s a relief. It’s not a bug it’s a known issue and limitation, entirely different from a bug. If it was a bug I’d be stuffed and would have to go back to my project manager and tell him that we’re starting the export again from scratch so the deadline is receding rapidly into the distance. Thankfully because it’s only a limitation I only need to go back to my project manager and tell him that we’re starting the export again from scratch and etc………..

IT’S A BUG. It’s not a limitation, known issue, user error, unforeseen circumstance or convergence of several highly unlikely events. Come on Microsoft admit to it. My software’s got bug’s, my colleagues software’s got bug’s and Microsoft’s software’s got bugs. It’s nothing to be ashamed of. The first step to solving a problem is admitting it’s there. Mr Bill Gates – you’ve got a bug.

Saturday, 17 January 2009

Facts and Fallacies of Software Development


It’s been said by people a lot cleverer that me (DeMarco and Lister 1999 – Peopleware) that most developers don’t read books. So with a typical level of humdrum insight I’ve worked out that if I read a few programming books a year then it will lift me a bit above the norm – keep a positive career calculus.

Facts and Fallacies of Software Development by Robert Glass is the latest book to have taken up residence on my bedside table. It’s a collection of little known “facts” with a smaller number of falsehoods about software engineering – unsurprisingly. How though can there be a “fact” in a profession that seems to owe more to superstition and religion than it does to science and engineering. The conceit it that the facts are items of research and less often the authors personal experience. So at it heart it is a book popularising academic research in a series of short (1 -5 page) articles.

So does it work? I have enormous sympathy with the project of academic popularisation and God knows – computer science needs it more than most. It’s very engaging, very readable and gives food for thought. For me though the nature of the book makes it a bit disjointed. I appreciate IT books are novels – but that said I do like them when they have more of a beginning, middle and an end. That said – for dipping into its perfect. So buy it when you’ve a long journey – sitting on a train, sipping an overpriced coffee and reading this book – that’s the way to travel.

And my favourite fact – well it’s “[Software] Maintenance is not a problem it’s a solution”. When you’ve completed your project and your client comes back with 4 pages of desired enhancements it isn’t because your product is rubbish – it’s because your client has total engaged with it and can now see the potential. And if they pay for it – then everyone’s a winner.

Wednesday, 14 January 2009

Gordon Brown Loves Developers. It’s Official


It appears that Mr Gordon Brown our beloved prime minister is proposing that we reinflate the UK economy by a massive digital infrastructure programme. Mr Brown has clearly been reading recent Tech Splurge posts and is quite rightly basing his economic policies on my idle technology musings. With this blog as his guiding light we can expect the recession to be a mere blip.

While Mr Brown is in the technology investment zone here’s a five point tech investment plan that can only assist the UK ailing economy.


  1. Two monitors for all programmers and designers.

  2. Comfy chairs and foot stools for anyone who knows what a complier is.

  3. Free StarBucks/Café Nero coffee for anyone even obliquely involved in software development.

  4. Dry cleaning service for anyone that can write a bit of HTML

  5. Free taxis service for anyone who can tell the difference between a computer and a microwave.
With this forward thinking policy I believe that the UK will be at the forefront of technological innovation and the five point plan is in now way motivated by greed, self-interest and a desperate attempt to get something for nothing.

Saturday, 10 January 2009

T-SQL Random Data Generator

I always think that creating a component to generate random data for a table in SQL Server should be easy but it never is. I’ve written a few windows components in the past to do this but I always leave them in random folders and lose them in my sock draw. So I’ve spend a bit of time writing a stored procedure that will do the job – so I can keep it associated with the database du jour and not lose it. The proc isn’t perfect but then neither am I.

What it does
  1. Will output an insert T-SQL statement for any named table in the database.
  2. Only tested on SQL Server 2005. The INFORMATION_SCHEMA use should make it forwardly compatible but doesn’t do backwards compatibly any favours.
  3. Detects foreign keys and inserts and makes a random but valid link to the child table (this was the hard part)
  4. Detect different data types and do the necessary SQL formatting
  5. Accounts for max character length in string type fields
  6. Accounts for identity columns
  7. Detects nullable columns and leaves them null

What it doesn’t do
  1. Doesn’t account for unique indexes
  2. There are omitted datatypes (cursor, timestamp, uniqueidentifier, binary, varbinary, image)

Horrible hacks
Where the foreign key links where linked to child table via a unique index rather than a primary key it assumes a foreign key of 1. The INFORMATION_SCHEMA views don’t include index information. So this would necessitate delving into the sys.index table. Not impossible but the proc was complicated enough as it was. I didn’t need it so I didn’t do it.

Assumptions
  1. Foreign keys are of a numeric type i.e. int, float et. al.
  2. Foreign key constraints exist on the database. It isn’t magic – it can’t work out the relationships if they don’t exist.


Create Procedure usp_RandomInsertGenerator
(
@TableName nvarchar(128)
)
As

Begin

Set NoCount On

Declare @ColumnName nvarchar(128)
Declare @FK_TableName nvarchar(128)
Declare @FK_ColumnName nvarchar(128)
Declare @ConstraintName nvarchar(128)
Declare @DataType nvarchar(128)
Declare @CharacterMaximumLength int
Declare @Sql nvarchar(max)
Declare @MaxValue int
Declare @InsertValue nvarchar(200)
Declare @SqlOutputFields nvarchar(max)
Declare @SqlOutputValues nvarchar(max)
Declare @FirstLoop bit
Declare @IsIdentity bit
Declare @StringInsert bit
Declare @DummyText varchar(48)

Set @FirstLoop = 1
Set @SqlOutputFields = 'INSERT INTO ' + @TableName + ' ('
Set @SqlOutputValues = ' VALUES ('
Set @DummyText = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

-- cursor loops through every column for named table
Declare procCursor CURSOR FORWARD_ONLY
For
Select
COLUMN_NAME,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH
From
INFORMATION_SCHEMA.COLUMNS col
Where
TABLE_NAME = @TableName
And IS_NULLABLE = 'NO'
Order By
ORDINAL_POSITION

Open procCursor
Fetch Next From procCursor Into @ColumnName, @DataType, @CharacterMaximumLength

while @@fetch_status <> -1
Begin

-- datatypes i haven't bothered implementing
if @DataType = 'cursor' OR @DataType = 'timestamp'
Or @DataType = 'uniqueidentifier' Or @DataType = 'binary'
Or @DataType = 'varbinary' Or @DataType = 'image'
Begin
Raiserror('Unsupported Data Type', 1, 16)
End

--reset variables
Set @FK_TableName = ''
Set @FK_ColumnName = ''
Set @StringInsert = 0
Set @ConstraintName = ''

-- Don't add in an insert value if the loop is an identity
Select @IsIdentity = COLUMNPROPERTY(OBJECT_ID(@TableName),@ColumnName,'IsIdentity')
if @IsIdentity = 1
Begin
Fetch Next From procCursor Into @ColumnName, @DataType, @CharacterMaximumLength
continue
End

-- getting the value to be inserted for this data type
if @DataType = 'varchar' Or @DataType = 'nvarchar'
Or @DataType = 'char' Or @DataType = 'nchar'
Or @DataType = 'text' Or @DataType = 'ntext'
Begin
Set @StringInsert = 1
Set @InsertValue = SubString(@DummyText, 1, @CharacterMaximumLength)
End
Else if @DataType = 'datetime' Or @DataType = 'smalldatetime'
Begin
Set @StringInsert = 1
Set @InsertValue = Cast(GetDate() as varchar(20))
End
Else -- it is some key of numeric type
Begin

-- getting the child table indexes
Set @Sql = '
Select
@FK_TableName = pkconst.TABLE_NAME,
@FK_ColumnName = pkconst.COLUMN_NAME,
@ConstraintName = coluse.CONSTRAINT_NAME
From
INFORMATION_SCHEMA.KEY_COLUMN_USAGE coluse
Join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS fkconst
On fkconst.CONSTRAINT_NAME = coluse.CONSTRAINT_NAME
Left Join INFORMATION_SCHEMA.KEY_COLUMN_USAGE pkconst
On pkconst.CONSTRAINT_NAME = fkconst.UNIQUE_CONSTRAINT_NAME
Where
coluse.TABLE_NAME = @TableName
And coluse.COLUMN_NAME = @ColumnName'


Execute sp_executesql @Sql, N'@TableName nvarchar(128),
@ColumnName nvarchar(128),
@FK_TableName nvarchar(128) OUTPUT,
@FK_ColumnName nvarchar(128) OUTPUT,
@ConstraintName nvarchar(128) OUTPUT',
@TableName=@TableName,
@ColumnName=@ColumnName,
@FK_TableName=@FK_TableName OUTPUT,
@FK_ColumnName=@FK_ColumnName OUTPUT,
@ConstraintName=@ConstraintName OUTPUT

if Len(@FK_TableName) > 0 And Len(@FK_ColumnName) > 0
Begin

/* have found foreign key and the lookup table
so pick a random primary key from the lookup table */
Set @Sql = 'Select top 1 @InsertValue = Cast(' + @FK_ColumnName +
' as varchar(200)) From '
+ @FK_TableName + ' Order By newid()'
Execute sp_executesql @Sql, N'@InsertValue nvarchar(128) OUTPUT', @InsertValue=@InsertValue OUTPUT

End
Else if(Len(@ConstraintName) > 0)
Begin

/* OK we've found the foreign key constraint but have no idea what the
lookup table is. This is because we are joining on a unique index to the
lookup table not a primary key. Make a MASSIVE assumption in this instance
- that the lookup table has a link value of 1 */
Set @InsertValue = '1'

End
Else
Begin
-- no foreign key so the max that can be inserted is based on the datatype
-- don't bother with any thing greater than thirty thousand - big enough
if @DataType = 'bit'
Set @MaxValue = 1
else if @DataType = 'tinyint'
Set @MaxValue = 255
else if @DataType = 'smallint'
Set @MaxValue = 32767
else
Set @MaxValue = 32767

-- randomly generate a number to insert up to maximum
Set @InsertValue = Cast(ROUND(((@MaxValue - 1) * RAND() + 1), 0) as varchar(200))

End
End -- end of numeric processing

-- building up output string
Declare @Delimiter char(1)
if @FirstLoop = 1
Begin
Set @FirstLoop = 0
Set @Delimiter = ''
End
Else
Begin
Set @Delimiter = ','
End

Set @SqlOutputFields = @SqlOutputFields + @Delimiter + @ColumnName

if @StringInsert = 1
Begin
Set @SqlOutputValues = @SqlOutputValues + @Delimiter + '''' + @InsertValue + ''''
End
Else
Begin
Set @SqlOutputValues = @SqlOutputValues + @Delimiter + @InsertValue
End

Fetch Next From procCursor Into @ColumnName, @DataType, @CharacterMaximumLength
End -- finished this column = go to next

close procCursor
deallocate procCursor

-- outputting the sql string
Set @SqlOutputFields = @SqlOutputFields + ')'
Set @SqlOutputValues = @SqlOutputValues + ')'

select @SqlOutputFields + ' ' + @SqlOutputValues

End
Go


It’s very easy to create a wrapper sproc to get multiple statements.
One row of random data isn’t that much use – 10,000 might be.



Create Procedure usp_RandomInsertGeneratorWrapper
(
@TableName nvarchar(128),
@NumberOfInserts int
)
As
Begin

Set NoCount On

Declare @StatementCount int
Set @StatementCount = 0

While @StatementCount < @NumberOfInserts
Begin

exec usp_RandomInsertGenerator @TableName
Set @StatementCount = @StatementCount + 1
End

End

Room for improvement
Here’s some extensions that my be useful for individual projects
  1. Implement missing datatypes. Things like uniqueidenifier would be very easy indeed to implement. It’s just that I didn’t need it.
  2. Create custom inserts for know field names to give more realistic data for your application
  3. Randomise the character data properly.
So that’s it. Live it, love it and fiddle about with it a bit.

Wednesday, 7 January 2009

Mobile Phone Whisperer


It was a moving, almost spiritual moment. In a bustling, busy office a mobile phone begins to chirrup. It chirps, chirrups and cheeps and no-one answers. People look up and sigh but still the mobile phone bleats away. A young woman stands up and advances towards the phone. She leans towards the phone, puts her finger to her lips and shushes the phone. The phone ignores her. Undaunted the woman leans closer to the phone and shushes again. This time the phone listens and obeys. Its chirping ceases and the office once again can work in silence. The woman is a mobile phone whisperer.

Like the less interesting horse whisperer and ghost whisperer the mobile phone whisperer has a deep empathetic relationship, in this case with mobile technologies. So close it almost seems supernatural. If you are fortunate you may work near one of these special individuals. I urge you to pay attention, even homage to them and learn all you can about the ancient art of mobile phone whispering.

Saturday, 3 January 2009

70-551 Hints and Tips

I recently did battle with the source of all evil in the world or to give it it’s official title Microsoft exam 70-551 - MCAD Skills to MCPD Web Developer by Using the Microsoft .NET Framework. A snappy title for an exam that really does bite. Lucky recipients of the qualification will receive the hand of a fair maiden and sparklely new MS certification MCPD Web Developer. Since I’m a sucker for any new certification I embarked on this foolhardy quest.

The beast to slay is characterised by the following
  1. Composed of three lesser beasts
    Exam 70–528 : TS: Microsoft .NET Framework 2.0 - Web-Based Client Development
    Exam 70–536 : TS: Microsoft .NET Framework 2.0 - Application Development Foundation
    Exam 70-547 : PRO: Designing and Developing Web Applications by Using the Microsoft .NET Framework
  2. It’s three hours long. Normal MS exams are about 90 mins typically but can be done a lot faster
  3. You need to pass all the components and your score is the lowest of the three components.
  4. If you fail on component then you fail them all. So do brilliantly on two and fail one by a mark then tough – no exam for you. Try again next time.

General beast slaying tips
  1. The exam does absolutely stick to the syllabus. So print of the entire 70-551 syllabus and go through the component ones – 70-528, 70-536 and 70-547 deleting any content that isn’t on 70-551. You’ll end up with about 50% of 70-536, 75% 70-536 and 95% of 70-547.
  2. There isn’t any specific books for 70-551 so you’ll have to go to books for the individual exams. At the time I did this there were only the Microsoft press books which event if I’m charitable are generally of variable quality. Still better than nothing. The amended syllabuses from above will prevent you going over unnecessary content.
  3. After you’ve read the books – do transcenders or equivalent. You will probably fail them at this point.
  4. From the transcenders it should be obvious where you’re weak. Get to MSDN and plug those gaps
  5. Take the exam and good luck

70-536
The Microsoft Press book is quite good for this. This with the transcender will probably see you through it. Areas to look out for


There’s obviously more but these areas kept cropping up


70-528
Even though my job is primarily web development I found this part the worst. Don’t rely on knowledge of ASP1.0 to get you through. It’s focussed on the new features and particularly the (obscure parts) of the new controls. The Microsoft Press book is of less use but still worth a read. Areas to look out for

70-547
This is like ASP1.0 70-300. If you loved that then you’ll love this. I didn’t love either. The Microsoft Press book was no help. White papers were of limited use as well. It comes down to experience so it that respect it’s a very effective exam. The following areas may help

Last word
It’s a lot to know and many things can go wrong so expect to fail. You can pass on the second time (I did). You only need to be lucky once.