Saturday, February 9, 2013

NDepend review… Coming up

Patrick Smacchia, the lead developer at NDepend, recently offered me an NDepend Professional license and asked for a review.

For years, I’ve heard a ton about NDepend but never got to use it for real. Today I installed NDepend and was hit in the face by a bunch of static analysis features that NDepend provides. It’s a pretty slick piece of software and would definitely require a good amount of digging on my part to actually be able to give a comprehensive review.

NDepend is amazingly helpful and first impressions have been really nice. First thing you notice is that it would be a key addition to any continuous integration environment. I look forward to exploring it in more detail.

So, until the review is published…. adios!

“Only what you need son”

..and the word “need” right there is marked in a monstrous bold font.

We look around today and almost everything is on sale. People and businesses want you to buy. They show you that something is available for half the price, tell you that you can buy something in installments, on *easy* EMIs. They want to buy things that you probably do not need.

It’s easy to get swayed into the craziness.

I’m only human. I too have my needs and wants. I look at such things and ask myself, “Do I want it or Do I need it?”. Only when the answer comes out as “I need it!”, do I ever think of buying that *thing*, whatever it may be. It’s a nice perspective to have.

I take my *wants* as luxuries. I sure can afford some luxuries, but I need to look way ahead into the future and make sure that the decisions that I make today do not, in any way, harm my tomorrow.

However, every once in a while you need to satisfy at least one “want” that keeps your morale high and gets you through this unfair life, and hope and pray that it gets better one day at a time.

Monday, February 6, 2012

NCrunch, The Incredible TDD Tool!

I've been meaning to evaluate and review some development tools since forever. I think I waited so long just because I never found a tool that grabbed my attention to a level where it could really get me on my butt and make me jot down a review. Well, now we have such an awesomized tool - NCrunch!



Calling NCrunch just another TDD tool would be terrible injustice to it's developers.

NCrunch is -
  • An automated parallel continuous testing tool for Visual Studio.
  • A code coverage analyzer
  • A performance analyzer
  • And last, but not the least, incredibly smart!
Think about the usual steps you go through with test driven development:
  • Write test
  • Build and run tests
  • Write code
  • Build and run tests
  • Refactor code
  • Build and run tests
As a highly optimised test runner, NCrunch can knock half of these steps away by automating them completely - so you end up with:
  • Write test
  • Write code
  • Refactor code
Yes! The tests are automatically built and run in the background. Continuous feedback is provided on the fly, thereby making test development easier. As soon as the tests are build-able, NCrunch runs the tests and provides immediate feedback. Writing assertions is a pleasure!

And there's much more apart from this main feature. But, let's look at how a developer would use NCrunch. Here, we have written a simple test.


The view above shows the normal view that a developer shall have when NCrunch is disabled. Go ahead and enable NCrunch. Go to NCrunch -> Enable NCrunch. And now you see your editor shows something like this. Note that we have defined a default implementation for the Add() method that returns zero.


We shall go back and fix the method Add(). Also, you don't even need to save your files for NCrunch to be able to run your tests!


We now add another test to our suite.


While writing the test however, we see an error. This is because the test is wrong! Correct the test! I just love this level of immediate feedback! Hover over the red cross mark and it shows you a tooltip that tells you exactly what went wrong. (Click on image to view)


Fix the failing test and everything shows green again! NCrunch also handles exceptions gracefully and the tooltips indicate which exception occurred and where.

Code Coverage
The lines of code marked green indicate the parts of code that are covered by tests. This makes it very easy to spot areas that have not been covered yet, write covering code or eliminating any dead code. The following tooltip on the test tells you that the test is covered by 1 passing test.



Performance metrics
NCrunch also provides information about performance metrics and hot-spots in the tested code, thereby allowing you to identify parts of code that might induce a performance problem in the long run. The previous figure shows you the execution time of the test. The next figure shows you that the method being tested is too slow.


The yellow marker indicates that the code is executing really slow and that you should take a look to see if that's normal.

What frameworks does NCrunch support?
Supported testing frameworks are:
  • NUnit
  • MS Test
  • Xunit
  • MbUnit
  • MSpec
Supported languages and .NET versions are:
  • C#
  • VB.NET
  • F#
  • .NET Framework v2.0 and above
  • Visual Studio 2008
  • Visual Studio 2010
  • Visual Studio 11 Developer Preview
