harriyott.com

Friday, June 20, 2008

Extension methods in C#

I recently needed to encrypt a string with MD5 encryption. Not having used this before, I looked at the MSDN page for the MD5 class. There was a ComputeHash method, but no overload took a string parameter - just a stream or a byte array.

I may be naive, but I would have thought encrypting a string would be a common enough task to warrant its own overload, but apparently not. It is common enough though, for some example code that converts the string to a byte array, calls ComputeHash, and converts the result to a hex string. This example seems to work fine, so I don't know why it isn't just squished into the class in the framework.

Not wanting to just add this example to the class I was working on, I thought I would write my first ever extension method, and add the example as an overload to the MD5 framework class. I read about extension methods in the marvelous Pro C# 2008 and the .NET 3.5 Plaform, which are straightforward, but the syntax is a little unintuitive:

public static class MD5Extensions
{
public static string ComputeHash(this MD5 md5, string input)
{
byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
}


In short, both the class and the method should be defined as static, and the first parameter has "this" before the type, which is the class that is being extended. I'm going to have to keep looking this up, as there are three things to remember. I would have preferred a new keyword, extended, which works in the same way as partial classes, like so:
public extended class MD5
{
public string ComputeHash(string input)
{
...
}
}


This would have been far easier to remember, and would actually look like the programmer's intention. I'm sure there must be a good reason for the way it has been done though.

Monday, June 02, 2008

Re-inventing the toll

One of the side-effects of being a developer is that I often find myself "debugging" things outside of the IDE, or the computer itself. Recently I went somewhere that involved driving across the Dartford crossing on the M25*. There's a tunnel under the River Thames for northbound traffic, and a huge bridge for southbound traffic. There are toll gates for both directions south of the river.

As I was in a long, southbound queue (caused by the toll) on my return journey, I started thinking about why there were two tolls in operation at the same time, and two resultant traffic jams, and what to do about it. I think I've come up with a way to ease the jams.

The obvious first choice is to dispense with the tolls altogether, since the bridge paid for itself in 2003. The government aren't going to do that though.

I reckon that almost everyone that uses the bridge in one direction uses it again in the opposite direction very shortly afterwards. In my case, it was about 7 hours after. Very few people make journeys from their home or place of work and don't return via the same route in the opposite direction.

On my journey, I had two toll transactions, of £1 each way. I think it would be better to have one transaction of £2 instead, that would cover both journeys. In this way, one set of tolls could be closed, and allow traffic to flow freely through, removing one traffic jam altogether.

Depending on the traffic flow, the tolls could be changed over to reduce an extremely long tailback. If this happened in the middle of the day, then some people may have to pay twice, and others nothing at all. Although this doesn't sound fair, it should even out over time.

Should I suggest this to Boris, or is it a silly idea?

* Actually, it isn't the M25 at the crossing, it's the A282. I presume this is so that learner drivers can cross the river without going into town, as they're not allowed on motorways.

NxtGenUG FEST08

Dave McMahon has asked me to let you know about FEST08. In his words:

"FEST08 the annual NxtGenUG one-day event takes place ar Microsoft Reading on Thursday 12th June. As ever it's going to be an action packed day with great content from the likes of Mike Taulty ,Oliver Sturm , Dave Sussman and other top speakers. No doubt there will be bundles of 'swag' and prizes and Pizza somewhere down the line - there always is when the nxtGenUG Boyz are around. There seems to be a few more of them this year with the Cambridge and Southampton crews joining in the mix.

So got to http://www.nxtgenug.net/fest08/ for details and to register your place. It's free to all NxtGenUG members and a mere £49.99 to non-members - bargain! Oh and also if you're around the night before there is a G(r)eek dinner to toast Daniel Moth on his way to the states. http://www.nxtgenug.net/ViewEvent.aspx?EventID=140 is the link to signup to."

Friday, May 23, 2008

Converting SVG images to PNG in C#

I've been dynamically generating SVG images for the intranet I'm working on. I initially chose SVG, as it's an XML format, which is easy to manipulate in C#. I've started with the template picture, and added elements based on the data pulled from the database. These elements are lines and text, positioned according to the data.

There have been two minor problems so far. Firstly, although FireFox displays SVG files beautifully, IE just shows the XML. No biggie, as there's only a few users, and I can tell them to use FireFox (a pragmatic bug fix!). The other problem is that one of the users wants to copy and paste the image into PowerPoint. With a BMP, JPEG or PNG image, the context menu has a copy option that just isn't there with SVG, so there's no simple way to get it into PowerPoint. Time to bite the bullet (whatever that means) and convert the image to PNG.

I decided not to convert my code to use the System.Drawing to generate PNGs from the database data, as I'd already solved that problem. Surely conversion would be easier...

The obvious first step is to Google for a free SVG to PNG library, or example code on CodePlex or something, but I couldn't see anything amongst the noise of shareware apps that did conversions through a GUI. I did however, find mention of inkscape's command line interface. Inkscape is an open source SVG editor, which I used to create the image template.

I tried it out, and it was really quick, and the resultant PNG file was indistinguishable (that's a longer word than it sounds) from the original. Now to call it from the .ashx. This was quite simple, but I'll put the code here for any future Googlers (and there'll be some, there always is. If it's you, then hello and welcome. You're the reason I wrote this post). First, the "spec":
  1. Write the SVG file to disk
  2. Start inkscape as a process with the correct parameters
  3. Send the PNG file back to the browser


Now the code:

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/png";

String svgXml = GetSvgImageXml(context);
string svgFileName = GetSvgFileName(context);
using (StreamWriter writer = new StreamWriter(svgFileName, false))
{
writer.Write(svgXml);
}

string pngFileName = GetPngFileName(context);

string inkscapeArgs =
"-f " + svgFileName + " -e \"" +
context.Server.MapPath(PngRelativeDirectory) + "\\" +
pngFileName + "\"";

Process inkscape = Process.Start(
new ProcessStartInfo(
"C:\\program files\\inkscape\\inkscape.exe",
inkscapeArgs));
inkscape.WaitForExit(3000);
context.Server.Transfer(PngRelativeDirectory + pngFileName);
}


There's only one drawback that I can see, and that's having to install inkscape on the server. It's fine for me and my intranet, but may not be possible on hosted servers.

Saturday, April 26, 2008

Dell has a screw loose

A friend of mine has a new computer, her very first, and she asked me to set it up for her. I plugged everything in, switched it on, and got a black screen with some hardwareish words on it. It looked like it hadn't booted properly, so I wondered if something had come adrift in transit.

As I tilted the computer ready to open it, there was a gentle "clonk" noise from within. Once I'd opened the case, I saw that the hard drive was connected by only one of its two cables, hence the boot failure. I also saw that the hard drive wasn't attached to anything, and was completely out of its bay and resting on the motherboard.

This was rather surprising, as it should have been screwed into the case. I checked inside the case, but there were no screws rattling around. Not that they could have come off, as the screw-holes in the bay were covered by the side of the case. No, the screws were quite simply never there in the first place. All 4 of them.

Fortunately, my friend's mum had given her a really old Dell (Pentium III old), which was unused in a cupboard and about to go to the tip. I opened it up, and eventually found 4 screws that fitted the hard drive. I attached the hard drive into the new PC, connected the cables and it all works fine.

The question remains though, how on earth can Dell fail on something so basic? Not being into hardware, I don't know whether a minimum-wage worker forgot to screw it in, or the robot's screw pot was empty, but either way, I would have expected better from Dell.

[Tags: ]

Wednesday, April 23, 2008

Geek Dinner with Mike Hadlow

Many thanks to Mike Hadlow, who gave an excellent presentation with code samples about inversion of control containers tonight. A link to the source code for the examples will appear on his blog soon.

Good to meet a few new people too, and catch up with various people I haven't seen for a while.

Friday, April 18, 2008

Working in Uckfield

Despite my enthusiasm for co-werking in Brighton, I have a problem. I live in Uckfield. Not that it's a problem in general; I love being near the country-side, being able to afford a house, and seeing someone I know every time I go into town. Uckfield is a small town, and contrasts greatly with Brighton.

Brighton has free wi-fi along the seafront, and in lots of cafés, bars and restaurants. Brighton has lots of web agencies, software companies, financial institutions and a thriving tech community.

Uckfield is somewhat different. There are very few tech companies in Uckfield. Apart from one or two geek dinners that I organised a while back, there is no tech community in Uckfield. Just like with clothes shopping, you'd have to go to Brighton for that. I've tried working in various catering establishments in Uckfield, but they're not that geared up for it.

Here's a quick run down on what Uckfield has to offer the mobile worker:

  • Vespa. The only place in Uckfield with free wi-fi. Despite this, I've been there only once. MTV was on quite loud, playing music I didn't like. It closes at 4pm, which means I had to find somewhere else to go. The coffee was fine, but I didn't feel that comfortable there.
  • The Coffee House. Opposite Vespa, but not near enough to filch their wi-fi. I've met Heath, the guy in charge, only twice, but already he feels like a friend. Very friendly and welcoming. There aren't many tables, and the chairs are rather uncomfortable for working at though.
  • Costa. The nicest interior by far, and I like the coffee. I asked about wi-fi, and they said they're always asked, but apparently the owner isn't that bothered about it. They might put it in and charge for it one day. I did manage to connect to someone else's unsecured network sitting in the front of the shop though.
  • Luna. Being a restaurant, it's open after the cafés close, so I'll head there if I'm working late. I'm always made to feel welcome, although it is disconcerting sitting near couples out for a romantic meal (I'm sure they're less than delighted too). Although it advertises wi-fi on the sandwich board outside, it hasn't been working for yonks.


There are a few other places to try, but they look even less promising than these. Even though it takes an hour to get to Brighton in rush hour, it's still a good alternative. Clearly there's no mention of co-working in Uckfield (although I can use a window-less room in our church office), so I'm hoping that The Source will be a good option when it opens soon.

Shared Office Space

For the last 3 months or so, I've been working from home, and I've loved it. The flexibility, the commute, and the better family life are huge advantages, but the biggest disadvantage, for me anyway, is the loss of office life. I'm working in my spare room, which is small, contains a bed, an open wardrobe and a small table and chair. It needs painting, and the sun shines in mercilessly, so I have to close the curtains. Some days I don't leave the house, and other days I may not see my family until the afternoon. After a couple of months, the novelty started wearing off, and despite the advantages, I was feeling lonely.

As I'm now getting into twitter, I twittered my loneliness, for no other reason than I fancied telling anyone who would listen. I was surprised when @richardvahrman replied, generously offering me a desk in his office. I spent the next day in a lovely office in Hove overlooking the sea, and had a very productive time. There were 5 of us working in the office, and nobody working for the same company (the others rent desk space from Richard). It seemed like good old office life again, with long periods of companionable, busy silence, interspersed with the occasional techy discussion or general banter.

I was also invited to The Werks, also in Hove, so I went along a week or so later. The Werks is just brilliant. It's a co-working office, where people turn up and work. (Generally it seems to be people like me who work with laptops, rather than people who work with pneumatic drills.) I turned up quite early, and I was the only one there, so I just plugged my laptop in, connected to the wi-fi and got to work. Before long, a couple more people turned up, some who I knew from various Brighton geek events, and some strangers. We all sat round the same table, busying away, with the occasional chat, and sharing advice when appropriate. Again, a really productive environment, as it felt like being at work, as opposed to being at home. I've been back once since, and it was just as good.

There are a few different ways of doing it, which are priced accordingly. Occasional use (couple of times a month) is free (with contributions welcome), 2-3 days a week costs £60p/m, which seems very reasonable. So let's say that's 12 days a month, that makes it a fiver per day. An excellent alternative to renting an office. It's possible to rent a fixed desk and move in too, so there's a good mix of people there.

Thursday, March 27, 2008

Sussex Geek Dinner

After a break of 9 months (with the exception of the joint Christmas geek dinner with the girls), I'm glad to say that I've arranged another Sussex geek dinner.

This time, Mike Hadlow will be speaking on "Alternative Architectures: Inversion of Control". In Mike's words:

"I'm going to talk about how to write software, specifically .NET, as a collection of components using a design pattern called 'inversion of control'. It'll include a little bit about why it's good to do this and I'll also show you an eCommerce web site built with these techniques."


It's on 23rd April 2008 at 8pm, at the Black Horse, Church St, Brighton, and you can sign up on upcoming.org.

For a couple of years, I used a subdomain of geekdinner.co.uk to arrange the geek dinners, but the server crashed, and it isn't back up again yet. After initial concern, I decided to use existing social networks to publicise events, so there's now a Facebook group, a LinkedIn group, an upcoming.org group and a Google groups group. Hopefully that should cover everyone.

Wednesday, February 27, 2008

Pulling data from Excel

I spent much of today pulling data from Excel to put into SQL Server tables. The data was pretty well formatted, but each row of spreadsheet data traverses many database tables.

I saved the spreadsheet to CSV, and then used my trusty friend, the world's simplest code generator (javascript edition), to generate SQL statements from the many rows of CSV which I pasted into SQL Manager, e.g.

INSERT INTO People (FirstName, LastName) VALUES ('$2', '$3')

Some of them became quite convoluted, as once I'd inserted rows into the People table, I had to look up the IDs for the link tables. Also, there were a couple of Irish names with apostrophes in them, so I used a regular expression to double them up:

~(:Wh)'~([,|:Wh]|\))

n.b. I think this is a Visual Studio style regex, as it seems a little different to what I vaguely remember (not that I do remember, that is).

Tip - using units of measure

When naming a variable or database column that is used to store a measure, include the units of measure in the name. For example, instead of calling a column Height, call it HeightInInches. This prevents misunderstandings in future maintenance.

Friday, February 22, 2008

Lines of code != running time

I've just realised I do a bizarre thing in my subconscious when I'm coding. Now I'm all .NET 3.5, I've been writing code like:

feeds.ForEach(f => ProcessFeed(f));

One line of code instead of the usual four (OK, so two lines were the curly brackets) to write a foreach loop.

Now the thing is, I've unwittingly felt like the code now runs faster because the method is shorter. Of course that isn't true, but having nicer, shorter, eleganter, maintainabler code feels like it should be more efficient too.