Wednesday, August 30, 2006

Delphi the best tool for .NET? Er, no

Nick Hodges is doing a fine job of evangelizing Delphi which makes me think Delphi may have some kind of future but in his latest post, he suggests that Delphi is the best choice for .NET development. Delphi is certainly still a great choice for native Win32 application development but it just can't compete in the .NET world. There still isn't a version that supports .NET 2 so Delphi developers don't get to play with all the new features. Delphi is always likely to be playing catch-up in this respect. Also, almost all .NET code examples on the web are in C# or VB.NET which would make life more difficult for anyone developing in Delphi for .NET.

There are situations where using Delphi in a .NET environment makes sense. If you have a large Delphi code base that you want to get to .NET, rewriting in C# or VB.NET isn't likely to be the most cost-effective solution. If for some reason you need to target Win32 and .NET, Delphi would also be a good solution, in fact probably the only solution.

Finally, looking round at new applications coming out, we are now starting to see .NET managed desktop apps appearing. How many of them are written in Delphi? I don't know of one. In the world of ASP.NET I guess it's harder to know what language is being used for the development but I'd guess the vast majority of them are in C# or VB.NET. Compare this to the world of Win32 development where there are quite a few high quality apps being actively developed in Delphi and it's clear that .NET developers also don't think Delphi is the best tool for the job. 

Sunday, August 27, 2006

Getting into MySql with PHP

Our host for the Random Pub Finder has been providing MySql integration for a while. I've been holding off using it for a while because I was thinking of converting the RPF to ASP.NET. But I eventually decided that was going to be too much like hard work and would break any links in. OK, I could probably do some URL rewriting to get round that but again it seemed like a lot of bother and PHP does pretty much everything we need.

Anyway, I signed up for the MySql integration and I've been pleasantly surprised with how good the phpMyAdmin web interface is. RPF has been running off several text files for the last five years so I had to make quite a few changes to our code but getting the data in to MySql was pretty straightforward (phpMyAdmin will suck in any kind of delimited text file). Setting up phpMyAdmin on my local machine was pretty straightforward. OK, it's not MS easy, but then this is a free bit of software developed by people in their spare time. So I had to tweak a few text config files to get it working and I couldn't get it to play with PHP 5 but PHP 4 is fine for our needs. And now it's working I'm presuming I won't need to touch it again.

Updating the RPF live site is now much simpler, I just insert a new row in a table and a new pub appears on the site. Previously I had to update one of our text files and email it to myself, run to my other half's laptop, download the email and FTP it to our host via a phone modem, because they won't let me connect to the FTP site via our broadband connection. I guess that's because their business model is based on getting revenue from phone calls... 

So, in conclusion, a thumbs up for PHP, MySql and phpMyAdmin. Perhaps I'll stop being an MS fanboy and become a open-source zealot. Time to grow a beard...

Programmable Web

Just found this site, which looks like a useful resource for knocking together Web 2.0 (God I hate that term) mashups (God I hate that term)

Thursday, August 24, 2006

What is the point of Second Life?

Apparently it's very popular with the young uns but I'm failing to understand why. I've been wandering around for a while and there just doesn't seem a great deal to do, except check out some butt ugly buildings. If I want to live in a fantasy world I want to be able to do some fantastic things, like wield big guns and blow up things, not just socialise...

Worst of all, I seem to have to download a new version every time I log in. 

Wednesday, August 23, 2006

Google Maps and the Random Pub Finder

OK, I got bored waiting for a response to my queries about ripping off people's code so the Random Pub Finder London Map has gone live. Trying not to be too big headed, I think it's superb. None of it would have been possible without phpcoord and overplot. If programming is an art form then the old adage 'good artists borrow, but great artists steal' must be true...

Solving the Google Maps performance problem

Google Maps has a nice API to create your own map interfaces on a website. Unfortunately it has some serious performances problems when you add a large number of markers. In my case, I have about 500 markers and both IE and Firefox grind to a halt on my page. I've seen various suggested solutions, the most common being to reduce the number of markers by only showing one marker when there are several clustered together when zoomed out. I'm sure that would work but I wasn't too keen on the idea because it just sounded like too much work. Fortunately somebody has come up with a nice solution that works well for me. thanks to the wonderful open source nature of the web, I can happily rip off his code. Just need to get approval from him before I show off my new page to the world...

Sunday, August 20, 2006

Pompous rock star is hypocrite shocker

This is old news but apparently Chris Martin, lead singer of Coldplay and a man known for mouthing off incessantly about environmental issues, owns a BMW X5. This Chelsea Tractor will be doing approximately 15mpg as he drives near his central London home. Nice one!

Thursday, August 17, 2006

More Windows Live Writer

A comment to my previous post from Spike Washburn (of the Windows Live Writer team no less!) suggests image uploading won't be supported until Blogger improve their API, which is a shame. So Blogger, get your finger out! And apologies if it appeared that I was suggesting Windows Live Writer deliberately wasn't supporting image uploads to Blogger.

A couple of other points about Writer. First, I'm very pleased to see it is a managed application. Great to see MS dogfooding the .NET Framework and proving it's possible to produce professional apps using WinForms. 

Second, it's great to see developers from MS responding to blog posts from little old me. Fact is I'm a Z-list blogger that no-one reads but I've had two lots of feedback from MS people. That kind of communication will really help build a good feeling towards MS in the IT community.

And yes, I'm using Writer to write this post.

Windows Live Writer

Just playing around with Windows Live Writer and it's mostly pretty cool. The first problem I've encountered is the lack of image support on Blogger, which is pretty much a showstopper. Odd really, because Blogger does support images, but I guess this is a beta...

More fun with <noscript> tags

The guys at BetterDeal wanted to know why their website didn't rank as highly as some of their competitors. Short answer is inbound links, which seems to be the prime ranking decider used by Google. To illustrate I did a link:www<dot>carbroker<dot>com<dot>au search (replace the <dot> with ., don't want them getting anymore inbound links), which is one of their competitors. The odd thing was that one of their inbound links came from a penis enlargement site. Penis enlargement doesn't have a lot to do with new cars, other than the obvious psychological enlargement for men who buy big red Ferraris. Looking at the source of the penis site (purely for research of course) showed up the reason. The link was hidden away in a <noscript> tag. Car Broker are also the guys who have <noscript>betterdeal</noscript> hidden away in one of their pages slagging off reverse auctions, which is why they rank pretty highly for a search on "BetterDeal reverse auction". Although Google know about this, they haven't done anything about it and their algorithm still doesn't seem to handle <noscript> tags too well...

Tuesday, August 08, 2006

Borland goes Turbo

So Borland have revived their Turbo range of products. The originals came out before I did any real programming (the ZX Spectrum probably doesn't count) so I don't how revolutionary they were at the time. But the question remains whether this will help revive Borland/DevCo's fortunes. Microsoft moved the goalposts when it released its Visual Studio Express range for free, and Borland had no choice but to respond by releasing free versions of its own development tools. But free and academic versions don't bring in a lot of revenue and although they may drag people in Borland's direction who may start to pay for products later, that's likely to be a long term effect. For Microsoft, development tools are a loss leader, they don't care if they make money so long as they keep people using Windows. For Borland/DevCo it's essential these products make money or else they're out of business. On another note, although the Delphi community seem to be very excited about these new developments, will the rest of the world care? The people who Borland seem to be aiming for, i.e. new developers, probably don't have a clue what the Turbo range was and because of that the new website probably doesn't look retro and nostalgic, it just looks naff. Saying all that, I am pleased to see Borland/DevCo making some positive moves to sell their development tools, it certainly makes a change from the last few years.

Monday, August 07, 2006

Land Rover's misplaced marketing

Today I received a letter from Land Rover, offering me the chance the test drive their latest model. Whilst I'm sure it would be fun, there's no way I'd ever think about buying a new Land Rover so why are they sending it to me? I'm not sure where they got my address from but I think they need to do some better filtering of their mailing lists. First, I can't afford a new Land Rover. Second, I live in the middle of the largest city in the UK, why on earth would I want to buy a car that has 'authentic off-road ability'? Third, I'm concerned about this environment thing. Why would I want to buy a car with a 4.2 litre engine that does approximately 13 miles to the gallon with CO2 emissions of 374g/km??? It's nice to see their letter was printed on paper from sustainable forests, but perhaps they need to sort out their massive gas guzzling machines as well? To be fair, the original Land Rover is a design classic and before I realised the environmental damage owning one would do, it was near the top of my list of cars to own. Any way, the real reason for this post is to point out there is a way to stop receiving all this junk mail. MPS Online claim that they will stop unsolicited mail coming to your door. I only signed up a week or so ago so it hasn't stopped yet but fingers crossed it will do soon.

Sunday, August 06, 2006

Richmond Park

Truth be told I don't much like London. When hearing this, people will often trot out the usual Samuel Johnson line, but the fact is Johnson lived in an entirely different London to the one I live in now. But one of the great parts of London has to be Richmond Park (although some people will claim this isn't really part of London, because it's in zone 5). When cycling around its huge area, I can almost forget that I'm anywhere near the busy, unfriendly city I know.

Thursday, August 03, 2006

Lots of new posts

Just copied across the interesting posts from my old blog, enjoy!

DesignerSerializationVisibility attribute

When writing .NET components, often you don't want properties to appear in the Property Window. This is well documented and is achieved with the following [Browsable(false)] But what you also generally want to happen is for the property not to get persisted to the form in the InitializeComponent method. Unfortunately the Browsable attribute doesn't do this part of the job, but thanks to one of my colleagues, this is how you achieve that. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] Perhaps there are occasions where these would be used separately but I can't think when they'd be

Use the tool, tool part 8

OK I lied, the last post wasn't my last post on .NET tools, there's one more. NAnt is a handy tool for automating builds. Although it's possible to drive Visual Studio.NET from the command-line, NAnt does lots of other things, like running your unit tests and zipping up files etc etc via an XML configuration file. I haven't used it a great deal myself, but I will be shortly.

Use the tool, tool part 7

Right I have one more .NET tool to recommend and then I'm done. And that is FxCop. This will analyse your assemblies and tell you all the problems it finds. And my word, does it find a lot of things. The fact is a lot of the rules are just plain anal, but it still finds stuff that could be a problem. And whats more, you can add your own rules, although I can't say I've ever done this.

Use the tool, tool part 6

Documentation is a right pain the behind, or at least it used to be. C# simplifies it a great deal by providing in-built support for it. XML tags can be added to your source code as you go along, so that 2 week task at the end of the project can be avoided. So once you've tagged all your code, what next? Download NDoc and you can generate help files just like the ones in Visual Studio. If it hadn't been for this tool, I'd probably never have got round to releasing a little project of my own into the wild. Another useful tool for generating documentation is GhostDoc, which automatically generates a first attempt at the documentation based on parameter names and method names. It doesn't always get it right, but it's often good enough.

Use the tool, tool part 5

I haven't covered the most useful .NET tool yet, the wonderful Reflector. If you haven't got this yet, download it now. One of the great things about Delphi development was the fact that Borland provides the source to the whole component library, which really helps tracking down weird bugs and work out how their stuff works. Microsoft don't provide the source to the .NET Framework, but with Reflector it doesn't matter. It can reverse-engineer any .NET assembly and you can see how it works. Yes, some class library developers obfuscate their libraries, but Microsoft don't and that's the most important library. Reflector also has several add-ins that do useful things like reverse-engineering a whole assembly which is useful for, er, more nefarious deeds. There are also plug-ins to generate Delphi code and other languages. So, as I said before, if you haven't got it, get it NOW!

Use the tool, tool part 4

If you've written some unit tests, the next thing to find out is how much of your code is covered, since you want to get as close to 100% as possible. This is where AQTime comes in. This profiler does all kinds of profiling but the coverage profiler is what you'll want to use here. AQTime may cost quite a bit of cash but it's worth every penny. Another use of AQTime is to track down performance problems. If I have a performance issue in some code, the first thing I do is turn to AQTime. Some people will think about what is causing their performance problems, but frankly what's the point? The theories they come up with are invariably wrong, because more often than not, the actual problem is caused by some poorly implemented algorithm, that manual analysis completely missed. Performance analysis should always be undertaken with the help of a profiler, since not only will it tell you the cause of the problem, but will also tell you exactly how much time you'll save by fixing it.

Use the tool, tool part 3

According to 'Working effectively with legacy code', any code without unit tests can be considered legacy code. That means pretty much every piece of software I've ever worked on is legacy code. Before .NET, writing unit tests was hard. In my Delphi days I tried to use DUnit but the language didn't lend itself to writing a tool that was simple to use. In .NET, attributes and reflection make it much easier. So we have NUnit, which has been the tipping point for me writing unit tests. As well as testing functionality, unit testing also helps validate the design of a system. If it's hard to write tests for your classes, chances are the design isn't too great. It suggests too much coupling and cohesion between the classes. Unit tests are always mentioned in the context of agile development, but there is no reason why they can't be used without adopting the whole philosophy. I have my doubts about some of the agile approach but I still believe unit tests are worthwhile. In the short term, they certainly add time to the development process, but I believe in the long run they save time and improve code quality. Of course management are often more interested in the short term (understandably since in the short term bills have to be paid), so unit tests may be a hard sell.

Use the tool, tool part 2

OK, before I get onto .NET tools, a bit of a diversion first into the realm of web based tools and HTTP. Fiddler is a great tool to see the traffic between IE and any web servers it's talking to. I've used it to track down performance problems and to see what cookies applications are using so I can hack them (meaning interact with them in a non-supported manner rather than steal credit card details...) If you're interested in HTTP calls that are made through some other app than IE, then TcpTrace is the tool for you. It's a little bit harder to set up than Fiddler (but not exactly difficult) and the UI isn't quite as polished but it gets the job done. It also supports any protocol, not just HTTP.

Use the tool, tool part 1

OK, the title is pinched from an article by Malcolm Groves, but I like it. After a week of having to work on an XLA written in the worst development language of all time, VBA, I suddenly realised the importance of using the right tools. You can be the best programmer in the world, but if you're using crap tools, your solution will still be crap. So here is the first in an occasional series of articles highlighting what I reckon are the best development tools. I spend most of my time doing .NET development, so I'm going to concentrate on that side of things. The first and probably most important tool is your IDE. And the clear choice is VS.NET 2003. OK, it falls over occasionally but I've very rarely lost any work. The choice is also easy just by a process of elimination. VS.NET 2002 was essentially a 1.0 product, so best avoided. VS.NET 2005 is a beta, so best avoided. And is just me, or is it one of the most butt ugly pieces of software ever? Delphi 2005 is, by all accounts, flaky as hell. Note, I still think Delphi is the best development language for Win32 client-side development, but for .NET forget it. SharpDevelop has one thing going for it, it's free, but other than that, it's pretty poor. So, almost by default VS.NET 2003 wins. Next time, more .NET tools

Wednesday, August 02, 2006

BPM software comparison

Over the coming days/weeks/months (depending on when I get bored) I'm going to take a look at some Business Process Management (BPM) software and see if it's any good. What is BPM software? Good question. I'm in no position to give a definitive answer to that and I'm sure a BPM expert would give a different answer but to me it's all about automating all the boring repetitive crap associated with any business so workers can get on with more interesting stuff. Or alternatively workers discover they aren't needed anymore and get shown the door... The BPM market is growing and there are heaps of vendors out there producing software so I'm only going to look at products that meet one criteria, they have to provide a downloadable demo version of their software I can play with. If a company doesn't have the confidence to provide a demo then I am deeply skeptical of their software. So the vendors I'll be looking at will be (in no particular order) Savvion, Fuego, Metastorm, Tibco, Fujitsu and Microsoft. I may cover some more if I find they have demo versions I can download. Keep reading!

Monday, July 31, 2006

House price crash? I hope so

When we bought our first flat in 1998, it cost us £99,950. At the time I thought it was a huge amount of money and I thought house prices couldn't rise any more. How wrong I was. Two years later we sold it for £175,000 and bought our current house for £220,000. Again I thought house prices couldn't rise any further and again I was way off the mark. In both cases I wasn't particularly concerned with house prices, since I never thought of buying a house as an investment but rather somewhere to live. Buying was (and still is) cheaper than renting for us since we were lucky enough to buy at a good time. Now our house is worth over £300,000 and by all accounts still rising, although the price rises have certainly slowed down. If we were starting over and looking to buy a place now we couldn't afford to, certainly not where we bought our first flat. I do wonder who can afford to buy somewhere now. But rising prices don't help us either. If we ever did want to move house, chances are anywhere we bought would be over the magic £250,000 mark, meaning our fees would be about £10,000. I can think of lots of things I could do with £10,000 and handing it over to the government doesn't seem the most appealing option. The guys at House Price Crash have been predicting a crash for some time, but they are still waiting for it to happen. The sooner the better as far as I'm concerned.

Friday, July 28, 2006

Windows Live Local vs Google Maps part 2

So I tried to switch to Live Local but my first problem with it is a bit of a showstopper. The map doesn't show tube or train stations, so for getting round London it's completely useless. Back to Google Maps... Windows Live Local 1 - Google Maps 1

Wednesday, July 26, 2006

Windows Live Local vs Google Maps

It all started with a trip to the wilds of Lincolnshire. We'd been there before but I didn't know the way too well, so thinking Google has the answer to everything I thought I'd use Google Maps to give us directions. Turns out the directions it gave us weren't too hot, causing much screaming and shouting between me and my other half who was trying to decipher the instructions. Admittedly where we were didn't help, all the roads and countryside looked the same. In the end we had to call the people we were visiting and ask for their help. Somehow they worked out where we were and guided us in. So for my next little trip I thought I'd give Windows Live Local a try. I was dropping my brother off at Heathrow airport so searched for directions for that. It's been a while since I've used the MS mapping stuff and it has certainly improved, in fact I think it may well have moved ahead of Google Maps. Google may have been first with the whole draggable map thing but they don't seem to have done a great deal since. But back to Heathrow, Windows Live gave sensible driving instructions and printing was completely customisable. Google Maps on the other hand suggested a completely insane route, via the M4. For the reverse trip it suggested a completely different insane route via the M25 and M3. Looks like Google thinks motorways are super fast which in the case of London certainly isn't the case. Final score, Windows Live Local 1 - Google Maps 0

Cunts are still running the world

Jarvis Cocker is back with a new ditty that won't be getting much airplay I guess. Not a great song but I can't help agreeing with the sentiment.

Tuesday, July 18, 2006

An unobjective review of Metastorm BPM 7

First the disclaimer, I used to work for Metastorm, I use Metastorm e-Work/BPM most days for my job and I'm a techy so may not be interested in the same things as a business user of the software. Finally I haven't got my hands on the software yet, so can't comment on stability etc. And because of all that, this review will be completely unobjective and uninformed. First up, and possibly the least important new change, the name. To my mind, e-Work was a good name, if only because my boss's company ranks highly on the search term 'Metastorm e-Work'. BPM on the other hand doesn't set the software apart from every other BPM product out there. It's like Microsoft calling their word processor software 'Word', what they did? OK, perhaps I'm wrong... Having had a quick look at the webinar, there are quite a few new features. Metastorm seem to be making a lot of fuss about the SharePoint integration, I'm not hugely interested in this but if you're a SharePoint shop already it looks pretty sweet and much improved over the previous ActiveX implementation, perhaps not in features but certainly in acceptability in the corporate world. The Designer gets a makeover, going down the Visual Studio route with dockable windows, which should be pretty useful in terms of screen real estate. There are new icons, but they look pretty ugly to my eyes. There are a few new features (including the ability to specify roles in a library which made me laugh since this used to be possible until it was pulled out of the product for some reason). You can now find which procedures use which libraries in the database, which is most welcome. Internationalization has improved but is not complete. It also hasn't been added to the Outlook client which is a shame and perhaps signifies the Outlook client may be coming towards the end of its life. There is a new Integration Manager, although I'm unclear what this is for, integrating with the bought out CommerceQuest stuff I guess. Overall I'm pleased to see there has been a reasonable amount of time spent on the core product, rather than features required to be buzzword compliant (anybody using that rules engine integration?). My personal bugbear with the product is the e-Work scripting language that just isn't powerful enough as a scripting language. Unfortunately the integration with other scripting languages still needs improving and it looks like these two issues haven't been addressed at all.

Friday, July 14, 2006

MMC RIP?

I never quite understood the point of Microsoft Management Console. It is a framework for building administration tools that allows end users to create their own admin environments by adding together as many 'snap-ins' as they like. But the cost of this is that any snap-ins have to fit into the MMC framework, which is fairly inflexible and forces an Explorer style interface on every snap-in. And who actually uses the customisation facilities provided? I certainly don't and have never seen a machine where the admin tools have been customised. So I was intrigued to see that the main admin tools in SQL Server 2005 are no longer MMC-based, they are just standard Windows applications (written in .NET methinks). So although Microsoft continue developing MMC (version 3 is coming out soon with support for .NET based snap-ins) it seems to me that the end may be nigh for MMC. As an aside, I helped develop an MMC snap-in for some software I worked on. Although they are generally pretty tricky to develop, Colin Wilson has written a great Delphi component set to help with the job if you really must develop one.

Friday, July 07, 2006

How to choose colours for a website

With my grade E in GCSE Art, my art skills have never been up to much. So my website colour choices have always been pretty ugly. I was therefore very pleased to find Colour Blender, which makes the choices for you.

Wednesday, July 05, 2006

Ajax.NET Professional

As always I'm late to the party, but I've finally got into some AJAX development. Since the project I'm working on is an ASP.NET 1.1 website, Atlas is no use to me, so I was pleased to find the free Ajax.NET toolkit. It makes development of AJAX based websites really simple. Add a line to web.config, add an attribute to a server-side method and then call it from client-side Javascript, it's that easy. The lovely thing about it is the way it copes with classes as well, my server-side method can return a class that can then be used in my client-side code. It may not actually be using magic but it sure feels like it.

Sunday, July 02, 2006

England suffer completely predictable World cup exit

It came as no great surprise to see England getting knocked out of the World Cup yesterday. As ever, the first time they had to play a decent team, they failed to progress. But what made this worse than previous efforts was that we appeared to have a squad capable of making a real challenge. Unfortunately our manager was clueless and decided to only bring 3 strikers (OK 4 if you count Walcott who Sven was clearly never going to select), 2 of whom were not fully fit. That meant when Owen was injured we were forced to play a formation that clearly didn't work. If we'd been able to play a more attacking formation, we might have got a goal that we could have protected when we went down to ten men. But with two strikers, Rooney would probably not have been so frustrated in the first place and might have been on the pitch for the whole match.

Friday, June 30, 2006

How to rescue a Delphi project

Delphi has been around a long time and there is a lot of Delphi code around but there aren't so many people around to work on it anymore. Developers are moving onto more modern technologies. To me it looks like the people who continue to maintain this code aren't always the most technically proficient so due to this and the fact that the code is getting long in the tooth means projects are becoming a bit of a mess. These days if I'm asked to look at some Delphi application, it is invariably in a bit of a bad state. So how to deal with this situation? How can these ill projects be rescued? These are the steps I've been taking with the latest bit of code I've been asked to look at. First up, I added all the source to source control. Without source control, you're doomed. There are plenty of source control products around, many of them free. I've been using SourceGear Vault, because it's free for a single user and does averything I need. Next, I attempted to compile the project. The main problem here was libraries I didn't have. Fortunately these were all available free, so I could compile it quite easily. Now it was time to see what the code was actually like. Unsurprisingly it was a bit of a mess. Compiling with hints and warnings on generated several hundred warnings and this was before I noticed somebody had put the {$WARNINGS OFF} compiler directive in several files... Warnings are there to help and can generally be fixed pretty easily, so don't hide them! Fixing these errors took some time but helped to learn about the code. I'd recommend removing all code that is never called and all commented out code, there is no point learning about code that is never actually called. And it's always recoverable from source control. Also searches through the project that throw up commented out code are generally pretty annoying. Another great tool for finding problems in Delphi code is Pascal Analyzer, which finds lots of things that the compiler will miss. Even the trial version has enough functionality to be useful. Reading the code can give you clues about a few things as well. Given that the developers of this code had a habit of leaving in lots of commented out code, my guess is they didn't use any source control. I'm also guessing they started work on this a long time ago, with lots of pointer based operations and references to WinTypes and WinProcs (which if I remember correctly was removed after Delphi 1). So this is where I'm at now. What I need to do now is take this Windows application and convert some parts of it into a web service. This is where it could get interesting...

