Friday, December 28, 2007

Foreach in C# uses ducktype

This came to me as little surprise. May be for others too.. including my manager with whom I had discussion about this once.

So far I was under the impression that for any class to be used inside foreach, it must implement IEnumrable interface. I remember myself asking this question in interview to many guys and even answered same question in the interview when I was on other side of the interview table.

Today I am going to proove that its not true anymore.... (what??????)

Well, all you need for your class to be used inside foreach is
  • have GetEnumrator method with no input params and return type object which has two method MoveNext (returns bool) and property Current with getter (returns object)
Still not want to believe me? well here is the code snippet
using System;

namespace ForEachDemo
public class Program
private static void Main(string[] args)
// the following complies just fine:

Person[] peopleArray = new Person[3]
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),

People peopleList = new People(peopleArray);
Console.WriteLine("This program demostrate usage of foreach without implementing IEnumerable interface.");
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);

Console.WriteLine("Press return key to exit...");

public class People
private Person[] _people;

public People(Person[] persons)
_people = persons;

public PeopleEnum GetEnumerator()
return new PeopleEnum(_people);

public class PeopleEnum
private Person[] _people;

// Enumerators are positioned before the first element
// until the first MoveNext() call.
private int position = -1;

public PeopleEnum(Person[] list)
_people = list;

public bool MoveNext()
return (position < _people.Length);

public void Reset()
position = -1;

public object Current
return _people[position];
catch (IndexOutOfRangeException)
throw new InvalidOperationException();

public class Person
public Person(string fName, string lName)
firstName = fName;
lastName = lName;

public string firstName;
public string lastName;

just copy paste this in empty console app and look at the result. You will be more than surprised to see what is happening....

Obvious question you might want to ask here is what the F**k is going on here. The answer to this is foreach in C# (may be even VB.NET, I didn't tried my self) uses ducktype.

Develop smartly:)

NUnit 2.4 is here with support to VS2008 and RowTest

This is really cool. So far NUnit was legging one cool feature of MBUnit - RowTest

Not any more. NUnit 2.4 is here to kick that legging :)

IDE support is included as extension in Test Driven .NET 2.11. you can download from here. Row extension binary is here

Click on one for 2.4.5 and the zip file will have two dlls (NUnitExtension.RowTest.AddIn.dll and NUnitExtension.RowTest.dll )

After you install Test Driven .NET 2.11, navigate to '%ProgramFiles%\TestDriven.NET 2.0\NUnit\2.4' and create subdirectory called addins. Then copy NUnitExtension.RowTest.AddIn.dll inside addins. Its is required that you don't keep any other non dll file in this folder. Click here to know why?

Finally use NUnitExtension.RowTest.dll as your BinRef in the UnitTest or IntegrationTest Project.

Now writing test is very simple. Here is the snippet

using NUnitExtension.RowTest;

namespace Mahendra
public class RowTestDemoTester
public void Simple_Addition_Test(int a, int b, int sum)
Assert.AreEqual(sum, a+b);

What is even cool is, once you install 2.11, right click on your test project and you will see under Test With submenu -> all your previous installation of NUnit as well. i.e. in my case it is NUnit 2.2 and NUnit 2.4

If you choose to test using NUnit 2.2 (any one prior to NUnit2.4) all the RowTest will be simply ignored without giving any compilation error or failing test.

Develop smartly :)

Thursday, December 27, 2007

T-SQL hacks, getting Nth highest, top N and paging

Its time for T-SQL

Some of the common scenario for data retrieval could be (without using TOP keyword remember oracle doesn't have TOP)
  • Getting Nth highest/lowest value column
  • Getting top Nth highest/lowest value columns
  • For paging purpose, getting X row for page n i.e. getting column 11 to 20)
Here is some of my hecks for obtaining above results. I have used NorthWind orders table for this purpose.

For bullet point 1: Getting Nth highest, here is the t-sql
select * from orders a
where N-1 =
(select count(orderID) from orders b where b.orderid > a.orderid)

trick here is self join. Notice closely here what I am doing.
  1. For each row of inner table (alias b) get count of columns from the same table i.e. self join, who has value higher than current row of outer table.
  2. Use common math like this: for any column, in outer table, to be Nth highest, it must be lower than N-1 columns of inner table.
  3. Select that row. It is your Nth highest row
Apply same logistic and you get N highest/lowest row like this
--TOP N highest
select * from orders a where 10 >
(select count(orderID) from orders b where b.orderid > a.orderid) order by orderid desc

--TOP N lowest
select * from orders a where 10 >
(select count(orderID) from orders b where b.orderid < a.orderid)

The only difference between last two queries are inner query condition. By same methodology mentioned above, first query is looking for number of columns having higher value, second one looks for number of column having lower value.

Well well well....
so what is the practical use of all this crap then? Hmmmm....
May be the answer is bullet point number 3 : For paging purpose, getting X row for page n i.e. getting column 11 to 20)

Now I am applying above logic in two fold to get rows for paging .

My input here would be page size and index of the page (1,2,3 base).
Logic here is to get 11 to 20 row, first get 1 to 20 and then filter out 1 to 10

Here is the query
declare @page_size int, @page_number int

set @page_size = 10
set @page_number = 3

