How not to handle exceptions!

Was trying to pay my Electricity bill online via a site called Bangalore One, which is the Governments, premier one-stop shop for Electronic Delivery of Citizen Services.

I could not pay because it seems like some backend services they need for credit card payment is down. How do I know this? Because the site is revealing too much detail! See the exception details pasted below.

This is a great example of what not to do! I have seen this often, and it is lazy developers and even lazier testers who approved this and get this into production. One would have thought that government managing the “Silicon Valley of India” would know better!

It is also interesting to see that they are on a very old version of .NET – running on v1.1.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Exception: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[Exception: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.]
   BangaloreOne.clsBESCOM.fnCheckTransCnt(String LocationRRNo, String StaffCode, Int32 intDeptCode) +381
   bOneWebPortal.BESCOMConfirm.Page_Load(Object sender, EventArgs e) +721
   System.Web.UI.Control.OnLoad(EventArgs e) +67
   System.Web.UI.Control.LoadRecursive() +35
   System.Web.UI.Page.ProcessRequestMain() +750

Version Information: Microsoft .NET Framework Version:1.1.4322.2300; ASP.NET Version:1.1.4322.2300

Writing a compiler using C#

I was cleaning out my old papers (finally!) and came across an old paper I had titled “Compiler Writing Tools using C#” which essentially shows how you can write a number of tools like lex and yacc but instead of C/C++ on Unix, you use C# and .NET.

This paper covers the tokenizer, grammar, DFA, NFA, etc. I think conflicts and precedence is one area it would need a little more work. But overall its a very interesting piece of work – especially for one to learn the ropes if a lot of this is new.

Of course, writing compilers with C, overall is not the most productive experience (it sure is fun though!); if you have never done it before Standard ML or Haskell would be a better place to start. If you want to stick to .NET and roll out your own language (or create extensions) then check out this paper on MSDN.

All of this brought back memories when I wrote my own C++ compilers mainly with those tools on Unix System V and also on Xenix. Most people did not know (or perhaps remember) that Microsoft had a Unix version called Xenix which was later bought over by SCO and eventually become part of SCO Unix. Back in the days I use to run a dual-boot machine with Xenix and DOS. 🙂

Metro Apps in C++ anyone?

In Visual Studio “11” when I try and create a new C++ Metro app using the built-in template, I get the following error: “Can’t find localized resources”.

I wonder if anyone else has managed to get around this? I am running the Consumer Preview Build of Win 8 (Build 8250).



AWS Extension for Visual Studio

I had forgotten that I had the AWS Extension for Visual Studio installed until recently I noticed AWS Explorer item in the View menu option. This add-in allows you to explore the various features that Amazon exposes right from within Visual Studio. The toolkit makes it easier for developers to debug and deploy a .NET solutions that uses AWS.


When you install this, you also get AWS SDK for .NET which provides one with all the building blocks that are required for consuming the IaaS services exposed by AWS including SimpleDB, S3 and EC2.

If you are or planning to use AWS, this add-in is a must have in my opinion.

Troubleshooting WCF Performance – Part 1

More related details on Dustin’s post – WCF scales up slowly with bursts of work.

PowerShell script to kill named processes

There are times when you need to kill a number of processes in one-go like today when Chrome crashed a few times hanging all the running instances – next time Google says, one tab cannot bring down all of them – send them my way :). For such times, a PowerShell script is all you need.

I wrote up a simple one which takes the process name as input and then kills all the processes which match that name.

#Script is not signed, so need this.
Set-ExecutionPolicy Unrestricted

#Need to set the param to a variable
$target = $args[0]

