Others

Hidden game in your Chrome

Published by:

For most of you that use Chrome this screen is maybe well known
google game

 

If you hit space, that turns into a game – the dinosaur starts running and you have to jump over cactus. It is pretty basic but also very addictive. You can even catch yourself pulling the internet cable out just to play around with the dinosaur 🙂

google game 1

javaScript

Angular directive for Twitter Bootstrap with datepicker extended to select hour

Published by:

If you find the native angular directives for twitter bootstrap neat to use but miss the functionality to select an hour from the datepicker (the original version get as granular as days), you are not alone. I know there are a bunch of other other datepicker directives out there but i am kind of used to this one and that’s why i extended it to use hours also. Note – if you include it in your project, beware to change the name to something other than “ui-bootstrap-tpls.js” because if you update packages it will be overwritten by the new one.

Clone it under: https://ivopashov@bitbucket.org/ivopashov/bootstrap-tpls-with-added-hour-to-the-datepicker.git

Coding javaScript

angular controller inheritance minification issue

Published by:

In Angular we use $injector service to require dependencies in any point of time. We can use it to create a hierarchy of controller inheritance very easily – consider the following example:

var ParentController=function($scope){
    $scope.triangle={
        a:3,
        b:4,
        c:5
    };
}

app.controller('ChildController',['$scope','$injector',function($scope, $injector){
    $injector.invoke(ParentController,this,{
        $scope:$scope
    })
}])

What we basically do is declare a regular js function (ParentController), inherit from it through the invoke method of $injector service and pass any dependencies in the curly braces. Note that all dependencies in the parent must be resolved in the child and then passed along in the $injector.invoke. So now we have $scope.triangle inherited in the ChildController.

The above example works great until we don’t minify the js files when things get ugly and $injector starts throwing errors in the console. We need a little angular specific hack to fix that:

instead of :

var ParentController=function($scope){
    $scope.triangle={
        a:3,
        b:4,
        c:5
    };
}

we need to do:

var ParentController=['$scope', function($scope){
    $scope.triangle={
        a:3,
        b:4,
        c:5
    };
}]

The reason is that angular resolves dependencies ($scope in the example) by their names and when minified, names become unrecognizable to angular. A workaround of that is to annotate the functions with the names of the dependencies as strings, which will not get minified.

.NET

Variance and Contravariance in C# generics

Published by:

No, it is not a mistake – you didn’t landed on a math blog although the terms in the title sound more math than IT. However, variance and contravariance are terms deeply rooted in C# since version 4.

The simplest way to think about those is that variance preserves the direction (from less derived object to more derived on – i.e. object->string) while contravariance reverses it. Variance is somewhat intuitive as it coincides with assignment compatibility. It is natural to make something as Object a = “test string”.

If you examine IEnumerable interface in the .net dlls, you will find out that it’s signature is IEnumerable (we denote variant generics with out and contravariant with in) and it means that the interface works with generic types that behave variant. So that if we have SomeMethod(IEnumerable items) we can pass it parameter as IEnumerable items and that’s very logical because if we can enumerate and manipulate the less derived type it is safe to go through and manipulate the more derived type.

I personally find contravariance way more challenging. I wont try to explain it but rather show an example which is very self-explanatory:

 public class Animal
    {
        public void SayYourType()
        {
            Console.WriteLine(this.GetType().Name);
        }
    }


    public class Human : Animal
    {

    }

So far so good – we have a class Human to derive from Animal. They do nothing more than say their types so that we can keep things simple

    public interface ICallType<in T>
    {
        void CallType(T x);
    }

    public class AnimalTypeCaller : ICallType<Animal>
    {
        public void CallType(Animal x)
        {
            x.SayYourType();
        }
    }

    public class TypeDiscoverer<T>
    {
        T Item;
        ICallType<T> TypeCaller;

        public TypeDiscoverer(T item, ICallType<T> typeCaller)
        {
            Item = item;
            TypeCaller = typeCaller;
        }

        public void DiscoverType()
        {
            TypeCaller.CallType(Item);
        }
    }

lets have an interface that works with generics and exposes only one method that is able to call the type (Note the in keyword). Let’s also have a concrete implementation – the AnimalTypeCaller that inherits from ICallType and works with objects of type Animal. Finally we have a class that works with generics, takes a generic item argument and ICallType interface and is able to call the type of the underlying item using concrete implementation of the interface ICallType.

The magic lies in the next two lines though:

var humanTypeDiscoverer = new TypeDiscoverer<Human>(human,new AnimalTypeCaller());
humanTypeDiscoverer.DiscoverType();

we declare humanTypeDiscoverer that works with Human object but pass it AnimalTypeCaller, so we reverse the direction- > we handle more derived types(Human) with handler that works with less derived types (Animal). Even the intellisense will hint you that it expects ICallType of type Human but because of the contravariance and the in keyword, the above code is perfectly legal and works as expected and we can treat Humans with AnimalTypeCaller 🙂

This pattern is used with handlers and most notably comparers. IComparer is implemented this way. And if you think about it, it makes sense – it is ok to compare integers with an object comparer, but comparing objects with int comparer would be strange.

I suggest you to make yourself a little proof of concept if you still have difficulty to grasp the idea. I spent a lot of time reading on the topic but it took me only 15 minutes to make my own example. 10 lines of code say much more than pages of text. And are more interesting to read 🙂

.NET

Change MVC project name in VS

Published by:

Changing the MVC project name in VS is not a standard procedure as hitting F2 and typing the new name. Here are the steps to change the name:

– Click on the project name, hit F2 and rename the project

Go to project properties (right click the project and select Properties). Then under the Application tab change the Assembly name and the Default Namespace

– Go to any class in the project and select the namespace (that should be the old project’s name). Right-click it and select -> Refactor -> Rename and type in the new name. That should change the namespace for the project.

– Change the project folder’s name

Open the .sln with a text editor and manually change the project’s name

– Finally (that’s tricky) go to views folder, locate the web.config there and edit the namespace in the file

sysAdmin

Setting up Git in the Windows Path

Published by:

You might want to set up git in your system PATH. Bower for example relies heavily on Git to install packages so if you get an error like “ENOGIT git is not installed or not in the PATH” that might be the solution (Win 7):

  • Open File Explorer and right click on Computer
  • select Properties and then Advanced System Settings
  • Under Advanced tab select Environment Variables
  • Then under System Variables go to Path and click edit
  • Append at the end of the Variable value string the path to the Git bin and cmd folder separated with semicolon(;)

Here is what i append:

;C:\Program Files (x86)\Git\bin\;C:\Program Files (x86)\Git\cmd\

Watch out: Depending on your system, Git might be in Program Files and not Program Files (86)

.NET

Dependency Injection – under the hood

Published by:

There is a best practice in software development – Program to an interface, not an implementation. That is – use as much interfaces as you can and not concrete implementations. For example make your classes use ILogger and not FileLogger or ConsoleLogger.

To achieve that we use the Dependency Injection technique where you supply your classes with interfaces in the constructor or as properties and then have something else inject the dependencies after you have set up which concrete implementation to use for each interface, usually called dependency map. Still here?

There are a list of libraries to assist you with that in C# – > the most popular being Ninject, Castle Windsor, Unity etc. But let’s get our hands dirty and see how this happens under the hood. Consider the following entities:

    
    public interface ICharge
    {
        void Charge();
    }

    public class MasterCard : ICharge
    {
        public void Charge()
        {
            Console.WriteLine("payment was made with mastercard");
        }
    }

    public class Visa : ICharge
    {
        public void Charge()
        {
            Console.WriteLine("payment was made with visa");
        }
    }

Now we want to create a class Payment which can make payment with Visa or MC depending on the configuration that we setup:

  
    public class Payment
    {
        //constructor dependency
        public Payment(ICharge cc)
        {
            _cc = cc;
        }

        private ICharge _cc { get; set; }

        public void MakePayment()
        {
            _cc.Charge();
        }
    }

So that’s how we program to an interface (ICharge) without knowing the concrete implementation – Visa or MasterCard. We also need a class o resolve the dependencies for us, which we will call Resolver:

    
public class Resolver
{
    //store for dependency maps
    private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();
        
    public void Register<T1, T2>;()
    {
        dependencyMap.Add(typeof(T1), typeof(T2));
    }
}

dependencyMap is the place where we setup which implementation we want to use for each interface. It is one more thing that we need and that is a Resolve method that will actually do the magic and give us classes with resolved dependencies to concrete implementations.

 public class Resolver
    {
        //store for dependency maps
        private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();

        //this method calls the next one - we use this one publicly just because its syntax is cooler
        public T Resolve<T>()
        {
            return (T)Resolve(typeof(T));
        }

        private object Resolve(Type typeToResolve)
        {
            Type resolvedType = null;
            try
            {
                //check if we have a configured map
                resolvedType = dependencyMap[typeToResolve];
            }
            catch
            {
                throw new Exception(string.Format("Couldnt resolve {0}", typeToResolve.FullName));

            }

            //get the constructor and then the parameters
            var firstConstr = resolvedType.GetConstructors().First();
            var constrParameters = firstConstr.GetParameters();

            //in the case of parameterless constructor
            if (constrParameters.Count() == 0)
            {
                //return an instance of the resolved type
                return Activator.CreateInstance(resolvedType);
            }
            else
            {
                IList<object> parameters = new List<object>();
                foreach (var parameterToResolve in constrParameters)
                {
                    parameters.Add(Resolve(parameterToResolve.ParameterType));
                }
                return firstConstr.Invoke(parameters.ToArray());
            }
        }

        public void Register<T1, T2>()
        {
            dependencyMap.Add(typeof(T1), typeof(T2));
        }
    }  

