Search

Thursday, December 13, 2007

Bar Charts on the console

Golconda fort arches

I work on the UI action recorder and it has a strict performance requirement. The tool dumps the time it takes to record each action in it's log and that is compared against the maximum allowed value (otherwise the system will seem sluggish). To do this obviously we need fancy charts, as everyone likes them, other than of course the alpha-geeks :).

However, I like the console chart. Way back my mom used to work on Main-frames that ran COBOL on them and dumped out business data on paper at the end of the day. These reports had these printed bar charts.

I wrote a small ruby script to dump these charts on the console. The output looks like

D:\MyStuff\Code\Ruby>perf c:\logs\Recorder_20071118_144855.843.log
c:/logs/Recorder_20071118_144855.843.log ===============================>
640 ********************************************************************************
0 *
109 *************
0 *
46 *****
0 *


Serves the same purpose as their fancier counterpart but manages to look uber geeky.

Support for range in programming languages

DSCF2530

The .NET platform and the languages on top of it have limited or no support for range of values. Data ranges are one of the most common data-types and somehow it's not there. Funnily most programmers do not even seem to miss it (unless of course if you have used Ruby).

How would you specify a valid range of age and validate user data against it? If you know the maximum and minimum values, at max you'd define a MaxAge and MinAge consts and strew the code with if(age < MinAge|| age >MaxAge). Or maybe you'll define a class to encapsulate this and add a IsValid method.

However, in Ruby, Range is a standard DataType like say string. To do the above processing you'd do

age = 1..120

print age.include?(50)
print age.include?(130)


print age === (50) # more easier way to do include? test using the === operator


So intuitively you create a range using start..stop.


Creating a range of data is also very simple. Say you want to generate the column numbers for an excel sheet, you'd do the following

column = 'A'..'ZZ'

column.to_a # creates an array of all the values

column.each {|v| puts "#{v}\n"}

Similarly ranges can be easily created for any class by implementing some special methods. On ruby the support of Range is in the compiler and makes the code very easy to develop and intuitive.


>>Cross posted here

Wednesday, December 05, 2007

Fun Windows Home Server site

2006_1101_200024

Windows Home Server team has a nice light-hearted site up at http://www.stayathomeserver.com/. All of it was funny, until I reached the page http://www.stayathomeserver.com/book.aspx. It says "daddy wants to give mommy a special gift.... So he buys a stay-at-home server".  That's not funny, "Wife Acceptance Factor" would be reflecting nitrogen freezing point for a home server.

You can sneak one in, understate the price and show all the image streaming to kinda buy acceptance, but a gift, no way :)

Saturday, December 01, 2007

Choose your company name well

 

Picture 057

Sometime back Hutch phone in India got bought over by the international phone giant vodafone. They re-branded Hutch in India to Vodafone.

Now when I call up home and the phone is busy I get a recorded message in Bengali which means "The Vodafone number you're trying to call is busy". All that is good but the problem is that vodafone in Bengali exactly means foolish phone. So I just hang up and wait for the foolish-phone to get free.

Friday, November 30, 2007

Ravenous Bugblatter beast on Indian roads

From the HitchHiker's Guide to the Galaxy.

"The Ravenous Bugblatter Beast of Traal is a creature that hails from the planet of Traal, and will eat anything. If you are to encounter one, the Guide tells you that it's impossible to slay, so you should wrap a towel around your head. This creature is so mind-bogglingly stupid that it assumes that if you can't see it, then it can't see you."

I felt like one while on a road-trip to Visakhapatnam and surely you'll feel like one on Indian roads. We were going at high speed and suddenly we see someone crossing the highway. We honked hard and the person simply looked down. So the idea is that, if he can't see you, then you don't exist. Or maybe they were using the SEP field technology.

In the following video watch the first person crossing the road and next a cyclist goes in the wrong direction as we wiz past at 120kmph (75 miles/hour).

Newbie Question: How do I figure out the inheritance chain of a type

Redmond_2005_0417_010447

I got this question from someone just starting out on the .NET platform. He is used to hit F12 (go to definition) on types and then figure out the inheritance chain. However, he couldn't do that say on a number (int) or array.

The solution is to write a simple recursive routine as follows

static void Dump(Type t)
{
if (t != null)
{
Dump(t.BaseType);
Console.WriteLine(t.ToString());
}
}