Pricing?
I'm sure that there has been a huge level of effort that has gone into developing this tool. But, the software is free to be used as long as it is in beta. Let's hope that on release the developers will price it economically.

There's a lot of other stuff that NCrunch supports that would make your life a wee bit easier. Go check out the NCrunch blog for updates! I really hope that this tool becomes a standard in everyday development for most software development firms.

Have fun with NCrunch!

Links:
NCrunch main website - http://www.ncrunch.net/
NCrunch Download - http://www.ncrunch.net/download.htm
NCrunch on Visual Studio Code Gallery - http://visualstudiogallery.msdn.microsoft.com/6946579c-c7d9-48ce-b039-994d30b85116

Saturday, February 4, 2012

IBM Research | Ponder This - IBM's monthly mathematical puzzles

A few days ago I came across this website by IBM - IBM Research | Ponder This. I'm no big fan of solving insane mathematical puzzles that boggle the mind. But, I really liked the level of the complexity these problems have. It has been going on for quite some time.

I've always wondered what the reason could be for such a huge corporation to run such mathematical puzzles. Maybe they are unable to solve these problems and want help from people. That would be funny. They can easily get other people to solve their problems for practically nothing.

I'm definitely not able to solve any of these problems yet. But, you might - if you're really know your math. Looks like they just posted a new one for February 2012. All the best!

Friday, February 3, 2012

Write to a console window from a Windows application

Ever wondered how you could write out to a separate console window from your Windows application rather than writing to a log file? You might need to do that for a number of reasons – mostly related to debugging. Here’s how you do it:

Predefined APIs are available in kernel32.dll that will allow you to write to a console.

AllocConsole

FreeConsole

AttachConsole

AllocConsole() attaches your process to a console window where the process’ standard output will be redirected. A process can be associated with only one console, so the AllocConsole() function fails if the calling process is already associated with a console. FreeConsole() is used to detach the process from the current console and AttachConsole() can be used to attach associate a console with the current process.

The following shows a sample usage of the feature.
private void button1_Click(object sender, EventArgs e)
{
    new Thread(new ThreadStart(delegate()
    {
        AllocConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        FreeConsole();
    })).Start();
}

You’ll need to import the AllocConsole and FreeConsole API from kernel32.dll.
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();

[DllImport("kernel32.dll")]
public static extern bool FreeConsole();

And you can always make it Conditional if you want to use it only while debugging.
private void button1_Click(object sender, EventArgs e)
{
    new Thread(new ThreadStart(delegate()
    {
        AllocateConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        DeallocateConsole();
    })).Start();
}

[Conditional("DEBUG")]
private void AllocateConsole()
{
    AllocConsole();
}

[Conditional("DEBUG")]
private void DeallocateConsole()
{
    FreeConsole();
}

Monday, January 30, 2012

VSX Add-in Development Adventures: Window.Object returns NULL

I’m in the middle of developing an add-in for Visual Studio 2008, a simple one that would help our in-house code review process. If you’ve ever written a VS add-in, you’d know the basic routine – Visual Studio creates the basic class Connect derived from IDTExtensibility2, then you put in your code in the methods OnConnection, OnDisconnection, OnAddInsUpdate, OnStartUpComplete and OnBeginShutdown.

I developed a few user controls (UserControl objects) for showing some UI as tool windows. One of them was AddCommentView which is just a dumb UserControl that displays some textboxes and buttons and also takes in some input. I deployed this control as a separate DLL and linked it to the add-in. Then, as usual, the following code should do the job of creating the tool window.
if (_addCommentWindow == null)   
{    
    object objTemp = null;    
    string guid = Guid.NewGuid().ToString();    
    Window2 toolWins = (Window2) this._applicationObject.Windows;

    // Create the tool window view for adding the comment   
    _addCommentWindow = toolWins.CreateToolWindow2(_addinInstance, "Controls.dll", 
        "Controls.AddCommentView", "Add Comment", "{" + guid + "}", ref objTemp);
}    