The first Resolve method is the beautiful public version of the second one. The magic, however, happens in the second Resolve method. For those of you with reflection being their second nature, the example is pretty straightforward but let me explain for the others.First, we check if we have a configured dependency map for the type that we want to resolve and if not-throw an exception (the prerequisite for every dependency injection is a dependency map). Then we take the first constructor with reflection and check number of parameters – if parameters are zero, we have nothing to inject but instantiate the type with the Activator method. However, in our example Payment has a constructor with one parameter – ICharge. In this case (where the constructor has some parameters) we iterate through them and do the Resolve procedure recursively for each (Notice that Visa and MasterCard don’t have constructors, but a default constructor is added by the compiler). Then we store the resolved parameters in an array and finally we instantiate the initial class with all the resolved constructor parameters with the Invoke method. Let’s see how that works in our example:

        
static void Main(string[] args)
{
     //inversion of control container
     Resolver resolver = new Resolver();

     // register dependency map
     resolver.Register<Payment, Payment>();
     resolver.Register<ICharge, Visa>(); 

     // thats where the magic happens
     var payment = resolver.Resolve<Payment>();
     payment.MakePayment();
     Console.ReadLine();
}

We populate the dependency map with Payment -> Payment (with the dependency injection libraries you don’t have to map concrete types as here) and ICharge -> Visa. So when we say

var payment = resolver.Resolve<payment>();

the Resolve method returns a Payment instance with the _cc property set to Visa, so the console reads “payment was made with visa”. If we have mapped ICharge -> MasterCard we would have _cc property instantiated as MasterCard.This example looks a little burdensome to inject a single constructor parameter in a single class but imagine the following example

   
    public IHttpResult UserApiController(ILogger logger, IRepository repository, IUserManager userManager)    
    {        
        //some code    
    }

Now imagine that you have 30-40 api controllers and you have to use different loggers, repositories and user managers in different contexts. That’s where you start to feel the advantages of dependency injection. With 3 lines of code (setting up the dependency map in this case), you do the whole work of substituting implementations instead of going to every single controller and switch the parameters. It is also much more error free this way as you don’t repeat yourself.

.NET

StringBuilder vs. Plus Operator

Published by:

One of the first things every developer learns is handling strings. String operations are so common that there is hardly a day without having to handle strings, so knowing the nitty-gritty of string handling is vital for every good developer.

It is something like a dogma to use StringBuilder when handling strings and not the + operator or String.Concat (which is + under the hood) because StringBuilder is way faster. Strings are immutable in C# so every time you want to change a string, you basically create a new string. StringBuilder solves this problem by keeping an array where it keeps the string chars and auto grows the array when needed (pretty much same principle as how Lists work in C#). The string object is then derived when calling the ToString method.

Although better performance is generally the case with StringBuilder VS the plus  operator, with string concatenation of only a few strings, i find the + operator  much more readable and the performance drain is close to zero so nothing to worry about. Consider the following example:


Stopwatch sbWatch = new Stopwatch();
Stopwatch plusOperatorWatch = new Stopwatch();
var destinationStringBuilder = new StringBuilder();
string destinationString = String.Empty;
string sourceString = new String('X', 20);

sbWatch.Start();
for (int i = 0; i <= 10000; i++)
{
    // Concat strings 3 times using StringBuilder
    destinationStringBuilder.Append(sourceString);
    destinationStringBuilder.Append(sourceString);
    destinationStringBuilder.Append(sourceString);
    destinationStringBuilder.Clear();
}
sbWatch.Stop();

plusOperatorWatch.Start();
for (int i = 0; i <= 10000; i++)
{
    // Concat strings 3 times using + operator concatenation
    destinationString = sourceString;
    destinationString += sourceString;
    destinationString += sourceString;
}
plusOperatorWatch.Stop();

On my machine the clock for StringBuilder shows 0 milliseconds and the clock for the plus operator shows 3 milliseconds which is very small difference for doing three string concatenations 10 000 times and in my opinion the + operator is much more readable.

The case, however, for StringBuilder is when we build larger texts out of smaller strings. If we remove

destinationStringBuilder.Clear();

from the first loop and convert

destinationString = sourceString;

to

destinationString += sourceString;

in the second loop

performance becomes an issue with StringBuilder outperforming + operator in the range of hundreds of times. StringBuilder takes 3 milliseconds and the + operator takes a little under 17 seconds.

So rule of thumb is if you have to do string manipulations with up to 5 strings go for the + operator for better readability, otherwise use StringBuilder for performance.

Consider the following example - a common practice is to write logs somewhere so i find much more readable to do something like :

var message="User " + user.userName + " tried to access resource " + resource.name + " at " + DateTime.Now;
Logger.info(message);

instead of:

var sb=new StringBuilder();
sb.Append("User ");
sb.Append(user.userName);
sb.Append(" tried to access resource ");
sb.Append(resource.name);
sb.Append(" at ");
sb.Append(DateTime.Now);
Logger.info(sb.ToString());

And performance difference in this case will be close to zero.