Wednesday, April 15, 2009

Australian Postcode Validation

I was recently porting and updating some old Pascal postcode validation to C# and thought i'd stick it up here.

To tell the truth, the Pascal code is more concise. Pascal, VB, Ruby etc have means to test a range of values in a single case statement. Unfortunately C# doesn't provide for this contingency, hence the "fall through's" in the case blocks.

Anyway, maybe someone might find this useful as there are a few "interesting" situations with the ACT and NSW.



 1     public static string GetState(string postCode) {
 2       if (!IsValidPostCodeFormat(postCode))
 3         return "";
 4
 5       switch (postCode[0]) {
 6         case '5': return "SA";             // SA:  5000-5999
 7         case '3':
 8         case '8': return "VIC";            // VIC: 3000-3999, 8000-8999
 9         case '4':
10         case '9': return "QLD";            // QLD: 4000-4999, 9000-9999
11         case '6': return "WA";             // WA:  6000-6999
12         case '7': return "TAS";            // TAS: 7000-7999
13         case '1': return "NSW";            // NSW: 1000-1999
14
15         case '0':
16           switch (postCode[1]) {
17             case '8':
18             case '9': return "NT";         // NT:  0800-0999
19             case '2': return "ACT";        // ACT: 0200-0299
20             default: return "";
21           }
22
23         case '2':
24           int tmp = Int32.Parse(postCode);
25           if ((tmp >= 2600 && tmp <= 2618) || (tmp >= 2900 && tmp <= 2920))
26             return "ACT";                  // ACT: 2600-2618, 2900-2920
27           else if ((tmp >= 2000 && tmp <= 2599) || (tmp >= 2619 && tmp <= 2898)
28                                                 || (tmp >= 2921 && tmp <= 2999))
29             return "NSW";                  // NSW: 2000-2599, 2619-2898, 2921-2999
30           else return "";
31
32         default: return "";
33       }
34     }
35
36     private static bool IsValidPostCodeFormat(string postCode) {
37       int tmp;
38       if (String.IsNullOrEmpty(postCode) || postCode.Length != 4 
39                                          || !Int32.TryParse(postCode, out tmp))
40         return false;
41
42       return true;
43     }
44




Monday, December 29, 2008

System.RunTime.Serialization.SerializationException: The input stream is not a valid binary format. The starting contents (in bytes) are: 3C-68-74-6D-

System.RunTime.Serialization.SerializationException: The input stream is not a valid binary format. The starting contents (in bytes) are: 3C-68-74-6D-6C-3E-0D-0A-20-20-20-20-3C-68-65-61-64 ...

This is the Remoting exception IIS was consistently giving me after a deep search. The search was returning some mammoth blob's and failing after a few minutes.

I thought it might be an IIS error, sure enough after firing up TCPTrace and sniffing around, I found


HTTP/1.1 100 Continue
Server: ASP.NET Development Server/9.0.0.0
Date: Sun, 28 Dec 2008 23:52:31 GMT
Content-Length: 0

HTTP/1.1 500 Internal Server Error
Server: ASP.NET Development Server/9.0.0.0
Date: Sun, 28 Dec 2008 23:54:35 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 2549
Connection: Close

--snip html
Request timed out.
--snip html

So rather than throwing a relevant HTTP response code, we get a html error page that can't be serialized. Hopefully this saves fellow insane technologists a little time.

Wednesday, September 24, 2008

Returning lambda's from a ternary in C#

In the midst of some mad refactoring I came across something similar to the following snippet:

 1 if (count == 0)
 2   choice.Finish = result => { return; };
 3 else
 4   choice.Finish = result => { letter.MailMerge(result); };

Looked like a decent candidate for refactoring with a ternary / conditional operator:

 7 choice.Finish = (count == 0) ? result => { return; }
 8                              : result => { letter.MailMerge(result); };

Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

Hold your horses, say what?

