Crack ThoughtWorks Minesweeper challenge

ThoughtWorks is awesome!!!.

ThoughtWorks interview process is one of the most difficult IT interview process. There would be a coding round where you have to design a solution for the problem given by them. Your solution can be developed in any programming language but it should be flexible in design to adapt new requirements in future.

For me it was to design a Minesweeper game.

You can checkout the source code for more details.

Advertisement

Rating control in WPF

This article gives you a step by step walkthrough how to create a Rating control like below in WPF. If you are new to custom control development, here is an excellent article to get the basic idea on Custom control development.

Rating2

Before we start, It is always good to separate custom controls from the project and maintain as a class library. I prefer below project structure for a custom control library.

Rating1

If a resource is not defined for a specific theme, then the control checks Classic.xaml for the resource. If the resource is not defined in the file that corresponds to the current theme or in Classic.xaml, the control uses the generic resource, which is in a resource dictionary file named generic.xaml.

Also it is very important that from where your components are derived. Here the Rating control is derived from ItemsControl, each ItemContainer will be replaced by a star symbol which is a ContentControl. This is achieved by overriding the GetContainerForItemOverride method.

 protected override DependencyObject GetContainerForItemOverride()
 {
    return new RatingItem();
 }

Rating control exposes RatingItemLimit, RatingItemBackground, RatingItemHighlightColor, RatingItemMouseDownColor and RatingValue properties to interact with the control.

<controls:Rating Width="250"
                 Height="20"
                 RatingItemLimit="10"
                 RaingItemBackground="Red"
                 RatingItemHighlightColor="Green"
                 RatingItemMouseDownColor="Black"
                 RatingValue="2.6">
</controls:Rating>

 

Get the complete source code here.

Multivalue Dictionary in C#

Microsoft BCL team has released a new collection type called MultiValueDictionary which is now available in NuGet repository as a Microsoft.Experimental.Collections package. You can install this NuGet package through Package Manager Console using below command.

PM> Install-Package Microsoft.Experimental.Collections -Pre

We have already a collection type called Dictionary<TKey, TValue> to store data in the form of Key, Value pair. nice !!!.  But I have a requirement to store multiple Values for the same Key, something like below.

Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, “Item 1”);
dictionary.Add(1, “Item 2”);

The problem here is, Dictionary should not allow you to add the same Key multiple times. So I have to write something like below.

Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>();
dictionary.Add(1, new List<string>(){“Item 1”, “Item 2”}); 

Fixed it :),

But the MultiValueDictionary  is more akin to a Dictionary<TKey, IReadOnlyCollection<TValue>> with a number of methods to enable the easy modification of the internal IReadOnlyCollection, also simplifies the above approach.

MultiValueDictionary<int, string> multiValueDictionary =new MultiValueDictionary<int, string>();
multiValueDictionary.Add(1, “Vimal”);
multiValueDictionary.Add(1, “CK”);
multiValueDictionary.Add(2, “vimkum”);

MultiValueDictionary allows you to add same key multiple times, but  it internally maintains a IReadOnlyCollection<TValue> to store values of the same key.

Console.WriteLine(“Items inside my Dictionary {0}”, multiValueDictionray.Count);

//Output : Total items inside my Dictionary : 2

foreach(var item in multiValueDictionary[1])
{
  Console.WriteLine(item);
}

//Output : Vimal
CK

Understanding Common Problems of Task Programming

TPL is one of the best tool now available in .Net framework to do Parallel Programming which helps developers to create and initiate Tasks in a simple and clean way. Below is the one way to create a simple task.

Task task = new Task(() => Console.WriteLine("My Task")); 
task.Start();

and the other is by using the StartNew method of TaskFactory which creates and starts a new Task.

Task.Factory.StartNew(() => Console.WriteLine("My Task"));

The question is when and why would use one approach versus the other? A Task can start only once, and we need to ensure that multiples calls to taks’s Start method from multiple threads concurrently will only result in the task being scheduled once. This requires synchronization, and synchronization has a cost. if you use Task.Fatory.StartNew, the task will creates and starts at that moment itself and it is no longer possible for threads to race to call Start, also the StartNew method avoids the additional synchronization cost. If you want to know how Microsoft did this,  go here  [takes seconds :)]. Below are the some important points to remember when you deals with Task Programming.

Task Dependency Deadlock

If two or more Tasks depend on each other to complete, none can be move forward without the others, so a deadlock occurs. The only way to avoid this problem is to ensure that your Tasks do not depend on one another. This requires careful attention when writing your Tasks bodies and through testing

Local Variable Evaluation

Assume that you create a series of Tasks in a for loop and refer to the loop counter in your lambda expressions. All of the Tasks end up with the same value because of the way that the C# variable scoping rules are applied to lambda expressions. The simplest way to fix this problem is to pass the loop counter in as a state object to the Task like below.

            BankAccount bankAccount = new BankAccount();
            Task[] tasks = new Task[10];
            for (int i = 0; i < 10; i++)
            {
                tasks[i] = new Task((stateObject) =>
                {
                    int isolatedBalance = (int)stateObject;
                    for (int j = 0; j < 1000; j++)
                    {
                        isolatedBalance++;
                    }
                    return isolatedBalance;
                }, bankAccount.Balance);

                tasks[i].Start();
            }