The routine can be called as follows

Dump(typeof(int));
Dump("abc".GetType());
Dump(1.GetType());
Dump(typeof(EventAttributes));
No marks for guessing the output though :)

Wednesday, November 28, 2007

Woohoo - Rosario November CTP is out...

2006_0311_123604

...and I can finally talk about what I'm working on for the last so many months.

First things first, for more information on Microsoft Visual Studio Team System code name "Rosario" November CTP release head on to Jeff Beehler's blog

A small bullet in the list of features is Manual Test execution. What it means is that you can now record you manual tests and play them back. Yes, it means you have a UI record and playback feature in the Manual Test Runner!! It's not a full fledged UI automation solution for now. It is mainly targeted to speed up manual testing so that the manual tester can zip past the part which she is not interested in testing. E.g. the manual tester can record the login, purchase pages so that she can play them to directly land in the final checkout page and do manual actions/validations on it.

The solution works for web-UI (IE pages) and also has very limited support for Win32 applications.

I work as a part of the team that develops the record and playback (RnP) framework. It's been an excruciating working on a great technology but not being able to publicly talk about it. Thankfully that time has ended :)

How do you name your computer

2006_1101_200024

Windows gives examples of "Kitchen Computer" or "Mary's Computer" for setting the name of a computer (Computer Name tab in System Properties). But I'm sure that most people don't name their computers that way and show off a bit of creativity in it.

Previously I used to use names from Asterix like GetAFix for my main dev box. Now I exclusively use names from Hitchhiker's Guide to the Galaxy. Some of the machines I use are named as below

  1. traal: My test box
  2. Krikkit: My dev box
  3. Vogon: A old vintage machine I have at work which I use to test some perf scenarios (Vista on 512mb RAM :^) )
  4. Hooloovoo : My personal laptop
  5. Bugblatter: Another laptop

What name do you use?

Tuesday, November 20, 2007

True object oriented language

 

DSCF2530

Today I was spreading the goodness of Ruby and why I love it so much (and you can expect multiple posts on it). SmallTalk programmers can sneer at me, but hey I wasn't even born when SmallTalk came into being and hence I can be pardoned for pretending that Ruby invented this :)

Languages like Ruby are "truly" object oriented. So even a number like 2 is an instance of the FixNum class. So the following is valid Ruby code which returns the absolute value of the number.

-12345.abs

Taking this to an extreme is the iteration syntax. In C# to write something in a loop "n" time I'd be needed to get into for/foreach syntax, however in Ruby I can do the following

5.times { puts "Hello"}

Which prints Hello 5 times.


However, I actually lied about having to use for/foreach statement in C#. With the new extension-method/lambda goodness we can very well achieve something close in C#.


For that first we create the following extension method

public static class Extensions
{
public static void times(this int n, Action a)
{
for (int i = 0; i < n; i++)
{
a();
}
}
}

Then we can call "times" on an int as easily (well almost as I still need some lambda ugliness).

5.times(() => Console.WriteLine("Hello"));
// Or
6.times(delegate { Console.WriteLine("Hello"); });

All programming languages evolve towards Lisp

 

2007_01_28 120

In an internal DL people were debating what all should be included in the next version of C#. One of the things I suggested turned into an interesting thread.

Abhinaba: Add if as expression (like in Ruby) so that I can do the following

var ageGroup = if age < 2
                   "Infant"
               else if age < 19
                   "Teen";

SomeOne: Can't we do

var ageGroup = ((age < 2) ? "Infant" : ((age < 19) ? "Teen" : String.Empty));

Abhinaba: We can but put 4 more cases and it’ll start looking like Lisp :) with all the parenthesis.


SomeTwo: All programming languages evolve towards Lisp.


Yeah, right!!!

Monday, November 19, 2007

Lack of Aspect Oriented Programming support in .NET

I was preparing for a presentation on Aspect Oriented Programming and I started re-looking for the solutions in .NET.