Tuesday, June 20, 2006

What is System.RuntimeType?

I was trying to get the metadata for a query coming back from SQL Server. I'm not interested in the data, I just wanted to know what the columns were in a particular table. So I was executing a query like so - 'SELECT * FROM blah WHERE 1=0'. When I executed it, I took the DataReader returned and used GetName to get the names of the columns and GetFieldType to find out the types. Perhaps there is a better way to do this but I'm unaware of it. But weirdly, GetFieldType returned System.RuntimeType for every column. I thought WTF is that? A quick Google then a quick Yahoo and quick MSN didn't show up anything useful. The only thing I could find was the comments from the MS Rotor source which said

"RuntimeType is the basic Type object representing classes as found in the system. This type is never creatable by users, only by the system itself. The internal structure is known about by the runtime. __RuntimeXXX classes are created only once per object in the system and support == comparisions."

But this still wasn't much help. So I thought I'd have a hack around. The reason it isn't documented and doesn't show in many searches is because it's an internal class, which makes it a bit surprising I'm seeing at all. But it does have a useful property called UnderlyingSystemType that returns the type I'm interested in. Of course because it's internal I can't access that property. The way round this is via the best thing since sliced bread, reflection. So here is the litle snippet of code I came up with to do just that.
object val = reader.GetFieldType(index);
Type runtimeType = val.GetType();
PropertyInfo propInfo = runtimeType.GetProperty("UnderlyingSystemType");
Type type = (Type)propInfo.GetValue(val, null);

Update - As mentioned in the comments (only took me three years to respond!), this code is actually pointless. The thing I hadn't noticed is that RuntimeType inherits from Type, so although it isn't possible to deal with an instance of RuntimeType directly, you can just treat it as an instance of Type instead.

Sunday, June 18, 2006

The construction of a disco shed

Here are some photos of the construction of my disco shed. I'm very pleased with the final outcome and I learnt a few things on the way. First I discovered that air-raid shelters are very difficult to pull down, especially when the bolts are all rusted in. Cutting through them with a hacksaw takes a flipping long time. Then I learnt that laying a concrete slab is a pretty big job. When I calculated I needed 68 bags of ballast (which is sand mixed with gravel) I thought I'd made a mistake. In fact it turned out I actually needed more. A cement mixer was pretty much essential as well. Also, getting the base level is quite important. Mine is a little bit out so my chair rolls down the slope when I'm sat at my desk. Not so bad that I fly out the door, but if I'd made more of an effort to get the base exactly level I wouldn't have the problem.
Finally, a disco ball is absolutely essential for the modern disco shed...

Thursday, June 15, 2006

The story of an SL-1210

When I was 17, my main ambition in life was to own two Technics SL-1210s and be a world famous DJ. The SL-1210 is a design classic. It has been around in one form or another for over 30 years and it is built to last. Everything about it is industrial strength, except the tone arm which by its nature has to be pretty fragile. The most impressive thing is when you lift up the platter and there isn't any kind of belt, just what looks like a magnet and some coils. I think this was the first direct-drive record deck and although it has been imitated many times, the SL-1210 is still the de facto standard in the world of DJing. But this design comes at a cost. When I was looking to buy one, they cost £400. I scrimped and saved and finally got together the money. In fact I only paid £360, since I was paying in cash. But I only had one, which was pretty useless when you want to be a DJ. Which is where Ali comes in. Ali was a friend of mine at school. I don't remember when he told me he was HIV positive but it was pretty soon after meeting him. He was a haemophiliac and had contracted HIV from a contaminated clotting factor injection, before testing for HIV had begun. The government had compensated all those who had contracted HIV, so Ali was a well-off young man, though one with a potentially terminal illness. So Ali bought himself two Technics decks and even got them put in flight cases, for the professional DJ look. We weren't great friends at shool but we ended up at the same university (Newcastle) doing the same degree so ended up becoming good friends. We also started DJing together, after getting an amp and some very big speakers. We were a good pairing, he did bang bang dance music and I did Indie pop with some mainstream pop music. When I finished uni after four years, Ali had missed a year due to illness and was still trying to finish his degree off. He never got the chance to though. I last saw him during the Christmas holiday of '94. He was in bed and was unable to come out for Christmas drinks, but I presumed it would be another passing illness, like the ones in the past. But not long after he was dead. At his funeral, Ali's dad told me that Ali had left me his decks. After leaving uni, DJing had dried up, not least because Ali wasn't around to get the contacts, since he was always much more gregarious than me. But I obviously wasn't going to say no. So now I had three decks, which was too many even if I was still DJing. So I gave my SL-1210 to another of Ali's friends and kept the other two for myself. Time went on and the DJing thing was obviously never going to happen so I gave one of the decks to my brother Simon, with the proviso he didn't sell it on eBay. And the other one has been mostly been doing nothing but gather dust for the last ten years. CDs and MP3s have replaced records in my life. And now I have a shed and space to spare, so out has come the SL-1210. I cleaned it up and threw on one of my ten-year old records and the deck still works perfectly. So thank you Technics and thank you Ali.

Saturday, June 10, 2006

HTTPS and stupid error messages

Ever seen this dialog box appear in Internet Explorer? Chances are you have. And guess what, most people who see it don't have a clue what it means and just get scared that the website they are on isn't as secure as they thought it was. And know what else? It's wrong most of the time when it appears. It will appear when there is a standard link to a non-secure page. Yeh, the other page may not be secure but the user isn't looking at any content from that page. Since it will appear whenever there is a link to a non-secure page, it's very easy to accidentally add stuff to your page that will cause this to show up. I wonder how much time has been wasted by developers getting rid of this? And IE7 doesn't fix it either...

Wednesday, June 07, 2006

Server-side view state

There was a reason for adding the user-agent string to my ASP.NET error handling code, some errors are browser specific. One bug that has been biting me is view state getting corrupted. View state is a big chunk of base-64 encoded data that gets passed from the server to the browser in a hidden field. The browser does nothing with it (or at least it shouldn't) except pass it back to the server in a post-back. Unfortunately it seems some bug in FireFox causes the data to get corrupted for some of our pages which then causes our app to blow up when the data gets posted back. But more weirdly, there doesn't seem to be any mention of this bug when I Google for it. The conspiracy theorist in me thinks this may have something to do with the geek community not liking to say anything bad about FireFox, but it's more likely that this is is just a very uncommon bug. Anyhoo, there seems to be a pretty good fix for this. This article describes how to store view state server-side. Not only does this solve the problem, it also reduces page size quite dramatically. Of course the downside is that server memory usage is increased.

Monday, June 05, 2006

Handling errors in ASP.NET

It would be nice if my sites never crashed, but unfortunately they occasionally do. First off I don't want users to see the ugly ASP.NET error page, so I add this to web.config. <customErrors mode="RemoteOnly" defaultRedirect="error.html"> <error statusCode="404" redirect="index.aspx" /> </customErrors> I redirect to a HTML page, just in case ASP.NET is so ill it can't display an ASPX page (although whether it will be able to redirect at all is open to question). The exception to this is 404 errors which are redirected to the home page. The code below is what I use to handle unexpected errors. This is added into global.asax. Some people will say log errors to the event log but I prefer logging to the database because it's easier to configure. By default, the ASP.NET user can't write to the Application event log. You can set up your own event log, but again this requires some configuration. Most projects have a database back-end, so I just need to add another table. I also send out an email so if there is a serious problem, I get notified pretty quickly. Note, the error also includes the full URL so if a test server or development machine starts sending out error emails, it's clear it's not a real problem. You could also configure this from web.config. Update - Now logs more information about the error, such as the type of browser making the request and any session data. Any objects being stored in session data must have a sensible ToString() implementation
public static void LogError(string errorMessage)
{
// log error to database
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = ConfigurationSettings.AppSettings["connectionString"];
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Log VALUES (GETDATE(), @Error)";
command.Parameters.Add("@Error", errorMessage);
command.ExecuteNonQuery();
}
}