For some reason the only way to fool it through the compiler is to cast one of the expressions (it doesn't seem to matter which one) to the expected return type.

11 choice.Finish = (count == 0) ? (TypeDelegate<int>) (result => { return; })
12                              : result => { letter.MailMerge(result); };


Go figure!

Tuesday, September 2, 2008

VIM on OpenVMS

This is a note to future Dan and anyone else that may have file permission problems when running VIM on OpenVMS.

Define this logical:

Dan$ define DECC$ACL_ACCESS_CHECK ENABLE

Apparently when disabled the access function only checks the UIC protection and not the OpenVMS ACL's.

There are all other kinds of goodies here

Monday, August 11, 2008

SVN 1.5.1 / Ruby bindings on Windows

Rather than messing around with compiling swig bindings etc:

  1. Download the ruby bindings from the svn site: (http://subversion.tigris.org/files/documents/15/43245/svn-win32-1.5.1_rb.zip)

  2. From the zip - copy ruby\lib\svn into c:\ruby\lib\ruby\site_ruby\1.8\svn

  3. From the zip – copy ruby\ext\svn\ext into c:\ruby\lib\ruby\site_ruby\1.8\svn\ext

  4. copy libeay32.dll and ssleay32.dll from your subversion 1.5 directory into c:\ruby\bin

  5. run irb and test with: require ‘svn/core’

Saturday, June 14, 2008

Why?

css:

.mainMenuHeader {color:#FFFFFF;}
.mainMenuHeader:hover {color:#F26540;}

xaml:

<Style x:Key="mainMenuHeader">
  <Setter Property="Control.Foreground" Value="#FFFFFF" />
  <Style.Triggers>
    <Trigger Property="Control.IsMouseOver" Value="True">
      <Setter Property="Control.Foreground" Value="#F26540" />
    </Trigger>
  </Style.Triggers>
</Style>

Saturday, May 31, 2008

Home Town Hero - That's How I Know

Hopping back in the time machine to 2002 a slightly rockin' album came out - Home Town Hero - Self Titled. It sounds a little grungy like The Exies and a little power-poppy like Rooney.

They had some minor successes opening for STP, Incubus and Weezer. Since then, they have completely fallen off the radar. Apparently there was some unpleasantness with their record label and they are now back under the moniker: Under the Influence of Giants. I gave their new LP a listen, i just couldn't get into it. I think it has validly been classified as disco-rock :)

Nick and I were giving it a thrash this week, so as an ode to the good old days I tabbed out the secret/bonus/acoustico track, as it appears no-one else has.

It ain't the most complicated tune on the planet but stay tuned for Niccolò Paganini's 24th Caprice next week :)

bon appétit!

Begin Tab
Standard tuning (EADGBE)
Intro (let ring)

 C       G\B      Am       F           C       G\B     C
---------------------------------------------------------------------
---------------------------------------------------------------------
-----0-------0--------2--------------------0-------0---------0---0---
---2---2---0---0----2---2------3---------2---2---0---0---2---2---2---
-3-------2--------0----------3---3-----3-------2-------3---3-3-3-3---
---------------------------1-----------------------------------------


Verse

 C       G\B      Am       F         C       G\B     E       F
------------------------------------------------------------------------
------------------------------------------------------------------------
-----0-------0--------2------------------0-------0----------------------
---2---2---0---0----2---2------3-------2---2---0---0-----2-------3------
-3-------2--------0----------3---3---3-------2---------2---2---3---3----
---------------------------1-------------------------0-------1----------

 C       G\B     Am        F    
-----------------------------------------
-----------------------------------------
-----0-------0-------2-------------------
---2---2---0---0---2---2-------3---------
-3-------2-------0-----------3---3-------
---------------------------1-------------

 C       G\B      E          F
-----------------------------------------
-----------------------------------------
-----0-------0----1-1-1-x-x--2-2--x-x-x---
---2---2---0---0--2-2-2-x-x--3-3--x-x-x---
-3-------2--------2-2-2-x-x--3-3--x-x-x---
------------------0-0-0-x-x--1-1--x-x-x---


Chorus (just bang out the chords instead of picking them)

 C   G\B  Am  F  C  G\B  C    (into to bridge)  
-0---3--------1--0--3----0--|--0------------
-1---3----1---1--1--3----1--|--1------------
-0---0----2---2--0--0----0--|--0------------
-2---0----2---3--2--0----2--|--0------------
-3---2----0---3--3--2----3--|--2------------
--------------1-------------|---------------


Bridge

 Am  F   G\B  Am  C  E    Am   F   G\B   Am  C   B\G
-0---1---3----0---0--0----0----1---3-----0---0---3---
-1---1---3----1---1--0----1----1---3-----1---1---3---
-2---2---0----2---0--1----2----2---0-----2---0---0---
-2---3---0----2---2--2----2----3---0-----2---2---0---
-0---3---2----0---3--2----0----3---2-----0---3---2---
-----1---------------0---------1---------------------


Thursday, March 20, 2008

Fixing the Teac HDB820 C.100 Error

The other day I mentioned I was feeling slightly hot and bothered. Well, so was my Teac HDB820.

I woke up this morning and I was greeted by the dreaded C.100 error. I tried turning it on and off, no go. I´ve had it for about 2 years so warranty was no option. On cracking it open one of the 1000uF 16V capacitors had a slight eruption. There are 3 in total and with the weather we´ve been having; i´m not suprised it gave up.

After I got home from work I ducked into DSE and grabbed 3 of these chunky bastards - 1000 uF 35 WV caps. I then whipped out the soldering iron (i knew doing year 11 electronics would pay off one day) and 10 minutes later I was back in sweet sweet HD heaven.

Saturday, March 15, 2008

SVN hooks on Windows with Ruby

I'd been meaning to write a pre-commit hook to catch empty log messages for a while but hadn't got around to it for one reason or another. I had a spare 5 minutes so I got stuck in.

The SVN book mentions that on Windows the hook files extension basically has to be .exe, .com or .bat. Even though .rb is executable on my SVN server it was not being called. So, instead I just called the ruby script from the bat file as such:

pre-commit.bat
1 SET DIR=%1/hooks
2 set REPOS="%1"
3 set TXN="%2"
4
5 c:\ruby\bin\ruby.exe d:\svn\hooks\pre-commit.rb %REPOS% %TXN% %DIR%

It also mentions that for security reasons, the repository executes hook scripts with an empty environment—that is, no environment variables are set at all, not even $PATH or %PATH%. Because of this, it is necessary to specify absolute paths.

Setting DIR above is a bit of a trick for debugging purposes so you can write a log file into the hooks directory to check things out. The ruby script is as follows:

pre-commit.rb
 1 REPOS, TXN, DIR = ARGV[0], ARGV[1], ARGV[2]
 2 SVN_LOOK = "C:/Program Files/Subversion/bin/svnlook.exe"
 3
 4 log_msg = %x["#{SVN_LOOK}" log -t #{TXN} #{REPOS}].chomp.strip
 5
 6 if (log_msg.nil? || log_msg.size < 5)
 7   err = <<-EOE
 8     This commit has failed due to the absence of a meaningful log message.
 9     Please provide a message describing why you changed what you did and
10     then try committing again. Ta -- Dan
11   EOE
12
13   STDERR.puts err
14   exit(1)
15 end

Yeah, I'm a bit of a bastard setting the minimum length of the log message to 5 chars. The only tricky bit of the entire process was realizing that I needed to chomp a new line off the log message. That's where using DIR and writing to a log file helped out.

Tally, ho!

Thursday, March 13, 2008

Sun / Microsoft developer marketing

I just got back from the Microsoft 'Visual Studio 2008' launch event at the Hilton. I can't put my finger on it but a few things just really pissed me off about the whole thing. Maybe it's the hot weather we've been experiencing but I'm fired up.

The ASP .NET session wasn't too bad. Kudos for the Javascript debugging / code completion, but then again firebug has been around for how long? To the people in the audience that debug their Javascript in IE using alerts; you deserve the agony :)

The next session was on Team Foundation Server , in particular the source control and continuous integration features. The presenter was carrying on like Microsoft invented these things. Personally, I found it rather condescending but on looking around everyone was lapping it up. I suppose if all you know is VSS then these things might impress you. These are not bells and whistles! These are essential development practices that you already should have been using. There are already so many existing tools available, I get along just fine with cruise control and svn. I didn't see anything innovative in TFFS at all.

I cast my mind back to the Sun Java developer day I attended last year; oh so many contrasts. Firstly, the Sun event was free, the Microsoft one wasn't (but thanks for sending me work) :). The Microsoft one was full of buzzwords, marketing and testimonials, where the sun one was more developer-centric, presenting some really cool shit, like launching project matisse.

It's a real shame the Sun event was cancelled in Adelaide this year. I dearly hope this isn't indicative of a shift

Unfortunately the biggest highlight of my day wasn't attending the event; it was my taxi almost running over Ahn Do on the corner of Wakefield and Pulteney street.

Saturday, January 26, 2008

Contributing to JRuby

Things have been pretty hectic at the moment but recently I found a little bit of time to contribute to JRuby. I highly recommend it.

The lads are doing a whole lot of good and could do with the help. Charlie wrote a post a while back on how to contribute. Go read it.. now ... seriously, and do something for the betterment of mankind.

Oh, and next time you pass an array to Dir.glob, I really hope it works :)

Monday, December 24, 2007

Stacked glasses stuck together?

Spray WD-40 using the nozzle around the lip of the stuck glass.

Run hot water around the bottom glass, fill the top glass up with cold water.

Smash on the lip with a skewer or more appropriate implement.

Bob's your uncle.


Merry Christmas

Sunday, December 9, 2007

Sventon for my homies

I'm a big fan of sventon, the guys have created one of the kickingest svn repository viewers around.

Much to my dismay after an upgrade to 1.3.0, stuff stopped working. I didn't have time to look at it until recently but I dived into the tomcat logs and pulled up this.

org.springframework.beans.MethodInvocationException: Property 'archiveFileCharset' threw exception; nested exception is java.nio.charset.UnsupportedCharsetException: cp437


Not so cool.

cp437 is the old dos-us character set which sure isn't installed on our svn box, hence the error.

So if this saves anyone else some time, go into the WEB-INF directory of sventon and edit sventon-servlet.xml. There is a property called archiveFileCharset. Change the value to whatever is appropriate for you. In my case it was cp1252 which is en-au amongst others, but should be good enough for most engrish speakers.

I thought Unicode had pretty much made Windows Code Pages obsolete, oh well.

Friday, November 16, 2007

Get full name for Windows user from Ruby

Lately I've been writing a few automation programs and it was suggested by a colleague that I write one for logging a job with EDS, our "service" provider.

The web page is nasty to navigate, I think they make it hard so people decide to give up and go get a beer instead of logging a job :)

Anyway, one of the fields on the page requires the full name of the person logging the job. It's trivial to grab the username of the logged on user:

1 puts ENV['USERNAME']

However, I wasn't sure of the easiest way to grab the user's full name. There are a few packages out there, for example the sys-admin gem. It didn't work though, I dug around in the source and it hardcodes a cimv2 path, no good.

Seeing this is a quick hack running on windows for windows, rah rah rah, might as well boogey with it.

Enter ADSI.

The following interrogates our AD and grabs what I want. Too easy.

1 require 'win32ole'
2 puts WIN32OLE.connect("WinNT://your.ad.box.sa.gov.au/#{ENV['USERNAME']}").FullName

Wednesday, November 14, 2007

Blowing away IE

ASP.NET development is great fun, especially when you are targeting Internet Explorer 7 (as if there are any other browsers anyway) :).

It doesn't take much to confuse IE so I find myself in the continuous loop of trying a code change, clearing the cache in IE, rebuilding the app and running it again. Numerous times a day, too many. Dancing the Microsoft Visual Studio developer jig if you will.

Well, enough is enough. Time to automate it.

Consider the following ruby script that uses WSH. I'm aware of watir and other winole jiggery, but why not just send the keystrokes, I say. This script blows out the IE cache, quits it, goes into visual studio and restarts the project, hurrah. Obviously you'll want to replace the AppActivate parameters to match your window titles.

 1 require 'win32ole'
 2
 3 wsh = WIN32OLE.new('Wscript.Shell')
 4 wsh.AppActivate('Generic Auditing Tool')
 5 sleep(2)
 6 wsh.SendKeys('%{T}') #ALT-T: select 'Tools'
 7 sleep(1)
 8 wsh.SendKeys('o') #select 'Internet Options'
 9 sleep(1)
10 wsh.SendKeys('%{D}') #select 'Delete'
11 sleep(1)
12 wsh.SendKeys('a') #select 'Delete all'
13 sleep(1)
14 wsh.SendKeys('d') #select 'also delete files and settings stored by add-ons'
15 sleep(1)
16 wsh.SendKeys('y') #select 'Yes'
17 sleep(8)
18 wsh.SendKeys('%{F4}') #quit 'Internet Options'
19 sleep(1)
20 wsh.SendKeys('%{F4}') #quit IE
21
22 wsh.AppActivate('NAT - Microsoft Visual Studio') #grab the visual studio window
23 sleep(2)
24 wsh.SendKeys('^{F5}') #start the project without debugging

Wednesday, October 17, 2007

C# .NET Regular Expressions gotcha

I sure do love me some regular expressions but haven't really had the need in any of my C# code until now.

A few things did catch me out though, in particular the constructor for the Regex class.

The constructor signature I'm interested in is this one: (string pattern, RegexOptions options). All well and good until you want to set multiple options!

Now I might be slightly naive but why doesn't the constructor use the params keyword allowing it to accept a variable number of RegexOptions? The constructor would then look something like (string pattern, params RegexOptions[] options). I think this follows the LOLA, unlike the current method of passing multiple regex options to the constructor.

Oh, guess how you are supposed to do it? Via a bitwise OR of the enum values ofcourse! Like my NUnit fun, at least I can now just get on with it.


 1 Regex matchFieldValue =
 2   new Regex(@"
 3     (?<Field>\w+) #capture 1 or more word characters to the named group 'Field'
 4     \s*=\s*       #followed by 0 or more spaces, an = sign and 0 or more spaces
 5     (?<Value> '   #match an apostrophe
 6         ([^'] |   #match 0 or more of any character that is not an ' OR
 7          ''.)*    #double apostrophe's followed by any character          
 8     ')            #match the closing ' and capture to named group 'Value'
 9             ",
10              RegexOptions.Compiled |
11              RegexOptions.IgnoreCase |
12              RegexOptions.IgnorePatternWhitespace);

Friday, October 12, 2007

NUnit configuration woes

I've been going through writing NUnit tests for a .NET web app I'm writing at work and all was going well until I hit some code that was using the ConfigurationManager.

1 private static readonly string CONNECTION_STRING =
2  ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;

For backgrounds sake I've created a test dll that sits outside the web app that calls a dll used by the web app. The connection string information is stored in Web.config.

Whenever NUnit loaded up the tests requiring that connection it barfed this at me:

Test.TestDataAccessUtility.GetNameValueTOList : System.TypeInitializationException : The type initializer for 'DataAccessUtility' threw an exception.
----> System.NullReferenceException : Object reference not set to an instance of an object.


Nice, this essentially means that ConfigurationManager had crapped itself.

ConfigurationManager.ConnectionStrings.Count was returning 1.

ConfigurationManager.ConnectionStrings[0].ConnectionString sent back a conn string for a SQLExpress db with some configuration string I sure didn't set.

It would appear that the NUnit loads it's config file over your application's config file.

To fix, I just replaced the contents of the NUnit config file: Project1.config with the contents of my Web.config. There could be a better solution, but it's working now and I can move on with my life.

Thursday, October 4, 2007

Sequence Mapping Functions

I've slowly been making my way through Peter Seibel's Practical Common Lisp. Even though I'm also in between a few other books at the moment I've managed to let some of it soak in.

I came across the following example that shows off the quintessential map function.

1 (map 'vector #'* #(1 2 3 4 5) #(10 9 8 7 6))

It simply produces a new sequence by multiplying the subsequent elements of the supplied sequences, resulting in: => #(10 18 24 28 30)

To put it in perspective I decided to have a crack and see what an equivalent function would look like in Ruby. After a bit of mucking around I came up with this:

1 [1,2,3,4,5].zip([10,9,8,7,6]).map{|x,y| x * y}

I'm sure someone could probably come up with something nicer as there is more than one way to skin a cat in ruby (I haven't tried, honest - ..to skin a cat that is). Regardless I think we should all sit back and appreciate the aesthetics of the lisp map.

Monday, October 1, 2007

A slipshod guide to replacing 2003 Ford Focus tail and headlights

This was not fun and a bad way to kill a few hours. L's drivers side rear tail-light and front passenger side head-light decided to cark it at the same time. Now, I've changed a few globes in my time but this was ridiculous. What were those freaking Germans thinking when they put this car together?

I'm documenting this due to the shitty Focus car manual and lack of good info on ye olde' internet. Remember I am a nerd, not a grease monkey so if you break something, sucked in for taking my advice :)

For the easier of the two, I present the rear tail-light:
  1. Open the hatch, you'll see a screw next to the light mounting. Of course it's not a phillips or flat-head screw, it's a bastard hexalobular type thingamajig screw, look here for more information than you could ever care to want to know about the stupid screw: http://en.wikipedia.org/wiki/Torx. Luckily i had an attachment in my drill-bit set and managed to whip it off.

  2. This is where the manual is crap, it has a picture of a screw in the light? What the hell? No, the screw is actually behind the light, not that they tell you that. So climb into the boot if you are nimble or reach your hand into the boot kind of behind where the light fitting is. You can undo this screw with your hand as it's quiet large.

  3. Now you can just pull the light fitting off, and unscrew the little cylindrical plastic thingy that is housing the globe.

  4. Change it, put it all back together

  5. Sup on some Coopers Sparkling Ale (you're going to need it for the passenger side head-light).

Ok, the rear tail-light wasn't that bad but this is where those conniving German engineers decided to play nasty shenanigans.
  1. The battery is on the passenger side right near where we need to shove our hands. Remove the battery cover as it will make life a little bit easier.

  2. You won't be able to see a thing because the light cover recess is underneath the front of the bonnet. I read on a few forums that people have done crazy things to get to it, like jack the car up and remove the front wheel, or completely dismantle the front-end of the car, we don't want to be doing that.

  3. Grab a mirror and put it in the engine-bay so you can get a better look at what you're fiddling with.

  4. You'll see the black light housing, there is a metal hinge that runs horizontally across it, you need to flick it down with a bit of force.

  5. The housing also has two clips attaching at the top. These are bastards. I just bunted it with the handle of the screwdriver and managed to pop it off. Remove it, and put it to the side.

  6. It's best to do this bit by feel, because it is insanely hard to hold a mirror and do this at the same time. Reach in to where abouts you think the globe is and to the right of it there is another metal hook. Push it in and kind of pull up on it, it should spring release, move it to the left, out of the way.

  7. Now you can reach in and pull the globe out and change it.

Probably the hardest bit for me was getting the housing back in, even though I aligned the two clips no matter how hard i pushed or angled it, it would not go back in and seal the light fitting. Probably didn't help that that I had bugger all lighting when I was doing it.

Hopefully this has saved someone else a headache or a $60 visit to your mechanic / ford dealer, let's see if I can talk L into trading the Focus in for an ESP XD, atleast i can change the globes in them :)

Friday, September 21, 2007

Code Voyeur

I like perusing public code repositories, be they CVS/SVN/Mercurial/Git whatever. I'm not sure if this is some kind of sick code voyeurism fetish but I think it's kind of healthy in degrees. It's a good place to pick up tricks. Kind of like doing the weekly ruby quiz but looking at the code before you know what the task is and seeing how closely you think they correlate to the spec.

Scott Hanselman is also on the kick of reading other peoples code to become a better developer, could it be the path to enlightment?

It dawned upon me that at work I have rarely had the need to tread outside my projects. All this time i've been searching far and wide for great code when I had a veritable treasure trove of unread code right under my nose.

We have a VB contractor doing some work for us and I caught wind that someone asked him to do it in C# ASP.NET. Wow. Might not be so bad I thought. So I had a look in SVN and came across this:


 1     public static string Proper(string StringIn) {
 2       string Temp = StringIn;
 3       if (Temp.CompareTo(String.Empty) != 0) {
 4
 5         char[] Delimiter = { ' ' };
 6         string[] Words = Temp.Split(Delimiter);
 7         Temp = String.Empty;
 8
 9         for (int i = Words.GetLowerBound(0); i <= Words.GetUpperBound(0); i++)
10           if (Words[i].Trim().CompareTo(String.Empty) != 0)
11             Temp += Words[i].Substring(0, 1).ToUpper() +
12                     Words[i].Substring(1).ToLower() + " ";
13         return Temp;
14       }
15       else
16         return String.Empty;
17     }
18


Apart from the upper case local variable names, in-efficient string concatenation and re-inventing the wheel, the dude did alright. Absolute respect to him, he's smart, he got it working, but it is obvious that C# is not his native tongue. That is textbook VB in C#.

Here is something roughly equivalent I came up with that produces the same output (don't lambast me for not getting the current culture, "en-AU" does weird shit that "en" doesn't) :)


1     using System.Globalization;
2     public static string TitleCase(string str) {
3       return String.IsNullOrEmpty(str) ? String.Empty
4              : new CultureInfo("en").TextInfo.ToTitleCase(str.ToLower());
5     }


It's not his fault really. He was asked to code in a language he wasn't familiar with and he got by. But what he did was speak English in down-town Nairobi.

Now I don't know what my point is but just look at the API's if you are using an unfamiliar language. I'm not shit-hot with C#, give me C, Java or Ruby and I've got a fighting chance. The thing is I'd assume that .NET would provide a way to title case a string. Instead of re-inventing the wheel I did a google search and came across the TextInfo class. You think he would have twigged that if VB has StrConv there might be something vaguely similar in C#.

Moral of the story, if you're asked to code in a language you are not familiar with, knock it back or make it clear it might not look pretty. But i guess who doesn't like getting paid?