I'm personally not interested about any of the dynamic methodologies, be it dynamic weaving or any other form of dynamic proxying. To me CLR is static-typed and I'd want any solution to be the same (on DLR I'd definitely accept a dynamic solution). Predictability, performance, debugability are  major concerns that are not well addressed in dynamic methodologies. Some of the Dynamic approaches also have special requirements like they can only support virtual methods as join-points.

To me the perfect AOP solution on .NET would either be an IL weaver which ships as a post-compilation tool or an extension language. AspectDNG and EOS are good example for the two approaches respectively.

Wikipedia had a bunch of links and I tried couple of them. It seemed like most of the tools uses dynamic approaches and had the same issues mentioned above. From the static tools I tried AspectDNG's IL weaver. Even though the weaving was good it didn't update the pdb files resulting in very poor (or no) debugging experience. I tried EOS and liked it a lot. However, the project seemed to have died with no updates for a long time.

I think something serious needs to happen in this space. Either Microsoft or some other large body (serious open source project ?) needs to pick AOP up to make it successful in .NET. To me the tool of choice would be extension to the C# language in the same lines as EOS (or AspectJ).

There seems to be already some work going on like the Policy Injection Application Block which works over .NET remoting.

Saturday, November 17, 2007

The WOW factor in software

 

I care a lot about the nice nifty features that takes a software from being just a good software to a great software. It makes me feel that the developer really cared. I know how features are cut and these making it to the product indicate a mature, well thought-out execution.

Joel in his How to demo software writes

"bump into all the nice little “fit and finish” features of your product. Oh look, that column is halfway off screen. No problem. I’ll just drag it over. (“Wha!” the audience gasps, “you dragged a column in HTML?”) Oh, look, this feature is supposed to be done by next Tuesday. I’ll type “next tuesday” in the due date box. (“OMG!” they squeal. You typed “next tuesday” and it was replaced with “11/20/2007”)."

I absolutely agree to this. I've seen Microsoft Office time and again do that. The first time I fired up a PowerPoint presentation on a dual screen I gave that same squeal "OMG! the slide show start on one and I get the presenter view on the other with full access to the notes!!!!". Even 3 days back I used the same mode for a presentation on Aspect Oriented Programming and felt happy about using the product.

However, there's the other category of software which doesn't work in first place and tries to be smart on top of it. There's nothing worse than this. You look at these in disgust and head over to the dumber but working competition.

Thursday, November 15, 2007

Don't forget to lock your Computer

So Amit pointed me to this post on Coding Horror (I didn't get time to read any of the feeds for the last 2 days!!). It's about colleagues playing pranks with folks who leave their computer un-locked. I myself have done couple of these stupid but amazingly successful ones like taking screen shot of the desktop and then making it the wallpaper. Then you hide all visible things on the desktop so that the user on retuning goes on clicking on them without any result.

However, these days at Microsoft the prank has changed. On returning you just get to see an email typed out, addressed to Bill Gates. I don't even want to get into the topic of what is typed. The effect is amazing and permanent. Win+L keys become etched in your reflexes.

Monday, April 23, 2007

I just heard from a friend that my ex-colleague Sachin Gaur has passed away. He comitted suicide unable to cope with the pressure of our profession. He used to work with me in Adobe. He left behind his wife and son.

Sachin was a very kind person. When I bought my car, he drove it back from the car showroom as I was a bit unsure of driving it. I still remember him advising me to driving slowly and safely on the way back.

This is me with Sachin sitting beside me at a office lunch at the Noida Radission. May his soul rest in peace.

Friday, December 15, 2006

switches and jump tables

In my last post I had discussed about how only constants can be used with C# switches. From the post's comments and later discussing with other folks I learnt something that came to me as a surprise. A lot of people working on managed code consider switch-case to be a stylistic variant of if-else, and that is all.

However, in the C/C++ world switch is not just a variant of if-else (neither is it in .NET), it's a fast (O(1)) variant of if-else (O(n)). Stating that switch is just a better way to express multiple comparison against the same variable is stating Dictionary<T> is just another form of List<T>. They are not (Dictionary can give you O(1) lookup results).

For example C restricts the case to have constant-expression. This is done so that the compiler can generate optimized jump-table for its execution. Let's consider the following code.


switch(i) {
case 4:...
case 5:...
case 6:...
case 7:...
// many more cases...
default:...
}

For this code the machine code generated is similar to the steps below.


  1. Compile time jump table creation: For each case statement a fixed block of memory is reserved. Say 8 bytes. These 8 bytes contain a jump (jmp) instruction to the location where the actual code for the case resides. The base address of this table is labeled as say JMPTABLEBASE.
  2. Normalizes the value of i as i = i - 4 (the first value of the case)
  3. Boundary check: For the i it sees if the value is larger than the largest case (7-4 = 3), in case it is the execution flows to default.
  4. Jump to address JMPTABLEBASE + (i * 8)

As you can see from above the whole thing happens at constant time.

Some embedded C compilers (like the TI C-compiler) generates separate code section named .switch for the jumptable. Later this section can be targetted to the high-speed internal DARAM for faster execution in case the switch needs such special treatment.

Obviously compilers vary a lot in this manner .

Why can we only use constants in a switch-case statement?

Why can we only use constants in a switch-case statement? The following code fails to compile with the error “A constant value is needed” for someStr as it is not a constant string.


static void func(string str)
{
switch(str)
{
case "Zaphod": Console.WriteLine("The king"); break;
case someStr: Console.WriteLine("The coder"); break;
default: Console.WriteLine("None"); break;
}
}
string someStr = "Noo";

Here goes a long answer to this short question.



The reason is simple and yet involved. Let’s take the following valid code which only has constants and see how it works.


static void func(string str)
{
switch(str)
{
case "Zaphod": Console.WriteLine("The king"); break;
case "Abhinab": Console.WriteLine("The coder"); break;
default: Console.WriteLine("None"); break;
}
}

If we open see the code in IL it looks something like this


      L_0007: ldstr "Zaphod"
L_000c: call bool string::op_Equality(string, string)
L_0011: brtrue.s L_0022
L_0013: ldloc.0
L_0014: ldstr "Abhinab"
L_0019: call bool string::op_Equality(string, string)
L_001e: brtrue.s L_002f
L_0020: br.s L_003c
L_0022: ldstr "The king"
L_0027: call void [mscorlib]System.Console::WriteLine(string)
L_002c: nop
L_002d: br.s L_0049
L_002f: ldstr "The coder"
L_0034: call void [mscorlib]System.Console::WriteLine(string)
L_0039: nop
L_003a: br.s L_0049
L_003c: ldstr "None"

See the usage of op_Equality in L_000C and L_0019. This indicates that even though we are using switch-case, ultimately the code is converted to multiple if-then-else by the compiler. So the switch-case is converted by the compiler to something like


if (str == "Zaphod")
Console.WriteLine("The king");
else if (str == "Abhinab")
Console.WriteLine("The coder");
else
Console.WriteLine("None");

If this is the case then what is stopping the case statements from having non-constants? In case of a non-constant the code generated could be something like if (str == someNonConstantStr) which is valid code.



The answer is simple. When the numbers of cases are larger, the generated code is very different and is not constituted of if-then-else. Isn’t that obvious? Otherwise why would anyone ever use switch-case and why would we call switch case to be faster??



Lets see when we have a large number of case’s as follows what happens.


switch(str)
{
case "Zaphod": Console.WriteLine("The king"); break;
case "Abhinab": Console.WriteLine("The coder"); break;
case "Ford": Console.WriteLine("The Hitchhiker"); break;
case "Trilian": Console.WriteLine("The traveler"); break;
case "Marvin": Console.WriteLine("The Robot"); break;
case "Agrajag": Console.WriteLine("The Dead"); break;
default: Console.WriteLine("None"); break;
}

For this first a class is generated by the compiler which looks like


Internal class CompilerGeneratedClass
{
internal static Dictionary CompilerGenDict;
}

And then for the switch case the following code is generated.


if (CompilerGeneratedClass.CompilerGenDict == null)
{
Dictionary dictionary1 = new Dictionary(6);
dictionary1.Add("Zaphod", 0);
dictionary1.Add("Abhinab", 1);
...
CompilerGeneratedClass.CompilerGenDict = dictionary1;
}
if (CompilerGeneratedClass.CompilerGenDict.TryGetValue(
str, out num1))
{
switch (num1)
{
case 0: Console.WriteLine("The king"); return
case 1: Console.WriteLine("The coder"); return;
case 2: Console.WriteLine("The Hitchhiker"); return;
...
}
}
Console.WriteLine("None");

What this means is that first time the function is called a Dictionary of strings (key) and int (value) is created and all the cases are stored in this dictionary as the key and an integer as a value is stored against it. Then for the switch statement the string is taken and is queried in the dictionary and if it is present the number value for the string is returned. Using this number the compiler creates an efficient jump table and it jumps to the target Console.Writeline string.



Now the answer :). The strings are pre-stored in the dictionary. If the strings in the case statement were not constants, changes in them won’t reflect in the dictionary and hence you’d land up comparing against stale value. To avoid this inconsistency the non-constant values are not supported at all.



Obviously for dynamic values the dictionary cannot be used and hence there is no optimization possible for switch-case so one should anyway use if-then-else.

Test Driven Development

A lot have already been said about Test Driven Development (TDD) by a lot of people, but I'd still like to add my 0.02paisa.

We have an internal requirement of checking in UnitTests along with the product code and the code coverage for the unit tests needs to be high. Most of our developers have over 85% code coverage.

In my sources I decided to try out TDD. I used the following steps

  1. Write the method's prototype so that it matches the design doc and throw a NotImplementedException in it.
  2. Write unit-tests in Visual Studio Team System unit-test framework. I try to cover all the requirements, even the ones required for negative testing like pass an invalid handle and catch an ArgumentNullException and verify that the correct argument is mentioned in ArgumentNullException.Param.
  3. After that I run the tests. All the tests obviously fail with lots of X marks.
  4. Then I go about fixing each of the test failures by adding the functionality in the code.
  5. After each fix (or couple of them) I run the tests and the red marks keep changing into test passed green ticks.
  6. Once I'm done, I run with code coverage and then add more tests if required to cover the blocks which were not touched by the tests.

Even though the system looks simple it has helped me enormously by catching multiple bugs at the beginning. Even trivial tests like tests for GetHashCode and operator overloads found issues :) The fun in seeing all those X marks disappear one after the other brings in a childish zeal to get them done even faster.