// send email
SmtpMail.Send("webserver@initech.com", "doogal@doogal.co.uk", 
"IniTech web server information", errorMessage);
}


protected void Application_Error(Object sender, EventArgs e)
{
// log exceptions
Exception ex = Server.GetLastError().GetBaseException();

StringBuilder errorMessage = new StringBuilder();
errorMessage.AppendFormat("An unexpected error occurred{0}", Environment.NewLine);
errorMessage.AppendFormat("Type: {0}{1}", ex.GetType().ToString(), Environment.NewLine);
errorMessage.AppendFormat("Source: {0}{1}", Request.Url.AbsoluteUri, Environment.NewLine);
errorMessage.AppendFormat("Message: {0}{1}", ex.Message, Environment.NewLine);
errorMessage.AppendFormat("Browser: {0}{1}", Request.UserAgent, Environment.NewLine);
errorMessage.AppendFormat("Stack trace: {0}{1}{2}", Environment.NewLine, ex.StackTrace, Environment.NewLine);
errorMessage.AppendFormat("Session data: {0}", Environment.NewLine);
foreach (string key in Session)
{
  string val = string.Empty;
  if (Session[key] != null)
    val = Session[key].ToString();
    
  errorMessage.AppendFormat("  {0}: {1}{2}", key, val, Environment.NewLine);
}

LogError(errorMessage.ToString());
}

Friday, June 02, 2006

Skype rocks

OK, so I'm about 12 months late but I've only just got round to using Skype on a regular basis and it's great. Most importantly it just works. I've had long conversations with people in the US and Australia and it drops out very rarely. Compared to my experiences with Yahoo Messenger (where conversations tended to consist of 'what was that?', 'you still there?', 'I'll call you again, see if it's any better', 'can you type out whatever you're trying to say', 'I give up, I'll call you on the landline') this is very pleasing. Any negatives? Sending files can sometimes be very slow (but this is still better than MSN which sometimes just refuses to accept files) and I can't seem to find a way to search through past chats. And it's written in Delphi, so perhaps there is life in the old dog yet.

Tuesday, May 30, 2006

DCOM from .NET

It's not well advertised but it is possible to use DCOM from .NET. It may not be as popular as the more recent RPC mechanisms but I still need to use it occasionally. So here's some C# code that should do the trick. The COM type library must be registered on the client machine. ComObject is the type of the COM object that you've imported into an interop assembly.
Type type = Type.GetTypeFromProgID(progId, serverName);
if (type == null)
throw new Exception("Unable to find the object, ensure the type library is registered");
Object objTest = Activator.CreateInstance(type);
ComObject comObject  = (ComObject)objTest;

Thursday, May 25, 2006

Apple finally gets it

Apple have always annoyed me. Many many years ago the original Mac was ahead of its time but slowly Windows caught up and eventually the old Mac OS was looking pretty dated. But still the Apple zealots would ramble on about how great Macs were. We had one of the original iMacs but it just wasn't very reliable, even though it looked quite photogenic. Which was another reason for not liking Macs. Even though 95% of the worlds' computers were Windows PCs, every film with a computer always had a Mac. I recently upgraded that old iMac to MacOS X and was quite impressed. Of course the problem was all the software I wanted to run was Windows software so it wasn't much use to me, so it is still languishing in the loft. But first Apple decided to switch to Intel processors (and seem to have admitted in the process that they are much better than the old PowerPC processors). Then they released software to allow Apple computers to run Windows XP, which solves the major problem for anybody coming from the Windows world. And now they've released a laptop costing as little as £749, which solves one of the other major problems with the Mac, the price premium. It's still there but it's much less than it used to be and I have to admit that if I do ever purchase a laptop, I will now consider an Apple. And that iMac in the loft will be moving into my new office very soon.

Sunday, May 21, 2006

A better link: search

I've known for some time that Google lies when I do a link: search to see which sites link to my sites. Even though I know of sites that link to mine, Google doesn't list them. So I was very pleased to discover that it's possible to use @: instead of link: and many more sites are listed, although it still doesn't show some sites I know link to mine.

Saturday, May 20, 2006

An alternative to Environment.NewLine

Looking through my logs is always an interesting way to find out how people end up at my blog. One of the most searched for terms is 'Environment.NewLine alternative'. I'm not entirely sure why that would bring you here but anyway, what alternatives are there to Environment.NewLine? On Windows, Environment.NewLine is simply "\r\n", so you could use that, which would save a few key presses possibly (which is the only reason I can think of for wanting to find an alternative). If you're one of the brave people trying to develop a cross-platform app with Mono, then Environment.NewLine will be "\r" on Linux and other Unix platforms. So depending on what you're trying to achieve you may want to go with Environment.NewLine anyway or you may want to hardcode your newlines to "\r\n" or "\r".

Friday, May 19, 2006

Not Google site: bug

So after looking more closely at what I thought was a bug with Google, it turns out it's not. site:http://www.randompubfinder.com/ returns only the pages in Google's main index, site:http://www.randompubfinder.com returns all pages, including supplemental results. What are supplemental results? Basically pages that might show up in search results if Google can't find anything better. So we now have 4 pages in the main index! Unsurprisingly our hits are way down, since most of our traffic is driven by Google. So why did this happen? It seems that Google now won't store all pages in the main index if your site isn't popular enough. By popular, I mean having lots of inbound links. We don't so we get the big heave-ho. Doing searches now that used to bring up links to us now actually shows less relevant results, so I'm not entirely convinced this is helping improve the user's experience. Somebody at Google has written a fairly lengthy article about the latest updates there, with lots of unhappy people leaving comments. Here's a blog post from somebody in a similar position to ourselves.

Wednesday, May 17, 2006

Weather Bonk

Bonk probably has a different meaning in the US, but other than the strange name, this website is pretty good. I think it's pushing AJAX and Google Maps to its limits, as moving around can get pretty slow, but it has all the weather info you could ever need along with links to webcams. And even better, you can plug it into your own website in about two minutes.

Google site: bug

So there I am panicking because the Random Pub Finder seems to be disappearing from Google and today it got worse. Only 58 pages in the Google index apparently. Then I looked at the search string, site:http://www.randompubfinder.com/ So I tried site:http://www.randompubfinder.com and there are 639 pages. Panic over. So it looks like Google has a bit of a bug in its search engine and in Google Sitemaps, which provides the first URL as a link to tell you how many of your pages are indexed.

Friday, May 12, 2006

SEO made easy

I think I've made a reasonable job of optimising the Random Pub Finder for search engines. Our average hits are over three times what they were before I did any SEO on the site. I've not done anything dodgy and it's cost nothing. At this point I could claim to be a genius or I could tell the truth and just admit to reading this book. There are plenty of guys out there who will do the SEO work for you (for a price), but it's probably cheaper just to read the book. The disclaimer at this point has to be that the rules for search engines are changing all the time, so this book may well be out of date already...

It's a small virtual world

