February 6, 2012 Leave a comment

Clever trick!

sermojohn's blog

Hi there!

Two days after my last post, I noticed that the example code from that post had been removed 😦
This is really bad, and proves me a bad tester! Hope to improve on this soon, which should be important for becoming a good blogger!

So, I decided to write a post in WordPress about writing posts on WordPress, which present any kind of source code! Sounds funny at first, but it is very useful for developers, who want to use the free version of the WordPress hosted blog to present examples of code to their subscribers! Thanks to a post on stackoverflow (http://stackoverflow.com/questions/1273647/how-do-i-add-syntax-highlighting-to-a-wordpress-blog-hosted-on-wordpress-com), I reached a link on the WordPress support site that described, how an internal code highlighting and formatting plug-in can be used, which is also available for the hosted WordPress version as well.

The obvious reason why WordPress strip off the source code…

View original post 83 more words

Categories: Uncategorized

Extending Internet Explorer – Scenario based overview

February 6, 2012 Leave a comment

For one of my projects, I was working on a minor enhancement. The project was web-based and as per client’s requirement, run only on Internet Explorer. The enhancement was related some data input page but access to any part of the site was restricted by a Login page.

The login page, as like any, consisted of a very minimal input – the username and password. But any change or recompiling on the site made me go from the login screen. Since it was a pretty old (almost a decade), it never had or no one bothered to put a “Remember me” check box. So logging in through the main screen was pretty customary.

I quickly considered the other alternative of hardcoding the values into the code, or at least till the release was made. But the idea of making temporary fixes to code for my pleasure nauseated me immediately.

What I was looking for, was a very efficient way to give me a quick form fill feature on the browser without having to mutilate the project in any possible way. May be Internet explorer had an option of extending itself! Fortunately it did and I finally figured out a way to do exactly that.

What would be the outcome? The outcome of this simple hack procedure would provide me with a new item on the Right click menu on Internet Explorer. On clicking upon such menu item, the fields on my form (website) would be auto filled with pre-set values.

Where all can I apply this hack? This procedure would specifically suit Internet Explorer browsers of versions anywhere in 6, 7 or 8. Although this has not been tested on very recent releases of Internet Explorer. If you’re using browsers like Chrome you have other ways of extending the browser functionality, this is just for my fellow developers like me who have no other browser to turn to except IE.

Can we get on to the hack already? Yeah sure.

All I need for this hack would be:

  • A registry entry
  • A simple javascript function

Registry entry: The whole purpose of the registry entry is to add the menu item to Internet Explorer’s context sensitive menu. As far as my knowledge goes, there isn’t a straight way of doing this than to go for a registry edit.

Warning: This section involves a registry edit. Altering registry settings without proper care might render the operating system useless. Kindly ensure necessary precautions before proceeding. Hazmat suits advised. Alternatively, you can visit this link to back up your registry settings.

  1. Enter regedit in your run command prompt.
  2. In the registry editor, navigate to the following tree-child.
  3. HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\
  4. Create a new key under this tree element, by any name “XYZ” of your choice.
  5. Under the registry item “XYZ”, add the following String Values as below:
  • String Value: CLSID
    • Value: A guid like {1FBA04EE-3024-11D2-8F1F-0000F87ABD16}
    • PS: You may use any GUID generator to get such a string
  • String Value: Menu Text
    • Value: My Menu Extension
    • PS: This text would appear on your Internet Explorer context sensitive menu.
  • String Value: Exec
    • Value: Path to the HTML file, you’ll be coding in the next section.
    • Example – C:\MyFolder\MyFile.html

JavaScript function:

  1. Place a simple javascript code to do the job of the form filling in a html file.
  2. Copy the location to this html file and place in the above registry item’s, Exec value.
  3. Restart your internet explorer
  4. Navigate to your page, a right click on it – you must see “My Menu Extension” on the right click menu.
  5. Click on it to perform the tasks you’ve coded in the javascript function. Or in this case, it would fill two textboxes txtUserId and txtPassword with corresponding values.
<Script language="JavaScript">
var parentwin = external.menuArguments;
parentwin.document.forms.txtUserId.value ="UserName";
parentwin.document.forms.txtPassword.value ="Password";

Well, that’s how I solved my requirement with a simple concept of extending Internet Explorer. The possible areas of further work I looked into were

  • Filling huge web-forms (repetitive tasks) for let’s say testing purposes with the ease of a right-click menu item
  • Automating using a excel macro to create the registry entries and their corresponding javascript function for different sets of values provided. Basically abstracting the user from the nitty gritties and allowing him just the final piece of cake.

For a very detailed look into various customizations on Internet Explorer, check this link

Regular Expressions – String manipulation simplified

February 1, 2012 Leave a comment

Regular Expressions are an amazing way to go. A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. Almost all languages support them and with a little understanding, you can ace at them. What more, they condense tens and thousands of lines of logic into just a couple of simple lines. I’ve used regular expressions both through .NET framework and in JavaScript and found them to be immensely helpful. This blog post focuses majorly on them and here’s a little outline on how I’ll be approaching the concept on hand.

  • A problem –  We engineers are problem solvers, so a simple problem followed by how regular expressions solved it in an even simpler way
  • Dissecting the solution – An understanding of the above simpler solution
  • Link to raw regular expression resources – Unless you can make up some of those regular expressions, you can never make it easier to use this language feature
  • RegEx class – The power of RegEx in .NET framework, what all you can achieve

Starting with this, followed by that, then this and then a dozen of that – A Problem!

I was given, the below problem statement and a laptop to code and solve. Developer instincts are hard to ignore and eventually I started scribbling off an elegant algorithm, or so I thought.

Domestic passport numbers either begin with the letter TW followed by 12 digits, or begin with 6 digits followed by 4 other characters and ending with the letters OFTW.

Pseudo logic:

  1. Is Starting With TW?
    1. Are the remaining 12 characters – digits?

i.      Return “Domestic”

  1. Is Ending with OFTW?
    1. Does it begin with 6 digits?

i.      Return “Domestic”

  1. If all above fails
    1. Return “Foreigner”

So with all the code logic and intricacies figured out, I exactly translate the pseudo code to C# code:

public bool IsDomestic(string PassportNumber)
if (PassportNumber.StartsWith("TW"))
string Rest=PassportNumber.Substring(2,12);
Int64 Result;
if (Int64.TryParse(Rest,out Result))
return true;
else if(PassportNumber.EndsWith("OFTW"))
string First6 = PassportNumber.Substring(0, 6);
Int64 Result;
if (Int64.TryParse(First6, out Result))
return true;
return false;

That’s when I was told; don’t you follow all the language features? Especially something called Regular Expressions?

Well, not to be an all knowing buff but yet, I knew what Regular Expression was and I perfectly knew how to use it. But surprisingly it never struck me. Given a problem, my initial mode of tackling it was to analytically approach it and solve. Although regular Expression’s way of doing it was straight opposite – it was elegant; and I hit myself why my mind didn’t think of it.

The Solution – Simpler one

So here’s the code, if I had used RegEx

public bool IsDomestic(string PassportNumber)
return Regex.Match(PassportNumber, "(TW)(\\d{12})($)|(\\d{6})([A-Za-z0-9]{4})(OFTW)($)").Success;

Surprisingly less lines of code, isn’t it?

Let’s dissect the solution

Without going into much deep, let me explain what the pattern (yes, I called it a pattern) means:


You see the pipe (|) symbol in the middle? Let me split the pattern at that part.

Left part: (TW)(\\d{12})($)

(TW) – Simply means that the two initial characters are TW

(\\d{12}) – tries to say that there are 12 digits following

($)– The string should end at the point, no more characters

Right part: (\\d{6})([A-Za-z0-9]{4})(OFTW)($)

(\\d{6}) – The first 6 characters are digits

([A-Za-z0-9]{4}) –  4 alphanumeric (A-Z or a-z or 0-9) characters would follow

(OFTW) – The next four characters would be OFTW

($)– The string should end at the point, no more characters – as we saw earlier

Did I miss the pipe (|)? You know what it is, it’s just an OR condition. The string in question, say TW012345678901 can choose to match with either the left part pattern or the right part pattern.

Some links before we proceed

This should have given you a basic idea into formulating a simple RegEx pattern; if you need further help you can visit http://www.regular-expressions.info/reference.html. It gives you a good glimpse on RegEx.

Or if you want a quick stop solution/pattern, visit Mark’s http://txt2re.com/, it’s an amazing site.

The almighty RegEx class of .NET

Let’s step back a bit and focus on the RegEx class in .NET framework, and see how better we can use it!

Check if a string is looking as it should

The above solution simply does that. The Match, IsMatch methods of the RegEx class tries to fits the given string into a pattern and says True, the string matches the pattern or False, the string looks nothing like the pattern! The simplest form of the method asks only for the pattern and the string.

Replace a questionable part in a string

Take for instance, the exclaimer. He gets too excited for nothing and you just need to dial his excitement down. How?

string SampleText = "This is Outrageous!!!!!!!! Regex can't solve all my problems!!!! What if it can!!!!!";

You can never track the count of the exclamations he has used (!) nor does he use a specific number all the time. The Replace method of Regex would help you there.

SampleText = Regex.Replace(SampleText, "(!)+", "!");

PS: The plus (+), here in the pattern says that the (!) can appear once or more in the string. And the last part is the replace with part. All questionable parts matching the pattern would be replaced with the input to the method.

This would give me an elegant output like thus:

This is Outrageous! Regex can’t solve all my problems! What if it can!

Pattern matching, only simpler:

Imagine how hard it was to match patterns or find the count of substrings actually matching a pattern you’re looking for. RegEx offers you an elegant way to the same, using RegEx.Matches. Let’s take the below statement.

“Are you working on any special projects at work? I am not reading any books right now. Aren’t you teaching at the university now?”

I need to fish out all the present-continuous forms verbs in them, i.e. the words ending with “ing”. Normally this would be a heavy code. But with RegEx we can do it faster and simpler using the pattern string “(\\b)(\\w+)(ing)(\\b)”

This says – in sequence,

\\b blank space
\\w+ [one or more] word character
ing The specific set of characters “ing”
\\b blank space
MatchCollection collObj=Regex.Matches(TestString, "(\\b)(\\w+)(ing)(\\b)");
foreach (var item in collObj)

Would print me out, all occurrences of the pattern, which are:





Through this post, I’ve summarized most of the key uses of RegEx with special emphasis on .NET code. Beyond a particular point, it depends on your creativity how you take it further to tailor the RegEx solution based on your problem. You can do away with ugly for loops or unnecessary if-else constructs in code.

The woes of a maintenance developer

January 30, 2012 Leave a comment

Call it a bad choice, fate or ill luck. Or all together – I’m struck. It has been almost a year since. I’ve learnt to live with it but the developer inside me keeps hurting. A huge code base of unmaintainable and stinking code (talk about code smells!) it’s like your nose itch when you’re hands are tied. What irritates me the most; I’ve borne the brunt, bitten the bullet and patiently made a little list:

Foul stench: Martin Fowler talks about Code Smell. It is a kind of a surface indication that is related to a bigger problem in the system. If you’re working on a maintenance project and your luck is at odds, then chances are it’s more than just a smell – It’s a stench! From ill-written [or no] comments, to insanely long method with ridiculous names it has everything. Let me quote a couple of examples, any idea what this method does?

public String ReturnString(String input)

It accepts a string input, opens an xml file, and loops through each tag, returns value of the tag matching the input. This goes on for almost all the tags in the xml file, i.e. the method is called a pretty 200 times each for each of the tag in the xml file. Didn’t expect that eh? Me neither, until I assumed it to be a piece of junk string to string conversion method and tried to chuck it off! This is just not it. As part of an optimization drive (I never learn from my mistakes), I fumbled upon the code below:

public void Method()     {
if(condition1) {
//1000 lines of code
if (condition2){
//exactly the same 1000 lines of code
//again, the same 1000 LOC

My heart cringed at the site of this and I refactored it into something very pretty and efficient. What happened next? Check the next section.

The Karma called Bug: Turns out that the 1000 lines of code had just one line (actually one variable) altered in each of the conditional blocks. And what’s worse, none of the tests covered and it was from the customer from whom the defect came.  Believe me; it took a good couple of days of code digging to figure out the source of a weird error.

So that’s the curse of an ill developed maintenance project. You are not to indulge in any refactoring unless you are ready to take full responsibility for any weird defect that may crop up, few minutes from now or few years from now or something that will never crop up.

Paralysis by Analysis: This is my favourite part. All through four years of graduate engineering study, you learn all tricks of the trade. From object oriented analysis design till may be even Artificial Intelligence. You learn all your skills and finally wind up as a maintenance developer filling scores of word documents and spreadsheets. I still vividly remember all those Impact analysis documents I filled out, none of which truly gauged the actual impact my two lines of code were going to make. Here’s a rough estimate of the whole saga of the release:

Requirements elicitation and clarification 3 days
Design – Detailed level with Impact analysis 10 days
Test plan preparation 5 days
Coding and Testing 10 days
Net number of LOC added – 5, just freakin’ 5

Hilarious isn’t it?

To sum up, here’s few points if you’re a maintenance developer – maintaining an ill-developed application:

  1. Thou shall not optimise
  2. Thou shall bear in mind that bug is inevitable
  3. When thy smells stinking code, remember rule 1
  4. Thou shall blame any defect on the developer or the previous maintainer whomsoever has left the organization
  5. Thou shall not crib

Parse a string as URL – HttpUtility

January 29, 2012 1 comment

A pretty neat requirement, automate using an application to go through an unattended mailbox and process the contents. Processing here simply meant to fetch a particular key identifier string the whole shebang that is the mail-body and cross check its presence in the database.

Everything sounded fine, except for the “Fetch a particular identifier”

A part of the entire mail-body was as below:

Identifier XYZ
Commodity Sugar
Date 12-12-2009

And we had the entire mail-body into a string.

String mail = Message.Body;

One of the developers instinctively suggested, let’s parse our way through “Identifier” substring and fetch the next available value. For me, it sounded a little tacky as the whole thing was in a table and to fetch the cell values based on such an algorithm sounded off to me.

I glanced a little down and my eyes fell on the URL that also had the identifier value XYZ. And as it turns out the mail generator generates the URL with the identifier values as a query string Id. Wah, now it was a piece of cake.

But to again go through the whole substring exercise sounded futile to me. I thought, okay now we have a URL why not programmatically fetch the identifier a query string, rather than parsing our way out. That’s when the following HttpUtility class helped us.

String strURLAddress;

strURLAddress = “http://www.sometempurl.com/page.aspx?id=XYZ&#8221;;


HttpUtility is a class part of System.Web namespace.

Here’s a link to the same tip on CodeProject – http://www.codeproject.com/Tips/304383/Treat-a-plain-string-as-URL-and-fetch-query-string

MSDN Link: http://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring.aspx


#20, What’s with India and Exotic foreigners?

January 26, 2012 Leave a comment

Yingluck Shinawatra. She would’ve been less famous in her country compared to here at India at this moment. Can anybody recall the last year’s guest for R-Day? You did? Well, Hats off to you. For those who did not, it was Susilo Bambang Yudhoyono – Indonesian President.

For the second time within a year, I reckon, we’ve gone mad trending over the attractive foreigner who visited our nation. (I’ll shortly return to the first time, just hold on) Just moments after the announcement or after her visit to India, couple of days ahead of R-Day, the first picture of her posing in front of the famous Taj Mahal floated around the Internet. I’d call that the first spark. We never knew about Thai leaders, let alone her. And suddenly the exotic foreigner, Ms. Shinawatra (Is she a Ms btw?) caught our attention.

We never lost a moment and immediately started discussing about her over any medium possible, especially twitter. Ms.Shinawatra is still trending you know! (May be not as herself, but as Thai PM) The discussion goes even as far to compare our septuagenarian male PM and regretting why our leadership isn’t attractive as others’? (True, couple of tweets did fret over that)

This isn’t a post to accuse anybody of anything. Yet, happening for the second time, this made me wonder. We’re from a land were Lakshman never bothered to look at an exotic Surpanakha, and foreigners like Ravan were projected as people who coveted foreign beauty (Sita).

Coming back the first similar incident – ever remember Hina Rabbani Khar, and how we went gaga over her visit to our land? 🙂

Categories: Personal

#19, An Interview at ThoughtWorks – Experience to share

November 25, 2011 13 comments

One of my colleagues mentioned about the “very different” recruitment process at ThoughtWorks. Something about writing code initially and further process based on modifications on the initial code. Well, that intrigued me! I’ve always wanted to be part of such innovative organizations. Hence, I took my first step of applying for the post Application Developer at their website.

As immediately as within two days, I get a call from HR at TW. Very pleasing gentleman, the call was pretty routine. From projects executed to my favourite pastimes, he inquired all. There was even a question on some of the awards I received. This went on for a while, and the HR on his part briefed about the recruitment process at TW. I vaguely had an idea, but I preferred to let him explain in detail. So here they were:

1.Logic Analytical thinking

2.Coding round for a problem provided

3.Pair Programming/Extension

4.Interview I

5.Interview II

Fine! I was very eager to start with the process. I was asked to drop in at their office* at a day of my comfort.

The first was the Logic test. I was given 11 flowchart problems. It was pretty simple but required intense concentration. I had to go back few questions once I completed all 11, just to see I’ve made mistakes. But I believe, when I handed over the booklet, I got most of it right. The HR dropped in 10 minutes later informing the candidates who cleared this round. (There were more than a dozen who were part of the process) Those who didn’t clear were asked to leave, of course courteously.

We met around for the Coding round, after a sumptuous lunch – courtesy TW. I was offered two choices – A game of life problem, a Sales Tax Problem (Feel free to Google, the Internet is full of them) I picked Sales Tax Problem, for one simple reason – It was more practical. I had been reading up about Calisthenics, Design Patterns and OODP. Hence, I perfected my code with as much good design as possible.

I left home after this exercise. The immediate next weekday, I get a response from the HR that I’ve been selected to go through to the next round. And my next visit to TW office was fixed.

The third part of the process – Pair Programming session. One of a seasoned ThoughtWorker met me with his laptop. We started with explaining my code, the philosophy of my design, etc… He asked me a few questions/doubts, few – Why this way and Why not the other way. Since we spent a lot of time on this, he chose to discount me of the huge extension to the code that was planned.

We chose a small extension. He left the floor to me, so that I can start designing the extension. I took the white-board and illustrated the new classes/behaviours that needed to be added. Then took to the laptop and started coding. The behaviour was simply to say True or False based on the condition if the string conforms to few conditions. To clear out my mind, I went ahead with pseudo code form of the logic. The code executed fine. He pointed out that it can be simplified using Regular Expressions, which I too realized but confessed that since I couldn’t recollect the expression type I didn’t venture into that. He confessed to the same, but since this was just an exercise we completed with a simple regular expression. He left the room, after a customary QA session with me.

Few minutes later, the HR came in. Briefed me that, although my design and analytical thinking was pretty good – my language skills (Not English, but C#) was not at par with my total experience. And I needed to focus on improving the language skills by more self-interest projects, etc… I politely agreed. And the HR walked me out of the office.

Overall the whole process was a great learning experience. I completed a record 5 design patterns in less than two weeks. And now I have a sense of direction as to what I should aspire for in my coding skills. Not to mention, I’d try to get back to TW after 6 month stipulated break.

*Office – Being at an organization which looks like a whole city, TW office seemed petite and cute. But what struck my notice where – Cubicle-less rooms (only the HR had cubicles) , Casual dress-code on a weekday and surprisingly no desktops.

Categories: Personal
%d bloggers like this: