Error 286 The “BuildShadowTask” task failed unexpectedly. System.NullReferenceException: Object reference not set to an instance of an object.

One of my colleagues meets the message above during building solution which has a test project. Because the solution he found isnt trivial I decided to distribute it here too:

Refresh accessors in Test References or add if some of them are missing.

Using accessors is obsolete now, but if You have an ancent project with them which wont compile with this error I hope You find useful this info.

Assembly generation failed — Referenced assembly ‘…’ does not have a strong name

A lot of useful nuget packages can be found around. But some of them are useless when You try to reference them from an assembly which should be signed. During compilation you will get the error message:

Assembly generation failed — Referenced assembly ‘…’ does not have a strong name

How to add strong name to a third party assembly?

I used to download the original sources and recompile them with assembly signing. But last time I simply neither cannot find the original sources nor the original download location of the used version of binaries. I tried to disassemble the dll but without success: ilspy and reflector generated uncompilable code πŸ™

But while googleing I found a simple 4 step solution here:

Step 1 : Run visual studio command prompt and go to directory where your DLL located.

For Example my DLL located in D:/hiren/Test.dll

Step 2 : Now create il file using below command.

D:/hiren> ildasm /all /out=Test.il Test.dll
(this command generate code library)

Step 3 : Generate new Key for sign your project.

D:/hiren> sn -k mykey.snk

Step 4 : Now sign your library using ilasm command.

D:/hiren> ilasm /dll /key=mykey.snk Test.il

Nice, eh?

Naturally You should repeat these steps each time when the referenced nugets are updated,
but this way is much easier than the download-actual-sources-and-recompile one…

NSubstitute’s unexpected default return value

NSubstitute is a great tool when You are writing unit tests for Your product which was designed with dependency injection in mind.

Let’s see it:

    public interface IWorker
    {
        object GetResult();
    }

    [TestMethod]
    public void ExecuterTest_WorkerCalledOrNot()
    {
        var workerSubstitute = Substitute.For<IWorker>();

        var executerToTest = new Executer(workerSubstitute);

        // we test here
        executerToTest.Execute();

        workerSubstitute.Received(1).GetResult();
    }

In the code above I was not interested in the real value of the worker’s result. I wanted only to know whether the worker’s GetResult method gets called or not. But all of my workers do some hard work, so for this test I dont want to instantiate them and implicitli convert my unit test into integration test. So I create a substitute via NSubstitute for the given interface and gave that to my Executer.

The substitute tries to be as neutral as it can be. All void methods return asap, all non void methods return the default value for the return type. Naturally You can modify that behaviour and explicitly tell the substitute what to do when it’s methods get called, so You can for example redirect all database calls to in memory data structures during tests if You created Your DAL layer with DI in mind. And meanwhile the subtitute collects data about its use, so we can ask it whether it was called or not and with what arguments, etc.

But today I found got something unexpected thing.

Change a bit the example above to demonstrate it:

    public interface IWorker
    {
        TRet GetResult<TRet>();
    }

    [TestMethod]
    public void SubstituteReturnValueTest()
    {
        var workerSubstitute = Substitute.For<IWorker>();

        // test #1
        var r1 = workerSubstitute.GetItem<int>();
        Assert.AreEqual(default(int), r1);

        // test #2
        var r2 = workerSubstitute.GetItem<List<int>>();
        Assert.AreEqual(default(List<int>), r2);

        // test #3
        var r3 = workerSubstitute.GetItem<IList<int>>();
        Assert.AreEqual(default(IList<int>), r3);
    }

This will fail at Assert of test #3 because r3 wont be null as You would expect but an instance of “Castle.Proxies.IList`1Proxy”!

I think it is a bug but may be a result of some design decisions which priorized some functionality (retval is an instance of some interface which is wrapped around with a subtitute created on the fly) over coherency.

So be careful πŸ™‚

DateTime.Now vs DateTime.UtcNow

A lot of times we used DateTime.Now for logging purposes. Once we got a task to search for and avoid performance bottlenecks in a data distributor projects. As a most simple measurement we put some logging around the code blocks in which we suspect the bottlenecks. The log showed us that a lot of time spent in a method which was really simple and we didnt understand why is it so slow.

After choosing professional performance profiler (RedGate’s ANTS Performance Profiler is the best one! πŸ™‚ ) we found that not the method was so slow but the logging! More precisely the DateTime.Now calls while writing timestamp on log lines!

After some googling we found that DateTime.Now after determining UTC time asks the OS for the timezone set on machine and computes the local time from it. And the determination of timezone from the OS was the real bottleneck.

So in high performing solutions use DateTime.UtcNow instead of DateTime.Now if You dont want to run into things like this.

Method implementation pattern

During the development of many projects I tried to standardize the outlook of methods to help anybody to distinguish between some parts of them.
Check the code below:

        public int SaveNewPartner(Partner partner, Operator modifier)
        {
            if (partner != null)
            {
                if (modifier != null)
                {
                    if (partner.ID == null)
                    {
                        if (!SanityCheck(partner))
                        {
                            throw new ApplicationException("partner failed sanity check");
                        }

                        partner.ModificationTime = DateTime.Now;
                        partner.Modifier = modifier;
                        return Save(partner);
                    }
                    else
                    {
                        throw new InvalidOperationException("Already saved!"); //LOCSTR
                    }
                }
                else
                {
                    throw new ArgumentNullException("partner");
                }
            }
            else
            {
                throw new ArgumentNullException("partner");
            }
        }

I have problems with this code, and if I have them maybe others who meet it later in our project will have too. If You should determine which part is its business functionality it will be probably a shot in the dark. I really need to understand the whole method before I can point out how it works because parameter checking, control flow, exit point mixed with business part.

That’s why I wrote all my methods by following a pattern:

  1. check parameters
  2. define return value
  3. do business functionality
  4. return retval

Here is the rewritten method:

        public int SaveNewPartner(Partner partner, Operator modifier)
        {
            if (partner == null)
            {
                throw new ArgumentNullException("partner");
            }
            if (modifier == null)
            {
                throw new ArgumentNullException("modifier");
            }

            int ret = 0;

            if (partner.ID == null)
            {
                throw new InvalidOperationException("Already saved!"); //LOCSTR
            }
            if (!SanityCheck(partner))
            {
                throw new ApplicationException("partner failed sanity check");
            }

            partner.ModificationTime = DateTime.Now;
            ret = Save(partner);

            return ret;
        }

In lines 3-10 the parameter check occures. There should be parameter checking in each public entrypoint of our class (methods, properties). I check all the parameters I use in the given method directly or in private members I call from here. It is not necessary to check params which are simly handled to other public methods (we may not know all the constraints about these, it’s not our business). I neither check the business validity here (line 3 vs. line 14).

In line 12 I define the return value, which I gave always the name ‘ret’. So if You check any line of the method You can clearly identify where the retval is set and You dont need to scroll anywhere to determine what is the retval variable.

In lines 14-24 placed the business logic. All extremalities are closed asap, so no long lasting ifs and unnecessarily deep indentations happen.

In line 26 we return from here. No other inline returns in the method body so the control flow is clear: we enter at the beginning and exit at the end.

for vs. foreach

If You write a cycle to reach every item in a collection You should use foreach instead of for.
So instead of:

            for (int i = 0; i < list.Length; i++)
            {
                list[i].DoSomething();
            }

write this:

            foreach (var item in list)
            {
                item.DoSomething();
            }

In first case the compiler may not determine what do You want with variable i.
It wont try to remember of position in list to step to the next item in next cycle which will be needed in next cycle.
The code will index the list in every cycle from the begining to the last element plus one.
Foreach will avoid this.
There are excemptions like real arrays via indexing cpu level instruction which will be faster than instantiating an enumerator
but remember my Think Runtime Principle.

Reuse intermediate results

Everybody knows that a good programmer writes reuseable code.
If somebody writes the same instruction sequence twice she/he will extract it to a method and the code becomes reuseable.
But how about data? Reuse it too!

            for (int i = 0; i < array.Length - 1; i++)
            {
                if (array[i] > array[i + 1])
                {
                    sum = array[i] + array[i + 1];
                }
            }

Depending on array’s content You will index array four times in every cycle instead of the two necessary.
Indexing an array is a cpu instruction, very fast, but imagine if it is a List and not an array!
The List implementation may switch to linked items and it becomes a lot of dereferencing steps to reach the item at specific index.

Go further:

                if (MyObject1.AnObjectProperty.ItsSubProperty.Value > MyObject2.AnObjectProperty.ItsSubProperty.Value)
                {
                    sum = MyObject1.AnObjectProperty.ItsSubProperty.Value + MyObject2.AnObjectProperty.ItsSubProperty.Value;
                }

How many times should the object graph walked down to Value property? What happens if the properties in path are calculated ones and not just field wrappers?

Go further:

            for (int i = 0; i < array.Length - 1; i++)
            {
                if (CalculateValue(i) > CalculateValue(i+1))
                {
                    sum = CalculateValue(i) + CalculateValue(i + 1);
                }
            }

We are calculating values twice!

Think about how Your code will be executed, not only what You should accomplish!
See my Think Runtime Principle.

“” vs. String.Empty and “a”+str+”b” vs String.Concat(“a”, str, “b”) reloaded

Despite the compiler optimizes the instructions above for a long time I suggest You not to use the firsts in the pairs.

The first pair has a lot of forum talks: which is better in terms of memory. But there is an other reason I favour String.Empty: You can much easier found all of it with FindAllReferences instead of looking for each “s in Your code πŸ™‚

The second pair the two sides in discussions are: readability vs. performance. The left side is much readable, but because of variable content in ancient days it becomes a double memory allocation to build “a”+str and then the tempresult+”b” string. Nowadays the compiler optimizes it to the call on the right side in the pair, which is much better: Concat allocates once the memory which is enough to build the whole result string at once. That is true till four parameters. If You have more params Concat will use StringBuilder class internally which works like Concat: allocates some space at first and uses it to build the string. The difference is: Concat knows how much space required for the result from it’s params, but StringBuilder dont. So it allocates a buffer and if that is exhausted it allocates a new bigger one, etc. If you check the IEnumerable<string> overload of Concat You will see that althought it knows from its parameters it dont calculates the required buffer size for StringBuilder constructor to allocate approriate buffer at once. So if You have more than four strings to concat You may write better code than using the builtin feature of Concat πŸ™‚

The reason for this post is very theoritical: the Think Runtime Principle

Volatile variables

If You want to exit from loop if some bool set from another thread You may be victimed by compiler’s code optimalization.

class Test
{
    private bool _loop = true;

    public static void Main()
    {
        Test test1 = new Test();

        // Set _loop to false on another thread
        new Thread(() => { test1._loop = false;}).Start();

        // Poll the _loop field until it is set to false
        while (test1._loop == true) ;

        // The loop above will never terminate!
    }
}

Found here: http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

Enum.TryParse<> unexpected behaviour

Check code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace EnumTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TestEnum result;

            bool ret = Enum.TryParse<TestEnum>("Yellow", out result);
            // ret value becomes: false
 
            ret = Enum.TryParse<TestEnum>("111", out result);
            // ret value becomes: true, result becomes: 111 !!!!!
        }
    }
 
    enum TestEnum
    {
        Red = 1,
        Green = 2
    }
}

Something found in help:

“If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum. ”

Nice.