Excessive Spinning

Many programmers overestimate the performance impact of a Task waiting (either via Thread.Sleep() or by using a CancellationToken wait handle) and use spin waiting instead (through the Thread.SpinWait() method or by entering a code loop). For anything other than exceptionally short waits, spin waiting and code loops will cripple the performance of your parallel program, because avoiding a wait also avoids freeing up a thread for execution

Don’t Synchronize Too Much

Most programmers write the program structure as though they planned for sequential execution and apply parallel features later. Data races arise, which are then fixed using synchronization applied like a Band-Aid. Because the program was designed for sequential use, the programmer finds it hard to synchronize with any granularity and ends up synchronizing everything. synchronization has a cost and can reduce performance. Synchronizing with a heavy hand means that your code will end up running restricting parallelism but still incur the synchronization overheads.

Don’t Synchronize Too Little

A program with too much synchronization is to overcompensate and use too little. Now, we end up with a program that performs well because the number of synchronization points is drastically reduced but doesn’t protect all of the shared data and so suffers from data races.

Pick the Lightest Tool

The .NET Framework includes synchronization primitives from the classic, also some new primitives introduced as part of the TPL. The new primitives are more efficient, but some of them lack useful features available in the heavyweight older primitives. You should pick the most efficient primitive that meets your program requirements.

Don’t Write Your Own Synchronization Primitives

At some point, every parallel programmer struggles to use a particular synchronization primitive in a particular way and thinks, “I should write my own.” You will have those thoughts, too. Don’t do it; don’t write your own. I guarantee you that you will end up making things much worse. Synchronization primitives are very difficult to write correctly. Most of the primitives in the .NET Framework rely on features of the operating system and, in some cases, of the machine hardware. My opinion to you is to change the code whenever you can’t get one of the .NET primitives to fit in with your code.

Interface Behaves Differently in Visual Basic

Learning programming language design or framework internals is a bit interesting!!!.

On a project development phase, my guru came up with a situation where Interface behaves a bit strange. In Visual Basic we can implement an interface member with a private method, and then call that method via the interface.

ahh!!, So what then does “Private” means?

This implementation violates the concept “Encapsulation” right?

The question in detail is available on StackOverflow :

http://stackoverflow.com/questions/18879142/interface-behavior-is-dfferent-in-vb-net

This feature of VB and C# makes developers confused!!!

Here is an awesome explanation of Eric Lippert from Microsoft, who was a developer of the Visual Basic, VBScript, JScript and C# compilers and a member of the C# language design committee.

http://goo.gl/prNL7c

Beware : Some times “Named Parameter” may cheat you

An another weekend!..

It has been a long time i am thinking to write an interesting article on C# programming. Here is an interesting post on Named Parameter, the thread is from a technical discussion happned between my collegue jameel and me 🙂

Let’s look into this sample

 class Program
    {
        static void Main(string[] args)
        {
            var man = new Man();
            var human = (Human)man;
            man.Calculate(x: 1, y: 2);
            human.Calculate(x: 1, y: 2);
            Console.ReadKey();
        }

        public class Human
        {
            public virtual void Calculate(int x, int y)
            {
                Console.WriteLine("Human Calculating X :{0} and Y:{1}", x, y);
            }
        }
        public class Man : Human
        {
            public override void Calculate(int y, int x)
            {
                Console.WriteLine("Man Calculating X :{0} and Y:{1}", x, y);
            }
        }
    }

The lines highligted as red would call the “Calculate” method of both Human and Man object which prints the values x and y respectively.

What would be the output?  Can you guess a little? 🙂

"Man Calculating X :1 and Y:2"
"Man Calculating X :1 and Y:2"

If your answer resulted as above, then i am sorry :(. It’s absolutly wrong… You have cheated by Named Parameter :). The correct answer is

"Man Calculating X :1 and Y:2"
"Man Calculating X :2 and Y:1"

Now you might be thinking, what the hell this guy is talking?.

Dont’ know… sometimes i may be like this. moreover programming is a fun. Let’s talk why it’s happening like this.

Argument binding for the method call Human.Calculate(x: 1, y: 2) is done at compile time, but method dispatch is done at runtime because the method is virtual.

In order to compile the method call, the compiler sees x: 1, y: 2 and needs to resolve this named argument list to a sequentially indexed argument list in order to emit the appropriate IL (push the arguments on the stack in the right order, then call method).

In addition to the named argument list there is one more piece of information available to the compiler: the type of human, which is Human. Now me and you both know that at runtime this is going to be a Man instance, but the compiler doesn’t know that. So it looks up the parameter list of human.Calculate and sees that x is the first argument, y is the second. This makes it compile your code as if you had written

human.Calculate(1, 2);

At runtime, the arguments 1 and 2 are pushed on the stack and a virtual call is made to Calculate. Of course this ends up calling Man.Calculate, but the parameter names have not survived the transition to runtime. Man.Calculate accepts 1 as its first argument (y) and 2 as its second argument (x), leading to the observed result.

