Thursday, October 30, 2008

The difference between Java and Javascript

 I recently posted the following question on Stack Overflow: What's the difference between Javascript and Java? and received some great answers.

Greg Hewgill's answer of "Java and Javascript are similar like Car and Carpet are similar" was spot on and amusing. Shog9's answer was hillarious.

The other answers citing the differences listed a few I hadn't thought of but essentially there's almost nothing to tie these two languages together but for part of a word and some curly braces.

But that's not what this is about. What I'm finding fascinating about Stack Overflow is asking questions that I already know the answer to and discovering a whole bunch of answers and opinions that I hadn't thought of and further broadening my knowledge. There're some very clever people hanging out there - I wish I was one of them.

Thursday, October 23, 2008

Running VPN on a VM

Just been doing some testing on running VPN on a VM and on the host OS. The host in this case is Server 2008 x64 and the VM software is Hyper-V and the guest VM is Vista x64.

As expected, the OS running VPN takes on the IP address of the VPN while host or guest will continue to use the original IP that you were previously connected to. Obviously the VPN is running over your original IP to get to the VPN but to the outside world this is the IP that you're using.

Wednesday, October 22, 2008

String Reverse in C#

 I had to write a string reverse function today and wasn't happy with my initial (basic) function so I posted it on Stack Overflow to see what other algorithms that developers might come up with. My restriction was that it had to be in C# 2.0 and so I couldn't use LINQ. Out of curiosity I decided to do a performance test on each of the functions and while I was at it I threw in the LINQ equivalent to see how it would perform. For the test of a 500 character string I looped each function 100,000 times and for the test of a 10 character string I looped the functions 10,000,000 times.
These are the functions that I tested:
// string concatenation with for loop
public string ReverseA(string text)
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
        reverse += cArray[i];
    return reverse;

// Array.Reverse function
public string ReverseB(string text)
    char[] charArray = text.ToCharArray();
    return new string(charArray);

// push/pop Stack<>
public string ReverseC(string text)
    Stack resultStack = new Stack();
    foreach (char c in text)

    StringBuilder sb = new StringBuilder();
    while (resultStack.Count > 0)
    return sb.ToString();

public string ReverseD(string text)
    return new string(text.ToCharArray().Reverse().ToArray());

// StringBuilder
public string ReverseE(string text)
    char[] cArray = text.ToCharArray();
    StringBuilder reverse = new StringBuilder();
    for (int i = cArray.Length - 1; i > -1; i--)
    return reverse.ToString();


What surprised me was how poorley LINQ did on the short string compared to the others.
You may also find the rudimentary test harness that I put together interesting:
delegate string ReverseDelegate(string text);

public void RunPerformance()
    int loopCount = 10000000;
    int stringSize = 100;
    string[] reverseTextArray = Enumerable.Repeat("abcde", stringSize).ToArray();
    string reverseText = String.Join("", reverseTextArray);
    // reverseText = "1234567890";
    DateTime startTime, endTime;
    ReverseDelegate[] reverseFunc = new ReverseDelegate[5];
    reverseFunc[0] = ReverseA;
    reverseFunc[1] = ReverseB;
    reverseFunc[2] = ReverseC;
    reverseFunc[3] = ReverseD;
    reverseFunc[4] = ReverseE;


    TimeSpan[] reverseTime = new TimeSpan[reverseFunc.Length];

    for (int i = 0; i < reverseFunc.Length; i++)
        startTime = DateTime.Now;
        for (int j = 0; j < loopCount; j++)
        endTime = DateTime.Now;
        reverseTime[i] = endTime - startTime;
        Console.WriteLine("{0}/{2} took {1}", i, reverseTime[i], reverseFunc[i].Method);

    Console.WriteLine("break point");

private void AssertThatFunctionsWorkCorrectly(ReverseDelegate[] reverseFunc)
    string test = "abcdefghi";
    string expected = "ihgfedcba";
    for(int i=0; i

Monday, October 20, 2008

Phoenix Startup Weekend Sunday 19 Oct 2008

The last day was good. We had more direction about what we wanted to achieve in that day and what it would take to achieve it. The team is very good and it did not appear that we took a lot of effort to make it come together. The prototype that we put together worked and played the player. The puppet master pulled the strings and web sites updated, text messages were sent and answer machines responded with the appropriate distress calls.

Dan, a Microsoft rep played the game towards the late afternoon and apart from some minor glitches which were nothing to do with our technology he succeeded in playing the game and accomplishing the mission which was do defuse a fake bomb (actually an iPhone). He also gave us a glowing recommendation at the sum-up at the end. The audience also had plenty of questions which was a good sign.

Sunday, October 19, 2008

Phoenix Startup Weekend Saturday 18 Oct 2008

The group started with a strategic meeting about where we wanted to get to and also the expanse and potential of the Alternate Reality Game project. There were a lot of good ideas and the potential for this product could be huge. Monetizing it without the player being offended appears to be fairly easy inasmuch as the oportunities for doing such appear wide spread.

Problems faced during the day:

  • The network at Gangplank (our hosts) was very slow. This could have been because the amount of traffic was not what it was set-up for.
  • The four developers on the team were split between the Java world and .NET worlds meaning that two of the developers could not work to their full potential.
  • The marketers/implementers were more focused on what the potential of the product could be and should have probably spent more time looking at what we can produce in the span of 1.5 days.

These were minor set backs and I hope that we get a working prototype finished by tomorrow evening.

Saturday, October 18, 2008

Phoenix Startup Weekend Friday Night 17 Oct 2008

The Phoenix Startup Weekend kicked off to a good start on Friday evening. Pizza and beer wer served. About 30 ideas were pitched.

I pitched two which got 3 and 2 votes respectively and were therefore dropped from the ideas list. The first idea was a web managed Scavenger Hunt which I didn't even vote for myself because it was very similar to the group that I eventually joined which is an Alternate Reality Game project. The second idea that I pitched was for a web based list learning system which I still think has a lot of potential but I don't think that I pitched it very well.

Of the 30 or so projects pitched about 6 to 8 of them went on to have groups formed to discuss their potential. One of the interesting fallouts from this stage of development was the importance of having developers buy into your idea. There was a small group of people who were very enthusiastic about their project but there were no developers that had joined that group. I believe that the decided to disband and redistribute.

After joining my group It was immediately obvious that there were a lot of very inteligent, motivated and highly talented people around me. This weekend promises to be at the very least a fantastic education.

Sunday, October 12, 2008

.NET Directory Notes

The documentation for the XmlWriter.Create Method (string) function has ArgumentNullException as the only exception that will be thrown for this function. I've found that System.IO.DirectoryNotFoundException can also be thrown here.

The AppDomain.CurrentDomain.BaseDirectory does not terminate with a back slash if you are running a unit test - you need to add this if you're going to append further directories. To make the using of AppDomain.CurrentDomain.BaseDirectory work in both unit tests and production code you might want to create a property to access the AppDomain.CurrentDomain.BaseDirectory that looks something like this:

string SafeBaseDirectory
                return AppDomain.CurrentDomain.BaseDirectory.EndsWith(@"\") ? 
                                AppDomain.CurrentDomain.BaseDirectory :
                                AppDomain.CurrentDomain.BaseDirectory + @"\";

Friday, October 10, 2008

C# Keywords

C# Keywords


Contextual Keywords

partial (method)
partial (type)
where (generic type constraint)
where (query clause)

Tuesday, October 7, 2008

LINQ to XML Notes

Some notes on LINQ to XML

  • All LINQ to XML objects inherit from XObject.
  • All LINQ to XML objects except XAttribute inherit from XNode which directly inherits from XObject.
  • Using XDocument is optional. (XDocument wraps an XElement object and adds to it.)
  • Both XDocument and XElement have static methods Load and Parse to load XML.
  • Load() can build an X-DOM from a TextReader, XmlReader, a file or a URI (such as a web service or RSS feed).
  • Parse can build an X-DOM from a fragment of XML in a string.

Monday, October 6, 2008

How does the Luhn Test work?

The code to find credit cards in a block of text is available on GitHub: Credit Card

The Luhn Test or Luhn Algorithm is a test of a series of numbers to determine if they could be a valid credit card. The algorithm is fairly simple and I'll demonstrate it with 4 digits.

The number to test: 4 - 5 - 6 - 7

Step 1: Starting from the right, double every second digit:

8 - 5 - 12 - 7

Step 2: If the result of the doubling ends up with a 2 digit number then add those 2 digits together.

8 - 5 - 3 - 7

Step 3: Add all the digits together.

8 + 5 + 3 + 7 = 23

Step 4: Mod the number against 10.

23 % 10 = 3

Step 5: Is the number exactly divisible by 10?

i.e. does 3 equal 0?

If it is (exactly divisible by 10) then it passes the Luhn Test and could be a credit card number.

Ask a simple question

I asked on Stack Overflow why i++ followed by ++i would compile but ++i++ would not compile under C#. When I saw the answer it was obvious why it was a simple question. I hadn't spent very long thinking about it and breaking the problem down.

What I found interesting though was that the question was immediately voted down and had a -2 vote after a few minutes. I checked again an hour later and it was back to zero.

I originally titled this post as "ask a stupid question" before realizing that the question wasn't stupid but one that many programmers could have. It was well answered and I am the wiser for it and I hope someone else is as well.

Based on this micro analysis, I wonder if Stack Overflow has a few elitist members who are fast to the draw and vote down anything that's a simple-to-solve problem.

Best practices for creating websites in IIS 6.0

 Omar AL Zabir has a good write-up on Best practices for creating websites in IIS 6.0.

Friday, October 3, 2008

Stopping a Hyper-V VM that refuses to stop

I posted this question on the Microsoft Tech Forums: I have a Vista (x64 Ultimate) VM that refuses to stop. (Host is Server 2008 x64.)  I've tried using the hard stop but it remains in the state of Stopping. How do I stop it from here?

And received this (great) answer from Stephen Edgar:

If you grab Sysinternals Process Monitor you can check each VMWP.EXE Process (Virtual Machine Worker Process) and Select 'Properties' and each process will have a reference in the 'Command Line' section of the properties dialogue which refers to the VM's GUID which can be found for each VM by examining the configuration files contained in C:\ProgramData\Microsoft\Windows\Hyper-V\Virtual Machines and then just kill the approriate VMWP.EXE Instance and that should kill that VM without affecting any of your other currently running VM's.

This is the second time that I've had this problem with Hyper-V and I have no doubt that it won't be the last. Thanks Stephen!

Thursday, October 2, 2008

Buying a PCI bus card on Craigslist

 Here's a question that I can't find an answer to. I've found a PCI bus card (TV tuner) on Craigslist that I want to buy. The seller says that they've got rid of their PC and now have a Mac and so don't have a need for this card. How can I find out if this card is working without lugging a PC around to his house and installing it then and there before buying it?

Wednesday, October 1, 2008

How not to leave breadcrumbs

I was listening to Jeff Atwood and Joel Spolsky's podcast from a couple of weeks ago (podcast 22) and Jeff mentioned the Fight Club rule (The first rule of fight club is you do not talk about fight club) and how Stack Overflow is not intended to be a site that discusses itself. i.e. The first rule of Stack Overflow is you do not talk about Stack Overflow on Stack Overflow. This is also the reason that I'm not posting this on Stack Overflow and instead posting it here.

One of the reasons that Jeff doesn't want Stack Overflow discussion on Stack Overflow is that he doesn't want Google et al indexing Stack Overflow pages that discuss how the site works. When a user finds Stack Overflow through a Google search it will hopefully bring them to a page with a question and solution to a problem that they might be trying to solve. Not to a meta-discussion.

So how do you solve this problem. In my opinion fairly easily: You dynamically create the robots.txt file that's in the root of the site each time it's requested (instead of having a static one). You then query the database for all questions that are marked with the "stackoverflow" tag and add their URL's to the disallow section of the robots.txt content that you're going to return to the requesting search-bot. That way the meta-discussion won't be indexed by the search-bot.

After typing that I thought of what is probably an even easier solution. When you retrieve and construct the page from the DB just add the <META name="robots" content="NOINDEX,NOFOLLOW" /> to the <head> tag in the page if it has a "stackoverflow" tag and Google won't index that page.

Not sure why I got so carried away with dynamically generating the robots.txt page/file...

Inheritance Question

In C#, which Console.WriteLine() would be hit?
Without consulting your compiler, take a look at the code and then vote your answer.

    public class A
        public void Bar(int n)

    public class B : A
        public void Bar(double n)

    class Program
        static void Main(string[] args)
            B b = new B();

Vote your answer now before you read any further.


At the time of writing this the general consensus was wrong. Note - I was also wrong when I took a guess at what the answer is.

The answer is that B.Bar will be hit and not A.Bar

My theory behind why this happens is that I think that C# walks the inheritance tree from the outer class inwards and each time that it finds a matching function name it then checks to see if all of the parameters can be cast to the first method that it finds. If so, it then uses that method.

With the help of a friend, I then tested this on Java. It turns out that Java does not behave in this manner. The Java compiler, I'm guessing takes 2 walks of the inheritance tree. The first time it looks for an exact match. The second time it attempts to do a cast. So the answer for a Java compiler would be a print of A.Bar. However, this question was asking about C#.

Here are the results of the poll

EDIT: Name mangling - that's how it does it in Java and C++. It creates a unique name for each function call based on its function name and the parameter types. I just remembered that.