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

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

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.

Anonymous Types

Anonymous Types are one of the nice feature in .net framework and i have never seen this code snippet anywhere in my project. Anonymous Types enable you to create objects without writing a class definition for the data type. Instead, the compiler generates a class for you. The class has no usable name, inherits directly from Object, and contains the properties you specify in declaring the object. You create anonymous types by using the new operator together with an object initializer

Dim carID As Integer = 100
Dim carName As String = "Car Name"

Dim carValue = New With {Key carID, carName}

'Which is same as

Dim anotherCar = New With {Key .ID = carID, .Name = carName}
Console.WriteLine("CarID : {0}", anotherCar.ID)
Console.WriteLine("Car Name : {0}", anotherCar.Name)

Anonymous types contain one or more public read-only properties.You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type.

Markup Extensions for events in .Net 4.5

My previous post was about how to create Custom Markup Extensions for XAML.  Until now, it was possible to use a markup extension in XAML to assign a value to a property, but couldn’t do the same to subscribe to an event. WPF 4.5 supports markup extensions for events. While WPF does not define a markup extension to be used for events, third parties are able to create a markup extension that can be used with events. When using the MVVM pattern, we often associates commands of the ViewModel with controls of the view, via binding mechanism. It has some drawbacks.Not all controls have Command property, and when exists, it corresponds to only one event of the control. The solution so far to this issue involved using the Interactivity assembly from the Expression Blend SDK. We can try something similar using the new feature, which will not require the Expression Blend SDK at all.

It is able to bind events directly to ViewModel methods, like this:

<Window x:Class="CustomMarkupForDateTime.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:custom="clr-namespace:CustomMarkupForDateTime"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Grid>
        <Button Width="300"
                Height="30"
                Click="{custom:CommandBinder ShowWindowCommand}" />
    </Grid>
</Window>

With the ShowWindow method defined in the ViewModel

 public class ViewModel
    {
        public ICommand ShowWindowCommand { get; set; }

        public ViewModel()
        {
            ShowWindowCommand = new DelegateCommand(ShowWindow);
        }
        private void ShowWindow(object obj)
        {
            System.Windows.MessageBox.Show("Hello World!");
        }
    }

CommandBinder Markup Extension :

using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;
using System.Reflection;

namespace CustomMarkupForDateTime
{
    public class CommandBinder : MarkupExtension
    {
        private string _commandPath;
        private ICommand _command;
        private Type _eventArgsType;

        public CommandBinder(string commandPath)
        {
            _commandPath = commandPath;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            Delegate customDelegate = null;
            IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (target != null)
            {
                EventInfo eventInfo = target.TargetProperty as EventInfo;
                MethodInfo methodInfo = GetType().GetMethod("InvokeCommand", BindingFlags.NonPublic | BindingFlags.Instance);
                Type parameterType = null;
                if (eventInfo != null)
                    parameterType = eventInfo.EventHandlerType;

                if (parameterType != null)
                {
                    _eventArgsType = parameterType.GetMethod("Invoke").GetParameters()[1].ParameterType;
                    customDelegate = Delegate.CreateDelegate(parameterType, this, methodInfo);
                }
            }
            return customDelegate;
        }
        private void InvokeCommand(object sender, RoutedEventArgs e)
        {
            var dataContext = (sender as FrameworkElement).DataContext;
            if (_commandPath != null)
            {
                _command = (ICommand)ParseCommandPath(dataContext, _commandPath);
            }
            var cmdParams = Activator.CreateInstance(_eventArgsType);
            if (_command != null && _command.CanExecute(cmdParams))
                _command.Execute(cmdParams);
        }
        private Object ParseCommandPath(object target, string commandPath)
        {
            return target.GetType().GetProperty(commandPath).GetValue(target);
        }
    }
}

Zipping Files and Folders using .Net

It has been almost a year since .NET 4.5 got released. But the problems with most of the recent Microsoft releases have been communication with .NET developers. Only one or two features are known to developers and other features just stay on MSDN and end up becoming simple documents.

For example, the time you ask a .NET developer what is new in the core framework .NET 4.5 most of them will just say async and await

Again it’s very difficult to run through all the new features. Because the features may not sound interesting depending on what you are working currently on..

So in this article I have picked a  nice feature introduced in .NET 4.5 core.

Zip File Creation

Now in .NET we did not have built-in support for implementing Zip compression. Many developers where using third party components like “DotnetZip”,”XceedZip”. In .NET 4.5, the Zip feature is baked in the framework itself, inside the namespace  System.IO.Compression

using System;
using System.Windows;
using System.IO.Compression;

namespace CompressionSample
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ZipButton_Click(object sender, RoutedEventArgs e)
        {
            ZipFile.CreateFromDirectory(@"F:\Pictures\Drawings",@"F:\Images.zip",CompressionLevel.Optimal,includeBaseDirectory:true);
        }
        private void UnzipButton_Click(object sender, RoutedEventArgs e)
        {
            ZipFile.ExtractToDirectory(@"F:\Images.zip",@"F:\Images");
        }
    }
}

The ZipFile class provides static methods for working with zip archives. To use these methods, you must reference the System.IO.Compression.FileSystem assembly in your project. The System.IO.Compression.FileSystem assembly is not available for windows store apps.