As an aside, this is also what happens when you use default argument values.

Do we really need “Debugger Customization”?

Application debugging is one of the most interesting part in a software development cycle. At the same time it faces some difficulties, Microsoft has already provided a couple of good features to overcome these problems and it helps developer to experience a smooth debugging session. Visual Studio provides a number of good features like Immediate Window, Command Window, Call-stack, Local, Auto and many more, which highly evolves on increasing developers productivity. Debugging an application is not an easy job. As it require good knowledge in debugging tools available in Visual Studio. So i have always been eager to learn new techniques to  make it as easy as possible.

Recently i got a chance to learn some tricks over debugger which i am sharing here!

Debugger1
2.1.1

In 2.1.1, moving mouse over debugger variable shows the debugger value as variable type. There is way to start take control over debugger is by overriding “ToString()” method.

Debugger2
2.1.2

Now in 2.1.2 the debugger use “ToString()” method as the default value for debugger variable. Another nice option we have is to use the “DebuggerDisplay” attribute which will give more control over the debugging variable.

Debugger3
2.1.3

The “DebuggerDisplay” attribute accepts a string where we can refer class members as arguments. In debugging mode these members replaces the string arguments. It gives more clarity while debugging the code and is useful when member names are defined in a complex way. We can use the “DebuggerDisplay” attribute with the Class, Structs, Delegates, Enums, Fields, Properties, Assemblies.

Visual studio exposes one more attribute called “DebuggerBrowsable”.

Debugger3
2.1.4

The “DebuggerBrowsableState.Never” attribute can apply only to members and fields which should not visible on debug mode. For collection we can use “DebuggerBrowsableState.RootHidden” which automatically expand the collection while debugging and thus provide more readability.

Remote Debugging in Visual Studio – Part 2

In my previous post i have explained about How to debug an application using Visual Studio Debugger. There is one more way to debug your remote application using a tool called “msvsmon.exe”. The Remote Debugging Monitor (msvsmon.exe) is a small application that Visual Studio connects to for remote debugging and can be found in the location of %Program Files%\Microsoft Visual Studio 11.0\Common7\IDE\Remote Debugger. Remote Debugging involves two way communication between the Visual Studio Debugger and Visual Studio Remote Debugging Monitor(msvsmon.exe). For remote debugging to work, it is important which user runs Visual Studio and also which user runs msvsmon.exe.  To connect to msvsmon, you must run Visual Studio under the same user account as msvsmon. So  you must have a local user account on each computer, and both accounts must have the same user name and password. I have a simple HelloWorld.exe application on my remote machine. To start remote debugging

  • Copy all pdb files on remote machine and launch your application there.
  • Run msvsmon.exe tool on Remote machine by using visual studio command prompt or launch directly from the location.

msvsmonServerName

  • Copy Server name from msvsmon.exe
  • Open application source code in client machine and launch “Attach To Process” window (CNTRL + ALT + P)
  • Paste server name in “Qualifier” textbox and Refresh will shows all the process from Remote machine
  • Attach the HelloWorld.exe project to debug.

Attach We have option to share pdb files from client side. Follow the below steps to debug your application using shared pdb files. Client machine

  • Create a folder with all pdb files that you want to debug.
  • Share the folder to access everyone.

Server Side

  • Open Command Prompt.
  • Change directory to msvsmon.exe location.
  • Set Symbol Path for msvsmon.exe using “set _NT_SYMBOL_PATH command and launch msvsmon.exe

SymbolShare

Next time onwards visual studio will try to  load symbols from shared path also.

Remote Debugging in Visual Studio – Part 1

Every Visual Studio developer has probably come across the need of Remote Debugging at some point during development. I too faced that situation.Visual Studio supports remote debugging from one computer to another. When you are doing remote debugging, the host computer can be any platform that supports Visual Studio on which you control the debugging process. The remote computer can be a 32-bit or 64-bit Windows or Arm platform on which the debugger is run. It ships along with all versions of Microsoft Visual Studio.

Fore more about setup and configure Remote Debugger please visit  How to: Set Up Remote Debugging

Debugging process is controlled from the host and the listener on the remote computer that executes commands sent from Visual Studio. Here the listener is Remote Debugging monitor (msvsmon.exe).

The next important thing is security. You can either perform debugging in NoAuthentication mode or in Windows Authentication mode. Windows Authentication mode requires the same account to be setup on the host and the remote compute and both usernames and passwords must be the same. NoAuthentication mode which allow all people to access your debugging monitor.

Once finished the configuration part, deploy the application and pdb files on the remote machine and begin with starting msvsmon.exe on the same. We can now either start the application under the debugger or attach the debugger to the already running process.

Let’s start with the first scenario : start the remote debugging by modifying the start project properties page

Debugger1

If you don’t have access to the application solution, then you need to use the application EXE file. From Filemenu choose Open->Project/Solution… and find the EXE file for your application. Select the newly opened project and choose properties. Fill the page with following values:

Debugger2

Pressing F5 will start the remote application, now you can debug application on the remote machine like how you debug application in the local machine.

My next blog is about :  How to Attach and Debug application in Cross Domain