if($target) {
    $orphanProcs = get-process | where {$_.Name -eq $target}

    #Check if list is null; if not kill all the procs
    if ($soonToBeDeadProcs) {
        #display list

        #kill list
        $soonToBeDeadProcs | foreach { $_.Kill() }
    else { Write-Host "Oops, no processes found older with the name: $target" }
else { 
    Write-Host "Oops, no arguments passed. You need to provide one argument (the Process Name)."
    Write-Host "Example 1: killproc chrome"
    Write-Host "Example 2: killproc 'some other process'"

Example Output (Killing Chrome in this case):

PS C:\Users\amit.bahree\Desktop> .\killproc.ps1 chrome

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
——-  ——    —–      —– —–   ——     — ———–
    139      30    34292      46708   164     3.87    376 chrome
    137      22    20932      33648   149     2.48   1260 chrome
    141      21    17896      31328   148     3.01   3572 chrome
   5434      37    56932      66528   266 1,134.36   4940 chrome
    139      22    20288      33084   150     4.12   5032 chrome
    145      21    16576      31368   149     0.58   5148 chrome
    147      19    14384      26992   150     1.42   5604 chrome
    142      23    32292      37416   156     8.42   6528 chrome
    136      17    12456      23964   142     0.30   6732 chrome
    144      26    27004      39136   156     0.98   6736 chrome
   1586      90   151224     209888   512   395.87   7184 chrome
    138      22    21388      33916   151     3.76   7504 chrome
    123      13     7756      15196   126     0.56   7512 chrome
    142      21    23112      35552   150     2.01   9860 chrome
    140      18    13032      25148   150     1.73  10432 chrome

Twitter Trends

I was excited to find that Twitter had a JSON (Javascript Object Notation) endpoint for the current trending topics and decided to write a simple consumer which can read this and then spit it out in a simple console. And JSON being so simple and more or less “universal” meant that there are multiple implementations for .NET. Of course if you got lots of bandwidth you can roll out your own parser.

I ended up using Json.NET, which in addition to being OpenSource is also one of the most robust utilities which makes working with JSON formatted data dead simple.

The code for the console app is quite straightforward. The static function ReadTrends() retrieves the JSON string from twitter which is then consumed and extracted. The only tricky part was using a constant key; the easiest way I could think of doing this was to replace the date-time stamp with a literal and then use that literal.

Of course this will fail if you the function ReadTrends() is called at (or just before midnight) on Dec 31st and the code returns to the main() function in the new year. I don’t think this is something I am going to put in production and am not going to be too worried about this behaviour.

At the time of writing this, the twitter trends (in JSON) are:

{“trends”:{“2011-03-04 17:18:01”:[{“name”:”#coisasderetiro”,”events”:null,”query”:”#coisasderetiro”,”promoted_content”:null},
{“name”:”Frying Nemo”,”events”:null,”query”:”Frying Nemo”,”promoted_content”:null},
{“name”:”Acoustic Aftermath”,”events”:null,”query”:”Acoustic Aftermath”,”promoted_content”:null},
{“name”:”Blade Runner”,”events”:null,”query”:”Blade Runner”,”promoted_content”:null},
{“name”:”Fun Race”,”events”:null,”query”:”Fun Race”,”promoted_content”:null},
{“name”:”Mike Huckabee”,”events”:null,”query”:”Mike Huckabee”,”promoted_content”:null},
{“name”:”Arctic Monkeys”,”events”:null,”query”:”Arctic Monkeys”,”promoted_content”:null}]},”as_of”:1299259081}

And here is the output in the console. I can see Charlie Sheen’s #tigerblood is still trending; and wonder what Artic Monkeys are upto – is there new album out or something?

Frying Nemo
Acoustic Aftermath
Blade Runner
Fun Race
Mike Huckabee
Arctic Monkeys
All done. Press any key to continue…

And finally here is the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;

namespace TwitterTrends
    class Program
        static void Main(string[] args)
                //get the trends
                string temp = ReadTrends();

                //as the key is a datetime stamp (which is constantly moving), need something constant to interrogate.
                //simplest way is to find out the year and then take 19 characters from that which is the datetime stamp
                //replace that with a literal (DESIGEEK.COM in my case) and then use the literal. I don't think I will
                //be trending on Twitter; but if you are worried then you can use something like a GUID.
                // For example at the time of writing this the datetime stamp was: "2011-03-02 14:20:00"
                string theDate = temp.Substring(temp.IndexOf(DateTime.Now.Year.ToString()), 19);
                temp = temp.Replace(theDate, "DESIGEEK.COM");

                //parse the string for the literal
                JObject trends = JObject.Parse(temp);
                var twitterTrends = from t in trends["trends"]["DESIGEEK.COM"]
                                    select t.Value<string>("name");

                //iterate through
                foreach (var item in twitterTrends)

            catch (Exception ex)
                Console.WriteLine("Following error occured:\n" + ex.ToString());
            Console.WriteLine("\nAll done. Press any key to continue...");

        private static string ReadTrends()
            //talk to twitter
            WebRequest theRequest = HttpWebRequest.Create("");
            HttpWebResponse theResponse = (HttpWebResponse)theRequest.GetResponse();

            //extract the data
            Stream stream = theResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string temp = reader.ReadToEnd();

            //clean up

            return temp;


Opensource ZigBee stack?

I was planning on getting the Telegesis ETRX2USB and wanted to know if there are any open source (or shareware) open source ZigBee stacks that I can use with that?

I also wanted to know if there is any opensource (or not too expensive), network management or network analyser for a ZigBee network? Essentially I want to be able to programatically view network and node information on the ZigBee network (e.g. S/N ratio, signal strength, etc.) – something similar to Ember’s Insight Desktop which shows the details I am interested in. I could not find anything specific and would be interested in getting ideas.

C++ Message queuing options?

I am thinking of implementing a queue in one of the projects I am working on right now (sorry cannot go into more details until it gets published – hopefully in a few months). Anywyas, this is in C++ which needs to run on Ubuntu and my queueing experience (with C++ or otherwise) is only with MSMQ which is brilliant, but does not help me here as that run only on Windows. I also cannot use something like STL Queue as this will need to run across a number of machines and trying to sync between them would a royal pain. In other words, this needs to be distributed and async “loose” messaging. 🙂

I am already using MOOS, so one option is for me to continue to use that – however this is for another part of the application and it might be easier for me to use something else (still need to think it through a little more).

These are the requirements (these are must haves!). Also if it makes a difference I am using CDT for this project.

  • Needs to be able to run on Ubuntu 9.04 (and higher)
  • Needs to be Open Source (cannot be commercial)
  • Needs to be able to store messages “offline”
  • Needs to be able to run on TCP with minimal dependencies. It would be nice not to have a whole bunch of underlying dependencies.
  • Preferably be easy to use (as a consumer) – I don’t have much time to read through loads of documentation just to get my head around the underlying object model and how to use it.
  • C++ support (if it was not obvious until now)

I did a little research online and came across the following, and wanted to get some feedback:

  • ActiveMQ – seems like it has good C++ support via CMS (C++ Messaging Service).
  • Amazon SQS –  not sure how good the C++ support is. If there is no library per se that I can use, then writing things around REST APIs might be more painful. Also I suddenly have a dependency to be able to go to the public internet. Also it is not free (though there is a free 100K messages / month).
  • MQ4CPP – seems quite amateurish (kudos to the guy writing it though – seems like an interesting project to pick up when once has time).
  • RabbitMQ – I know some guys used this at work (though that was using it in .NET); nothing for C++, but there some C experimental code; overall does not inspire confidence (in the context of C++).
  • OpenAMQ – seems quite interesting and also has a C++ API based on its WireAPI.
  • Anything else??

At face value it seems like this is down to ActiveMQ and OpenAMQ. Just looking at the quick samples between the two ActiveMQ seems like more C++ friendly and easier to use compared to OpenAMQ. Of course this is just the first impression and I could be completely wrong – it is not like I have had a chance to play with this (yet anyways).

Does anyone have any experience and feedback on this matter? Feel free to comment on this post, or tweet me.

SQL Syntax Error (with MySQL)

Say you are writing a new stored procedure (for MySQL) and when you execute it, you get an error something like shown below – as you probably figured out all it means is that there is a syntax error with in the SQL. Often the error is misleading especially if it is a complicated query. One easy way to help narrow down the issue is to run it in a SQL Console which usually provides a better clue that can be your pointer to fixing the issue.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for 
the right syntax to use near 'END' at line 17 (errno: 1064). Click 'Ignore' if you'd like to have this 
error ignored until the end of the script.

If you run this script you will get the above error:


DROP PROCEDURE IF EXISTS `someSchema`.`sp_someSP`$$
CREATE  DEFINER=`someUser`@`someServer` PROCEDURE `someSchema`.`sp_someSP` (
	in uavname varchar(20)
SELECT, i.*, ll.*, g.*, c.*
FROM 	uav as u,
	imu as i,
        uav_ll as ll,
        gps as g,
        uav_controller as c
WHERE = uavname and = i.uav_id and = ll.uav_id and = g.uav_id and = c.uav_id


The main issue in my example above was that a delimiter (semi-colon in this case) was missing where the SQL statement finishes i.e. in the last WHERE condition. Here is a snippet of what the updated WHERE clause should look like.

WHERE = uavname and = i.uav_id and = ll.uav_id and = g.uav_id and = c.uav_id ; -- semicolon added here

Impressed with Doxygen

I have recently started using Doxygen in anger and have been quite impressed with it. In addition to the documentation of code that you would expect, one of the most powerful and coolest features is the ability to create various types of diagrams showing various aspects of the application such as collaboration diagrams object and call graphs, etc.

The easiest way to configure your application  is to use Doxywizard. On Linux, if you do want the object and call graphs then you would need to choose to enable the DOT option. If you do that you will need to have Message Sequence Charts installed (typically found in /usr/bin/mscgen) and also Graphviz. DOT can typically be found in /usr/bin/dot.

If you are on Windows and use Visual Studio, then there are a few add-ins which will work – with VS.NET 2005, 2008 and 2010; more details here.

Below is a simple example of a collaboration diagram taken from VTK project. You can find more samples. When you do browse the code, click on the Classes link – that is where you can see the various diagrams.

Sample Collaboration Diagram


I had a need to dump some data I am getting from a real-time sensor network to a database and I choose MySQL – just because it is cheap and cheerful and will fit perfectly with what I am looking for. Now, I have never programmed for MySQL though I have used it in the past as a consumer (e.g. the backend of this blog). MySQL does expose a C API that one can use, but it seems quite arcane to use and does not quite conform to the C++ style (especially when using STL).

It is at that point that I stumbled across MySQL++ – something I had not heard of and of course not used until now. MySQL++ is just a simple C++ wrapper around the same MySQL C API, but it does follow the C++ STL principles and feels more ‘natural’ to use. I am still playing with it and getting to know it.

Below is a quick sample on how to connect to a database and retrieve all the records from a table called ‘stock’.

#include "cmdline.h"
#include "printdata.h"

#include <mysql++.h>

#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char *argv[])
	// Get database access parameters from command line
        const char* db = 0, *server = 0, *user = 0, *pass = "";
	if (!parse_command_line(argc, argv, &db, &server, &user, &pass)) {
		return 1;

	// Connect to the sample database.
	mysqlpp::Connection conn(false);
	if (conn.connect(db, server, user, pass)) {
		// Retrieve the sample stock table set up by resetdb
		mysqlpp::Query query = conn.query("select * from stock");
		mysqlpp::StoreQueryResult res =;

		// Display results
		if (res) {
			// Display header
			cout << setw(31) << "Item" <<
					setw(10) << "Num" <<
					setw(10) << "Weight" <<
					setw(10) << "Price" <<
					"Date" << endl << endl;

			// Get each row in result set, and print its contents
			for (size_t i = 0; i < res.num_rows(); ++i) {
				cout << setw(30) << res[i]["item"] << ' ' <<
						setw(9) << res[i]["num"] << ' ' <<
						setw(9) << res[i]["weight"] << ' ' <<
						setw(9) << res[i]["price"] << ' ' <<
						setw(9) << res[i]["sdate"] <<
		else {
			cerr << "Failed to get stock table: " << query.error() << endl;
			return 1;

		return 0;
	else {
		cerr << "DB connection failed: " << conn.error() << endl;
		return 1;

invalid use of incomplete type ‘blah’

When you try and compile some code and you get an error along the lines of invalid use of an incomplete type ‘whatever type’ then in most cases it means you need to include the header file where that type is displayed.

For example I had the following events in my header file:

    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

When when I tried to compile gave the following error:
invalid use of incomplete type ‘struct QGraphicsSceneMouseEvent’

This was because the compiler could not find details of the struct and hence the details. To fix the problem I need to include the header.

This of course is similar to the initialized but not complete error but subtly different.

Finding an element in a list

Often you need to search through an array or list to find a specific element and of course you need this search to be as fast and efficient as possible. One of the best ways to do this is using a binary predicate function.

A binary function is a function object (which are also called Functors) and is any object which can be called as if it was a function. Depending on your language and platform of choice, Function objects are also known as callback functions, function pointers and delegates (.NET). Generally, there are three types of function objects:

  1. Generators – function with no arguments
  2. Unary Functions – function with one argument
  3. Binary Functions – functions with two arguments

A function object which takes one parameter (i.e. unary function) and returns a bool are treated as a special case and are  called Predicate functions.

How do we use it? Say we have a simple data structure called ContactData to represent a Contact in an Address book as shown in the code snippet below. We also define a predicate function called FindAContact. Now we need to use this predicate function and define another function called  findContact. The findContact function in turn uses find_if.  find_if takes three parameters, the start of the iterator, the last element and the predicate to use. It returns the first iterator it finds in a given range for which the predicate holds. If no matches are found then  the last element in the iterator is returned.

We also need to ensure we have the relevant includes for this to compile and link properly hence include’s below.

The code snippet below shows all that we have discussed.

#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

//Simple data structure
struct ContactData {
	string name;
	string addr1;
	string addr2;
	string addr3;
	string city;
	string postcode;
	string country;
	int workPhone;
	int homePhone;
	int mobilePhone;
	string workEmail;
	string homeEmail;

//I am lazy, create a typedef for the vector
typedef vector<ContactData> ContactDataArray;

// predicate function for rapidly searching the Contact data array
struct FindAContact: public std::binary_function<ContactData, std::string, bool>
	bool operator() (const ContactData &contact, const string &name) const
		return ( == name);

//If a contact is find it returns that; else returns the iterator's last element
ContactData Contact::findContact(string name)
	ContactDataArray::iterator it = find_if(addressBook.begin(),
						std::bind2nd(FindAContact(), name)

	return *it;

Printing code and making it look pretty

If you are on Linux and want to print some code and also make it look pretty then check out a2ps (Any to postscript filter). Of course if you can avoid printing in the first place and saving paper and trees and make it greener that is ideal – however there are times that is not possible. I tried printing from CDT, but the printing options from CDT just looks plain ugly and big fonts and can spread over 10 pages for a simple code file (spanning 293 lines). Sure I can tweak the font in CDT, but that is the only option available – enter a2ps. It seems to have more options, but I have not had a chance to play with those.

For example if I wanted a C++ code file called MOOSSniffer.cpp and “print it” out as PDF then use the command shown below. Here “-E” is the option to make the code look pretty and the “-P pdf” is the option for printing to PDF. Next comes the source file (you can also provide multiple files such as *.cpp) and finally the -o option is for the output filename. Of course you will need to install a2ps, which you can do via System -> Admin -> Synaptic Package Manager

a2ps -E -P pdf MOOSSniffer.cpp -o MOOSSniffer.pdf

Now, for some reason the resulting PDF could not be opened in Acrobat Reader, but on my Ubuntu machine, I could open it using the “Document Viewer” and print it using that. And in case you were curious, the pretty page option came to 3 pages instead of the original 10.

Also no trees were harmed in the making of this post – my printouts were all to PDF and not real paper – but in the end I did print out the 3 page version. 🙂

Ten commandments of Programming

I came across the Ten commandments of Programming while looking at a question on StackOverflow and I can’t believe I have not seen these before. I think every developer, lead, architect, dba, pm, whoever should print this out! 😎

  1. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry, so we can, and should, learn, laugh, and move on.
  2. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered.
  3. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed.
  4. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.
  5. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.
  6. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, not as some serious inconvenience to be fought.
  7. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect—so if you want respect in an egoless environment, cultivate knowledge.
  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you do turn out to be right, don’t take revenge or say, “I told you so” more than a few times at most, and don’t make your dearly departed idea a martyr or rallying cry.
  9. Don’t be “the guy in the room.” Don’t be the guy coding in the dark office emerging only to buy cola. The guy in the room is out of touch, out of sight, and out of control and has no place in an open, collaborative environment.
  10. Critique code instead of people—be kind to the coder, not to the code.As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.

Copying strings in C++

Here is a good example on why either you love C++ or hate it with such terse expression oriented code; I think its pretty cool.

If you want to copy one string to another, one option can be something like this.

void mycopy(char *p, char *q) {
	int len = strlen(q);

	for(int i=0; i&lt;=len; i++)
		p[i] = q[i];

However this achieves the same thing as above and is more efficient:

void mycopy(char *p, char *q) {
	while(*p++ = *q++);

Of course why would you write your own version when you have standard string copy fundtion strcpy in <string.h>

‘QPainter painter’ has initialiser but incomplete type

If you ever got an error something like [some-class] has initialiser but incomplete type, it basically means the compiler cannot understand the type and you need to add the include for it.

QPixmap pixmap(20,10);

QPainter painter(&pixmap);
QPen pen(Qt::blue);

Take the code snipped above when you compile it you might get an error something along the lines of the following for line 4.

‘QPainter painter’ has initialiser but incomplete type

To fix this you need to include the header file where QPainter is defined. The updated code looks like:

#include <qpainter.h>

QPixmap pixmap(20,10);

QPainter painter(&pixmap);
QPen pen(Qt::blue);