This image shows where the hits to my main website are coming from. I'm blown away by the fact that my crappy little site can attract hits from so many places on earth. OK, people mostly come from the US and Europe, which I guess is due to the higher levels of internet connectivity in those areas, but I've managed to get hits from every continent (OK, if you want to be pedantic I probably haven't had any hits from Antartica but Google Analytics seems to ignore it so I don't know for sure). My guess is that when air travel becomes too expensive for the average man in the street (which will be pretty soon I reckon) this kind of virtual travel will be the best way to see what goes on in the rest of the world.

Thursday, May 11, 2006

The crazy world of Google

A few weeks ago the Random Pub Finder had over 600 pages indexed in Google, pretty much the whole site, then a week ago it was down to just over 200. Now its bounced back to over 300, but where are the other 300? Who knows. The site has hardly changed during that time so I don't think it's anything I've done. The more I learn about search engines, the less sense they make.

Saturday, May 06, 2006

Milton Keynes are relegated

Football isn't generally any kind of morality play, good things don't always happen to good people and vice versa. But it did today. The most disliked team in England were finally relegated to the 2nd division. Why are they disliked? They uprooted the club and moved it across the country to Milton Keynes from South West London. This may be a common occurrence in the US, but franchising of clubs here has never happened here in the past. Why do I care? If they had been successful then they may have been the first of many clubs moving just to get a few more bums on seats and to hell with the club's fans. Not only that, but the club set up by the fans, AFC Wimbledon, is ten minutes down the road from our house. Unfortunately they missed out on promotion this year, but they are still one division closer to their nemesis.

Monday, May 01, 2006

Pennine Lancashire

If you're of a certain age and were brought up in the North West of England, Tony Wilson was probably a big part of your formative years. Not only was he constantly on the local TV news, he also ran one of the coolest record labels of the time and owned the hippest nightclub. Well now he's going to try to help regenerate the rundown parts of East Lancashire. This part of the world is close to my heart and it certainly has some things going for it, it has beautiful scenery, it's very cheap to live there and, OK, I can't think of anything else. Tony certainly has a bit of a challenge on his hands. The towns around East Lancashire have never really recovered from the industrial decline in the latter half of the 20th century. I went to school in Blackburn and of the people I've remained in contact with, only one still lives in the area. My family have also all moved away, so it's no wonder there's a problem with negative equity. I went to a pretty decent school, so all my friends are well educated and probably just the kind of people the area needs to help regenerate it. But they've all moved to well-paid jobs in the South East (except for one friend who's moved to Lancaster, one part of Lancashire that does seem to be doing quite well for itself). That's the main problem Tony needs to solve, getting these kind of people moving back to their roots. Manchester and Liverpool managed to recover from their apparent terminal decline, so I'm sure it will be possible.

Friday, April 28, 2006

Is AdSense worth it?

I added AdSense ads to some of my websites as an experiment to see if it would be worthwhile adding them to the Random Pub Finder. I've now been signed up long enough to get a reasonable idea of how much money can be made. Based on my earnings, which may not be completely representative, you can get anywhere between $0.05 and $1.50 per click. But Google don't provide any information about which keywords provide the high-earning clicks, so it isn't possible to optimise your site based on that, which would be a pretty lame thing to do anyway. Earnings per 1000 pageviews seems to be about $5, so I'll never make a living based on it, but I might make a little bit of pocket money. So how many hits would you need to actually pack in the day job? OK, say you need to earn $6000 a month (which may be a bit high or low depending on where you live and your lifestyle) how many hits would you need? That works out at $200 a day, or 40,000 pageviews. My guess is you'd need to be running your own server to handle that kind of load (I'm sure any free host would throw you off their servers before you got to this level) so that's another expense. I've no idea how much that would cost but if you are getting that number of hits I'm guessing you also need support people to ensure your server is always alive (unless you want to provide the 24-hour support...) so add some more for that. Guy Kawasaki, who says he's in the Technorati top 100, also says he gets upto 1200 pageviews a day, so it certainly looks like it would be pretty hard to get near the 40,000 from blogging, doing IT writing at least. And more popular subjects lke the sex publishing industry seems pretty well covered already (so I hear). So in conclusion, I don't think ads are likely to finance mine or your lifestyle, but they could provide some useful extra cash. And are they worth it for the Random Pub Finder? Not until we get so large we get kicked off our free host. It's only a matter of time...

Tuesday, April 25, 2006

Diabolical dialogs

Apparently Windows Vista will have a whole slew of new dialog boxes for us to contend with. This is all in the name of security so perhaps there is some reason behind the apparent insanity, but us programmers have a bit of a soft spot for dialog boxes and our users don't. For a programmer, a dialog box is often the easy way out. What's the alternative? It depends on the scenario, but the typical situation where we would consider popping up a dialog is when the user is about to do something that could lead to some kind of data loss, so we throw up a dialog saying 'Are you sure?'. The alternative here is to have some kind of undo functionality and that can be pretty tricky to implement. So why don't users like dialogs? Because they interrupt workflow. The user is merrily going about their business when up pops a dialog and they have to think about the answer. After a while of course they learn to ignore the dialog and just hit the Enter key, which is another problem with dialogs that popup too frequently. They lose any effectiveness they initially had. Another problem occurs with multitasking. In one application I use, loading a document takes some time, so I open a file, then switch to some other application. When I flip back to the original application, there's a dialog asking a dumb question... So how do we get rid of them? First, remove any dialogs that serve no purpose at all. Examples of these are dialogs that merely say 'I've completed task X'. What is the user meant to do? Congratulate the computer? Next, find dialogs that 99% percent of the time serve no purpose, the 'Are you sure?' dialogs and just do what the user asked for but allow them to undo that action. Then look for dialogs that ask a question that invariably has the same answer. Add a checkbox that says 'Always do this and never ask me again'. You may decide that you want to provide a way of turning this back on, but have you ever needed to do it? I'd go even further at this point and suggest looking at any modal windows in your application and see if you can make them non-modal. Modal windows make user interaction more difficult, even though they make programmer's lives easier. If a user is likely to want to copy and paste between windows in your app, make sure they are non-modal so they have some chance of doing so. But I don't have an original bone in my body. All these ideas come from the great book 'About Face', that everybody should read.

Sunday, April 23, 2006

Serialization in Delphi

One of the few visitors to this site came here looking to learn how to do serialization in Delphi, so I thought I'd oblige. Fire up Delphi, create a new Windows Application project and add a button and a memo control to the form. In the event handler for the button, add some code as follows- procedure TForm1.Button1Click(Sender: TObject); var LStream : TMemoryStream; begin LStream := TMemoryStream.Create(); LStream.WriteComponent(Memo1); LStream.Position := 0; Memo1.Text := ''; LStream.ReadComponent(Memo1); LStream.Free; end; Now run it and hit the button and, er, nothing happens, which is exactly as it should be. This just shows that the memo control is getting serialized to the stream, the text in the memo is getting cleared, and then the memo is getting deserialized and the text is getting put back. And that is about all there is to it. To add a bit of excitement, add another button and another memo. Add the following code to the event handler for the new button- procedure TForm1.Button2Click(Sender: TObject); var LStream : TMemoryStream; LStringStream : TStringStream; begin LStream := TMemoryStream.Create(); LStream.WriteComponent(Memo1); LStream.Position := 0; LStringStream := TStringStream.Create(''); ObjectBinaryToText(LStream, LStringStream); Memo2.Text := LStringStream.DataString; end; By default, Delphi serializes objects in a binary format. The ObjectBinaryToText method converts it to a human-readable form and there is another method to go the other way. Recognize the text format? It's the same as Delphi uses for storing DFMs. The serialization support in Delphi was developed purely for the IDE, which is why it's only really a half-arsed implementation. The only properties that will be serialized are published ones, which will likely limit what you can do with it. Of course, there are all the problems with serialization you should consider before you start using it. There's a whole lot more to serialization than this, but I hope this has been a useful introduction.

Monday, April 17, 2006

What is wrong with visible instance fields? Part 2