select * from orders a
where @page_size*@page_number >
(select count(orderID) from orders b where b.orderid > a.orderid)
and not exists
(select c.orderid from orders c
where @page_size*(@page_number-1) >
(select count(orderID) from orders d where c.orderid < d.orderid)
and a.orderid = c.orderid
order by orderid desc

Again, I know some of the results above can be obtained easily with sql 2k5 (i haven't spoiled my hand with this yet though) and up,this exercise is to strengthen understanding of how select gets executed. The whole logic is to closely understand execution of query and thereby manipulating it to get desired result. Alternatively it can be helpful as interview question for either side of the table :)

Setting up wireless router

This time nothing my own creation. I was setting up my wireless router for the first time and was concern about security stuffs as wireless is more vulnerable to hacking. I can to this page. Sounds interesting reference to me. May be it can help somebody else too.

Tuesday, July 24, 2007

Beginner's guide to Scrum

Its almost 2 month, since I promise to post more about scrum methodology. Never got chance to write on this till date. None the less, here goes begginers guide

Scrum is yet another s/w methodology which focus more on interaction and colloboration amongs team. Here team doesnt simply mean group of developer/tester and architect but also project manager and business stack holders (or atleast some representatives of them).

Before we can proceed any further here is introduction of few terms
  • User Stories: mini card which describe feature of application, give it a name.
  • Product Backlog: List of all user stories which together implies functionality required by our application, listed in decending order of priority.
  • Sprint: Development Iteration, typically 1-3 weeks time. At the end of which development team comes up with demo of what has been implemented.
  • Sprint Backlog: Document which includes top priority stories out of product catelog which needs to be implemented in next/current sprint.
  • Story Points: Measure used for estimating size of user story.
  • Velocity: Number of story points that can be implemented by given team in single sprint.
  • Focus Factor: Fraction of Idle time, development team is expected to spent on implementation of current sprint backlog items.
  • Burndown chart: Pictorial representation of how many story points have been left, at any point of time during sprint.
With this knowledge lets move forward and state how they fit into day to day work.
At the very begining of project business stack holders, project manger and developers(part of the team if full team is not in place yet) come to user strory writting workshop. Input point for this workshop is user expection from the user and outcome is product backlog. While its true that end user know this part better, its important to involve developer as well since they are the one who comes up with non-funcitonal requirements during this workshop. (i.e. security and performance requirement).

Well if that sounds like requirement gathering phase of Waterfall method, wait a minute. Best part here is, this backlog is not static read only document. It just guides team to the right path. Depending upon visiblity and upcoming ideas during sprint, stack holders can come up with new features, droping certain part and product manger will readjust backlog iteam based on know priority at that point of time.

Once this gourd work is in place development team's work is very straightforward. Decide sprint duration and velocity (Initiate with trail and error method, adjust it until team is comfortable with it).

Now is time for sprint planning meeting.

Attendees for this meeting are stack holders, project manger and development team (by the way development team also includes testing people). Team starts by taking first item of product backlog, clarify what is the scope of this story, estimate it in terms of story points and putting it in current sprint backlog. This process contines till sprint backlog is populated with items whose estimation sums up to agreed velocity for this sprint.) Original story can be further segregated into multiple stories in this planning meeting as well as two or more stories can be combined to one. Nothing is hard and fast here. Flexibility is everywhere:). One important piece of information against each story is "step to demostrate". Together team indetify step to demostrate completion of that story.

With sprint backlog in place, developers task is to grab one story and start implementing till all the stories are done.(Developer can always pick up phone and dial to business owner should there be any doubt during implementation of any story and story can even be changed at this point if that makes sense to business). At the end of sprint, team meets again and performs those agreed upon steps to verify completion of user story. Any finding at this point will be included in product backlog and again starts game of planning next sprint. This game continues till business owners are satisfied with the system or they run out of budget to develop any further.

What are the benefits fo this approch???? Well there are many but someof them I would like to point out are
  • High degree of flexibility and adoptability is clear visible benefits.
  • Making sure that team works on high priority features always.
  • Highly recommend for development project where end user can't envise full set of functionality at the very begining.
  • Continues feedback by user rather than waiting till end which enables early correction.
  • Cost of changing is low and doesn't increase exponetioally with project duration.
  • Continueous collobaration between stack holder/user and developer ensures end product which meets user requiement.

Friday, May 4, 2007

Paradigm shift from Unified Process to Scrum

Till now, we all were talking about Unified Process and how well it fits into process driven software development. After all its all about following those stringent processes very strickly and rest is just done for you. These are the process which puts your organization at the status were you can claim to repeat your success every single time.

Hey but wait a minute... Aren't we really lieing to our self? Almost after decade of process driven cycles, and those big big claims of being process dependent aren't we really really depends upon one or more individual's skill to make it happen. After all if its process driven than why not to stop employeeing people and let your so called process does the job.

Todays fact is ; we do depends upon people, not process, to make our project a success. is all people and getting agile. It focuses more on Individual and Interaction over processes and running software over comprehensive documentation. To scrum responding to change is more important than negotiating for contracts.

So how does it work? Pretty simple... it follows KISS protocol..
K I S S = Keep It Simple Stupid

Ever heard customer comment, something like "Hey, your software is great but not what I wanted it to be"?. Well, this is more of a common than exception when we work on the assumption that customer knows everything. In reality Customers are not very decisive at the very begining of the project and this is fair enough since they don't have any ground yet base on which they can make solid (non-volatile) decisions.

Scrum is meant to handle this situation. Here team works in small iteration called SPRINT (typically 2-4 weeks). It all starts by a meeting called Sprint planning (typically 1 day) and the product owner, stack holders and team; all together find out what needs to be done over next 2-4 week and how to verify that its done (Acceptance criteria). Once this is done, team starts working on implementing those features (User Sotries in scrum methodology) which are required in current sprint cycle. Last day of the sprint is sprint demo, where one of the team member demostrates all the features. and the cycle repeats for the next sprint

The obvious advantage here is stack holders have base to make there next decision based on which they can rectify or mold the direction of the project rather than waiting till the end.

watch this space.....more on scrum and how it works.. sometime later.. :)