The other goodness is that after every code change later I can easily fire these tests for sanity check.

Conditional Text

We have moved to a new Satellite TV provider some time back. It is time to pay the quarterly bill, so I dug up their manual to look for online payment options. Sure enough there was a section on "Internet payments". I opened the section and it had one line. "For Internet payment options click here"!! How the hell am I supposed to click on a paper?

The reason for the line is simple enough, they are just distributing printed copies of their online documentation.

I shared this with couple of friends and the discussion soon turned to the issues with maintaining multiple versions of the same document. I figured out soon enough that they have not heard about conditional text supported in most DTP software. I was in the Dev team for Adobe FrameMaker and it was one of the features in the product. It works very much like the following C* kind of code


#if Web
Console.WriteLine("Click <a href=\"http://www.abhinaba.com\">Here</a>");
#elif Doc
Console.WriteLine("Visit http://www.abhinaba.com");
#endif

If the symbol WEB is defined then the fancy Click Here is printed else the URL is printed out. Conditional Content works very much like this. You can define document wide variables and associate text, images (any supported content) with these variables. Later you switch on/off one or more of these variables to print out various versions of the same doc. So all your common content remains common and you have the ability to pick/select from the rest.

No idea if Office supports this. But with the powerful collaboration features supported in Word, I highly suspect that this is indeed supported.

Change the world or go home

Saw this via Steve Clayton's blog. This is going to be my new wallpaper...


Funny messages are not always funny

I used to work in a Company where Easter Eggs used to be considered a feature and there used to be a official maintainer for it (I used to maintain both the Easters listed here and more). I used to feel that Microsoft shouldn't have moved away from inserting Easter eggs and should've stuck with funny messages in its Software. Microsoft Max (now canned) use to give really funny messages like suggesting that I get coffee as the installation may take some time.

However, with time I have realized that funny messages are not always funny (even though I still believe Easter eggs are). If you look up the demographic usage data of Orkut it is mostly used in Brazil (60%) and the 3rd highest usage is in India (12%) and growing astronomically. Server failures in Orkut is given out as a "Bad, Bad Server. No donut for you" message. Now the problem is in India we do not eat Donut and I have a ton of non-geek friends who've never been to the US and have no idea what a donut is. One of them got majorly irritated with the message.

I guess for free services where there is no paying customers it's OK to have these kind of funny light-hearted messages, but still you need to target your jokes well. Lets hope in the Future we have India servers throwing up "Bad Bad server, no Vada for you" messages :)