My previous post about visible instance fields actually got a comment, which is my first ever proper comment, unless you count the ones from my brother. Not only that, it actually got commented on by a member of the FxCop team at Microsoft. Crikey! I think that lifts me up from being a Z-list blogger to what, a Y-list blogger perhaps. Anyhow, the comment was that although moving from a visible field to a property won't break source compatibility it will break binary compatibility, which is a fair point. You can see this if you look at the IL for setting a field value compared to setting a property (via our old friend Reflector). ldloc.0 ldc.i4.1 stfld int32 ConsoleApplication1.Thing::Field ldloc.0 ldc.i4.1 callvirt instance ConsoleApplication1.Thing::set_Property(int32) So in some ways it will also break source compatibility if someone is using you class library from an IL application, if there are such crazy people around. But I think this does highlight a problem with FxCop. It was originally designed to help the .NET Framework team find problems in their code. But the kind of problems they need to worry about are not the same as what most programmers need to worry about. Mostly I don't care about binary compatibility, although I can see there will be companies doing component development who do need to care about it. Yes, I can turn off warnings that aren't of interest, but there are so many warnings in there, it's pretty overwhelming to even know where to begin. Perhaps I'm asking too much, after all FxCop was designed for people writing class libraries, but the fact it now ships with Visual Studio 2005, suggests Microsoft are now thinking application developers should be using it as well. If MS do think this, then I think they need to start thinking about having some different modes of operation in there for different use cases. As an example, it would be great to throw an application (ASP.NET or WinForms) at it and it to tell me which public code never gets called. It doesn't do this now, because it doesn't know who's going to be using the assemblies, but if the assemblies aren't shared with other applications then it should be able to work it out. Now, that would be cool...

Saturday, April 15, 2006

The fear

When programmers start out they are like small children, they have no awareness of danger. So they just go ahead and hack code, with no thoughts for the consequences. It's only after a few late nights caused by introducing serious bugs due to a one line change for some minor cosmetic problem that programmers develop the fear. The fear is a good thing, it helps us programmers to spot potentially dangerous changes to code and try our best to reduce the risk of breaking things. But there are two main ways that programmers (and managers for that matter) will deal with the fear. The first approach is to try to limit the amount of code change. If they are fixing a bug in an area they are unfamiliar with, they'll try to find the smallest amount of code they can change that fixes the problem, so rather than try to understand what the code is trying to do, they'll just shove in something that fixes the problem for this specific case and move on. This approach has some merits, there is certainly a link between the number of lines of code changed and the chance of new bugs being introduced but it doesn't solve the underlying problem, that the programmer doesn't understand what the code does. If they did, the fear wouldn't be so bad and they'd likely fix it properly. In the short term, that bit of code probably just got even more difficult to maintain. In the longer term, areas of the product can become no go areas that haven't been touched for years and nobody understands anymore. But they work mostly so that's OK, until a new feature needs to be added. At which point, the developers will turn round and say "we need to rewrite it all because it's such a mess". So how else can we deal with the fear? What you need to do is get into a place where the fear holds no, er, fear. It starts off simply enough, get some source control in place. If you haven't got source control, you're pretty much screwed, unless you're working on the next 'hello world' app. It's a great thing to be able to check out some code, hack it around, then if it doesn't work out go back to what you had before. Or two weeks down the line, when you realise that the bug fix wasn't such a big success, you can rollback to something that's more sensible. Check in regularly, like twice a day, not every two months. There are lots of other things to help reduce the fear. If it's code you don't understand too well, try to work out what's going on, do a bit of refactoring, try adding some unit tests, throw FxCop at it (or in the Delphi world Pascal Analyzer), adopt some agile methods, get a QA team. The tools are out there, so lose the fear.

Thursday, April 13, 2006

What is wrong with visible instance fields?

FxCop rocks, in a kind of hectoring school teacher kind of way. It complains about loads of things that are only relevant if you happen to be developing a class library that will be used by 3 million developers using every conceivable .NET language and in every human language known to man. But us mere mortals are mainly developing code that might get dumped onto one web server if we're lucky. But FxCop still helps out on stupid things like code that never gets called and visible instance fields. Except, what's wrong with visible instance fields? OK, making fields public that users of your class never need to access is pretty dumb, but how does a public field differ from a property with simple getters and setters? The FxCop help says "the code in a property's accessors can change as the type's features expand without introducing breaking changes." But if I need to change a public field to a property, how will this cause a breaking change? Fields and properties are used in exactly the same way by client code. The only explanation I can think of is that it may cause serialization code to break, but serialization code breaks all the time anyway so that doesn't seem particularly relevant. Saying all that, I'm still going to continue to use properties, if only to stop FxCop complaining.

Sunday, April 09, 2006

Another tech bubble?

In the late 90s, things went a little crazy. We had websites popping up here, there and everywhere that allowed us to do lots of exciting things, mostly for free. It turned out that this kind of business model wasn't generally very successful so most of these sites went bust. At the time, being an IT professional was pretty good, since the job market was red hot. Then suddenly in 2000, it all went tits up. So here we are in 2006 and the job market is moving very quickly upwards,lots of new websites are popping up doing lots of exciting things, mostly for free, many with a business model that seems to entail nothing more than ad revenue, or value added services. So is this another bubble or is this different? It seems to me the key here is the growing online ad business which is doing very well at the moment. It seems slightly crazy to me that I can get paid $1.50 just because someone clicks on a link on my site (and the advertiser is paying even more). If that stream of revenue stops or severely reduces, a lot of these new web businesses might start having problems I reckon.

Saturday, April 08, 2006

Virgin Wines are spammers

I can't remember how it all started. I think I entered some competition that offered the chance to win some free wine (how could I refuse?) and Virgin Wines got hold of my email address. Soon I was getting an email every week or so exhorting me to purchase a case of wine. I've no idea whether Virgin Wines provide decent wine or not, but the fact I've got a Majestic Wines about five minutes away means I wasn't tempted to purchase anything from them, so I sent an email to unsubscribe@virginwines.com (after all they are reputable company, right?). Then, nothing. the emails kept coming. So I sent another. And the emails still didn't stop. Then I got an email from the founder of Virgin Wines, not apologizing but offering me more wine to buy. So I replied directly to him telling him his unsubscribe functionality didn't work. I then got an email from Customer Services saying "Thank you for contacting Virgin Wines and we have arranged for the email address you have provided to be removed from our mailing list which will be actioned within the next few days.". So that was the end of it? Well, no. I then received what looked like a personal email from the founder saying "Dear Christopher I thought that, as we were warning our staff not to lose out on last weeks free case offer, we should do the same for you!Please don't hang about - when the free cases are gone, they are gone! Go to www.virginwines.com/reminder9 Cheers, Rowan Gormley Founder Virgin Wines" I presumed I was actually being offered some free wine at this point, perhaps as an apology for all the emails. But looking at the offer showed it was just another attempt to get me signed up to Virgin Wines. OK, I'd get a free case but only if I bought another case... OK, the price looks pretty reasonable, coming to just over £3 a bottle, but my corner shop does a nice red at £10 for 3 bottles. Then today I got yet another email offering me more wine at bargain prices. Frankly I don't care how good Virgin Wines are, they are spammers, so I will not be buying any wine from them, ever. And perhaps their PR department will see this and realise their mistake. Or they'll sue me...

Thursday, April 06, 2006

Nobody has ever needed to do this before

So I'm still trawling through this ASP.NET app and keep finding great WTFs. I spotted this method in one of the classes
private ArrayList SplitString(string str, string separator)

So presumably the writer of this piece of code assumed nobody had ever faced a similar problem before and might have provided a solution in the framework???? Anyway, that's some more redundancy I can get rid of.

Monday, April 03, 2006

The copy and paste anti-pattern

I've just picked up somebody else's ASP.NET 1.1 application and like probably every developer who's picked up somebody else's code, I think it's crap. The thing that worries me most is how hard it is to create a new page. I create a new web form and then I have to copy and paste the markup form another page. Then I need to go through and add a bit of code to the code behind file. ASP.NET provides lots of mechanisms to avoid having to do this (as does pretty much every other web development platform). We have page inheritance, so common code can be put in a parent class. We have user controls, so bits of repeated HTML can be put in them. OK, a bit of setting up of a new page may well be necessary but copying and pasting, whether markup or code, is a very bad sign. When the change request comes through (as it always does) to redesign the whole site, if every single file needs to be modified, life will be very painful.