And like always it worked just fine till I tried to test it and that’s when I realized something wasn’t quite right.
The CreateToolWindow2 method has two outputs – the tool window (which is returned by the method) and the hosted user control (the ref parameter ‘objTemp’ in this case). The hosted user control can also be retrieved through the Window.Object property of the returned tool window. The problem was – no matter what I tried the Window.Object property always returned null and so did ‘objTemp’.
AddCommentView addCommentViewControl = _addCommentWindow.Object as AddCommentView;   
addCommentViewControl.StartLine = selection.AnchorPoint.Line;    
addCommentViewControl.EndLine = selection.ActivePoint.Line;

The solution – I was acting dumb, very dumb. Visual Studio requires all hosted controls to be visible to COM. After adding the attribute to the entire assembly using [assembly: ComVisible(true)] , everything started working like a charm (you can apply it even to the individual control if you don’t want to make the entire assembly COMVisible).

Defining custom Dictionary keys in C#

Ever so often we come across cases where we need to store objects mapped to other objects in a Dictionary. And in most of these cases, the default solution of using the object reference as a key doesn’t really work. For example, if an object Person { Name = “Foo” } is mapped to value ‘x’, another object Person { Name = “Foo” } does not get us to the value ‘x’, although we probably would expect it to return ‘x’.
class Person    
{     
    public int Age { get; set; }     
    public string Name { get; set; }     
}

class Program    
{     
    static void Main(string[] args)     
    {     
        var p1 = new Person() { Age = 30, Name = "p1" };     
        var p2 = new Person() { Age = 31, Name = "p2" };     
        var p3 = new Person() { Age = 32, Name = "p3" };
        var personVsBonus = new Dictionary<Person, int>();    
        personVsBonus[p1] = 1000;     
        personVsBonus[p2] = 2000;     
        personVsBonus[p3] = 3000;
        var personToFind = new Person() { Age = 31, Name = "p2" };    
        Console.WriteLine(personToFind.Name + " will be given a bonus of " + personVsBonus[personToFind]);     
    }     
}     

The above program gives throws a KeyNotFoundException as the dictionary was not able to locate the entry searched as it was doing a reference comparison.
In such cases you need to define your own implementation of what the dictionary should consider as the key value. In the example we just discussed, we might like the property Person.Name to be considered as the key. Whenever a dictionary needs to decide where an item should be located, it calls GetHashCode(), whose return value decides where the item shall be stored. If GetHashCode() returns the same value for two different objects, the Equals() method is called with both objects being compared. The result of the Equals() method tells the dictionary whether the objects are the same or different.


Solution 1:
Implement the IEquatable interface for the Person class. This means that, “Hey, now the Person object will tell you whether it is the same as another Person object!”. You also need to override the Object.GetHashCode() method and write a good hash generating algorithm that generates unique values (int). Here, I use a simple method that just returns the length of the person’s name.
    class Person : IEquatable<Person>
    {
        public int Age { get; set; }
        public string Name { get; set; }
 
        #region IEquatable<Person> Members
 
        public bool Equals(Person other)
        {
            return this.Age.Equals(other.Age) 
                && this.Name.Equals(other.Name);
        }
 
        #endregion
 
        public override int GetHashCode()
        {
            return this.Name.Length;
        }
    }

Run the program after making these additions and the program works fine. The dictionary is now able to find appropriate values.

Solution 2:
There will be times when the key type might be a sealed type or you might not be allowed to change the key object’s properties. The Dictionary type provides us the IEqualityComparer interface that we can implement to provide our custom definitions based on the key object’s properties without having to modify the key’s properties.

Here is the modified code:

    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
 
    class PersonEqualityComparer : IEqualityComparer<Person>
    {
        #region IEqualityComparer<Person> Members
 
        public bool Equals(Person x, Person y)
        {
            return x.Age.Equals(y.Age)
                && x.Name.Equals(y.Name);
        }
 
        public int GetHashCode(Person obj)
        {
            return obj.Name.Length;
        }
 
        #endregion
    }

Also remember to use the comparer object while creating the dictionary.

var personVsBonus = new Dictionary<Person, int>(new PersonEqualityComparer());

Run the program after making these changes and the program works just fine!

The most important thing to remember here is that your definition of GetHashCode() shall decide how fast your dictionary can lookup an entry. Be very careful while taking these solutions into consideration as weak hash generation might lead you to long-term scalability issues where the dictionary might take more and more time to lookup entries in large dictionaries.