Wednesday, March 29, 2006

For sale: Several IDEs, one careful owner

Who will buy Borland's IDE products? My guess is no-one, certainly nobody who's actually interested in the IDE business. Somebody who wants some talented programmers perhaps but why would anyone in their right mind get into the IDE business. Delphi is a great product but it has some serious competition from Visual Studio, which is a loss leader for Microsoft. MS owns .NET and wants everybody to use it and doesn't much care if it makes money on its IDEs. Visual Studio Express is free and is probably good enough for quite a few people. Look at the figures in the UK for Delphi and C# jobs, Delphi is on life support. It is still the best development tool for native Windows desktop applications, but how big is that niche and how fast will it disappear? The other tool that may be of interest to buyers is JBuilder but that is losing out big time to Eclipse, because it's free and good enough. So good luck Borland and good luck Delphi, it was fun...

Friday, March 24, 2006

Beware the ribbon

Jensen Harris has convinced me that the new Office user interface will be lightyears ahead of the current one. But I'm going to make a prediction. I reckon soon we'll see almost every new Windows application adopting the new ribbon UI. But you need to remember that the ribbon has been created to solve a particular problem that Office suffers from. It has hundreds if not thousands of different commands. The average application doesn't have that many and the traditional menu and toolbar is still sufficient. So please spend your time fixing bugs and adding new features rather than adopting a new UI that you don't need.

Tuesday, March 21, 2006

Formatting C# code for a blog

This C# code formatter does the business. Much better than the manual fiddling I was doing before.

Creating thumbnails in ASP.NET

.NET makes some things really easy and creating thumbnail images for a website is one of them. Here's the code I'm using on one of my websites.
 private void CreateThumbnail(string fileName)
 {
   string physicalThumbFileName =
     Path.GetDirectoryName(Page.Request.PhysicalPath) +
     "\\images\\" + fileName + "_thumb.jpg";
   if (!File.Exists(physicalThumbFileName))
   {
     // create thumbnail
     using (Bitmap img = new Bitmap(ImageFileName(fileName)))
     {
       using (Bitmap smaller = new Bitmap(img,
         new Size((img.Width*120)/img.Height, 120)))
       {
         smaller.Save(physicalThumbFileName, ImageFormat.Jpeg);
       }
     }
   }
 }
The thumbnails are created when the page needs them, thus simplifying the upload process, since there's no need for any manual thumbnail creation.

Thursday, March 16, 2006

SEO works, but it shouldn't

It all started about two or three months ago. I got into an email conversation with the webmaster of a website doing a very similar site to the Random Pub Finder. He claimed to be getting about three times as many hits as we were. After looking at his site, I thought the site (to my eyes at least) was no better than ours (and I'm not talking about Beer In The Evening which is clearly better) so I couldn't work out why this was. After talking to a couple of SEO gurus I started making a few changes to the site and over the last couple of weeks or so, we've started to increase our hits. In fact, we are now getting about the same number of hits as he was claiming to get. Now this may not be entirely due to my changes, the search engine algorithms may have changed along with a whole host of other things. But if it is down to the SEO changes, then the search engines have a lot of work to do to optimise their search algorithms. For instance, why should putting the title of the page in a h1 tag make a difference? Surely the search engines should be clever enough to realise any old tag (a div for instance) with the correct style applied will look just the same. Why should h1 be considered as special? So search engines still have a lot to learn. People who put content on the web shouldn't need to know the special magic they need to apply to their pages to get attention. Until SEO gurus are no longer required, search engines will not have perfected their art...

Friday, March 10, 2006

The Road To Guantanamo

I've always followed the career of film director Michael Winterbottom since he went to the same school as me. He directed the great '24 Hour Party People', chronicling the coolest record label of my teeenage years. He also did '9 Songs', the most sexually explicit film to get a certificate in this country, a record that I'm sure will be highlighted in the school's old boys' magazine... Anyway, I saw his latest, 'The Road To Guantanamo', last night and it was great, in a horrendously depressing kind of way. Yes, the 11th of September attacks were horrific but can that excuse the kind of treatment that was handed out to these people (and is still being handed out to the 500 people still there). We protect our democracy by ignoring all the rights that democracy confers on people? Of course it can be said that the film isn't entirely objective, based as it is on the accounts of the inmates. But since the US doesn't seem too keen on letting anybody else in there to see what's really going on, it's all we've got. Required viewing for anybody who still thinks Bush's war on trrrr is worthwhile.

There's a reason they are called exceptions

Whenever you read about exceptions, one of the key points is that exceptions should only be thrown in exceptional circumstances. An example might be when a file the application can't survive without doesn't exist. However I've seen on several occassions now exceptions being used where the particular problem could be expected to happen on a fairly regular basis, if not every time the application runs. A common example can be found when trying to convert a string to an int. In .NET 1.1, int doesn't have a TryParse method so a quick and dirty approach to implementing similar functionality might be as shown here
int val = 0;
try
{
  val = int.Parse(stringVal);
}
catch (FormatException)
{
}
This solution can be fine when stringVal will generally be a valid int, but if it's used when stringVal is often not a valid int (when reading the value from a config file that by default doesn't contain any value for instance), it can become annoying. Why's that then I hear you cry? Just turn off breaking into the debugger when an exception is thrown and all is well. Well perhaps but I always want to break into the debugger when an exception is thrown. Why not just break into the debugger for unhandled exceptions? Because my applications have a global exception handler to do logging etc when an unexpected exception is thrown. So turning off breaking into the debugger when an exception is thrown means I never break into the debugger for any exceptions, which is less than ideal. When developers follow this pattern too often, it can actually become increasingly difficult to ever break into the debugger when an exception is thrown. The IDE option can be become impossible to switch on because the developer is thrown back into the IDE so often. When this happens, we've lost a very useful tool and our debugging becomes much more difficult. Having the option always switched on means we are more likely to find those obscure bugs that only happen once in a blue moon. Another point to make is that this kind of exception handling can affect not only the developers working on your project but developers working on something completely different. I've been working on an ASP.NET project that requires me to run another ASP.NET project at the same time. This other project uses a very similar technique as that shown above which constantly throws me back into the debugger when I'm working on my own project! So how to solve the problem? In the case of the code above, there are probably several solutions, although they will all require some work. Checking for an empty string often solves the problem in 90% of cases, whilst doing some kind of check of the characters in the string would cover the other cases. For most other scenarios where an exception will be thrown, there is almost always a different implementation approach that does not require exceptions.

Wednesday, March 08, 2006

The Doogal Effect

No, no, no, not the effect I have on people, but rather how the release of the film 'Doogal' (based on the drug-fueled children's programme 'The Magic Roundabout') has affected the hits to my home page http://www.doogal.co.uk. See that spike? That was the weekend it was released in the US. And it looks to me that it hasn't been too successful since my hits are already back to normal...

Friday, March 03, 2006

Does PageRank matter?

For some reason, the Random Pub Finder has now got a PageRank of zero. I'm not entirely sure what we've done to upset our lords and masters, but it doesn't seem to be having a negative effect on the number of visitors we are attracting. In fact, visitors are up and most of them are arriving from Google. So I won't take it personally...

The IT Crowd

Written by the same bloke who wrote 'Father Ted', starring Chris Morris and being about IT people, how could 'The IT Crowd' fail to deliver? Well it was reasonably amusing but was never quite the sum of its parts. I think the basic problem was that to hit the mark it would need to make techy jokes that would be lost on the general population. So the fact it is about IT people is kind of irrelevant, it's just another bunch of misfits in an on office sitcom. Saying that, I watched every episode, which is unusual since I don't really watch the telly anymore (unless you count CBeebies). The ending suggested there'll be another series, so perhaps that will allow the characters to grow somewhat.