Friday, February 20, 2009

How to add custom build step to a TFS Server Build ?

Most of the time when you are creating a build script (TFSBuild.proj), you need to do some steps after the build. Wether it's creating an MSI for easier deployment, creating a VSI for a Visual Studio Add-in, or whatever if may be... you normally do a post build.

A post build event looks like the following inside the TFSBuild.proj :

<Target Name="AfterDropBuild">
  <CallTarget Targets="PostBuildStep" />
</Target>

<Target Name="PostBuildStep">
  <!-- Do something -->
</Target>

When you only have 1 or 2 tasks and that one fails, it might be easy to find the one that failed. What if you have 8 to 20 tasks? It then becomes incredibly hard to find which one failed. What I've seen the most is normally some "<Message />" tags with some descriptive tasks. This is the equivalent of debugging with Console.WriteLine or Debug.Print.

What if you could know EXACTLY which task failed to run? Here is a way to add a custom build step to your TFS build which will allow you to easily know what crashed.

<Target Name="PostBuildStep">
  <!-- Create the build steps which start in mode "Running" -->
  <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Message="Doing Something on a PostBuild Event" Condition=" '$(IsDesktopBuild)' != 'true' ">
    <!-- Return the ID of the tasks and assigned it to "PropertyName" -->
    <Output TaskParameter="Id" PropertyName="PostBuildStepId" />
  </BuildStep>

  <!-- Do something -->

  <!-- When everything is done, change the status of the task to "Succeeded" -->
  <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(PostBuildStepId)" Status="Succeeded" Condition=" '$(IsDesktopBuild)' != 'true' " />

  <!-- If an error occurs during the process, run the target "PostBuildStepFailed" -->
  <OnError ExecuteTargets="PostBuildStepFailed" />
</Target>


<Target Name="PostBuildStepFailed">
  <!-- Change the status of the task to "Failed" -->
  <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(PostBuildStepId)" Status="Failed" Condition=" '$(IsDesktopBuild)' != 'true' " />
</Target>

With that in place, you will see exactly which task failed. As a bonus, it will also give you the time at which it completed. This will easily allow you to compare with your other task to see which one is taking the most time.

I would like to thank Martin Woodward which is a TeamSystem MVP. The question originated from Stackoverflow and more details are also available on Martin's website.

Submit this story to DotNetKicks

Wednesday, February 18, 2009

Why should I use mocking objects in my Unit Test?

If we cut out any "fanboy" or favouritism toward certain framework and that we try to keep it in a one liner... I would say: "To simulate behaviours of objects that are impractical or impossible to incorporate inside a unit test".

The Wikipedia's article about Mock Object mention some reason an object should be mocked.

The object...

Supplies Non-Deterministic Results

By "non-deterministic" we mean everything from time, currency rate, shipping rate, etc. Any value that could be changing because of a specific implementation such as algorithm should be mocked. Mocked object allows you to return predetermined value that are independent of the algorithm/time/etc.

This allows to more easily test the state of the System Under Test (SUT) after running some methods.

Has States that are difficult to create or reproduce

The example given by Wikipedia is "network error". It's difficult to reproduce this kind of situation on every developers station. Other situation might include security, location of the test on disk, network availability (not just errors). If some objects that the SUT is using require any of those, the tests WILL fail somewhere and somehow. If it's not on a developer's machine, it's going to be on the build machine.

Mocking those objects and giving them proper behaviour will remove any required "settings" that are necessary to run a Unit Test.

Is Slow

Databases, network, file access (up to a point) are all slow. If your SUT is an ObjectService that is using a Repository and you are hitting directly on the databases, it is bound to be slow. Of course the database can cope with it. But as you had more tests, the unit will soon take HOURS to run. With a small in-memory database will save the day and run those tests in less than a few minutes.

A mocked repository might just keep a collection of saved object so that when a "Get" method is called, it's readily available in this collection. This kind of mock is called a "fake" in the world of Mocking. It implements more complex behaviour but allows for easy initialization and more timely responses.

Does not yet exist or may change behaviour

If the only thing that is currently available within your system boundaries are contracts (Interfaces in C#), it's more easy to mock the interface that the SUT is requiring and go with this temporarily while the component is being developed. This allow testing and coding at the same time.

Conclusion

Mocking is an excellent tool to test a specific object under controlled conditions. Of course, those conditions are bound to change and tests are going to be maintained. Why I particularly like is when I use a mocking framework, I don't need to create 1000+ objects (exaggerating here) with some specific behaviours or create "too intelligent" mock that will have to be maintained. I dynamically declare a mock with my favourite mocking framework with the expected call and the expected returns and I go through with that.

What normally happens is I have considerably less mocking objects inside my Unit Tests and the only objects that are left standing are some in-memory database objects with simple implementation that would be to hard to define with a mocking framework.

Submit this story to DotNetKicks

Tuesday, February 17, 2009

Is blogging making people blog?

I have a colleague that have his own blog. When I started blogging, it was because of Jeff Atwood's post about starting to write and him having say on StackOverflow's podcast that he's not always right but that he have an online presence and that he's loud.

I agree. Having a blog and writing it (useful or not) is a way to broadcast yourself. Having a blog (depending on what you it) can be good for your career and can also serve as a way to store your personal knowledge that you gained through out projects.

I'm happy that I started my blog. It's kind of a technical diary and I'm more than happy to write to it when I have a moment.

To go back to my colleague, he's a nice guy with a huge technical knowledge. What I'm proud of is this. I started my blog in 2009 and he had his since 2007. During 2007 and 2008 he wrote an average of 5-8 post per years. When I started my blog, he followed me on my journey and we started comparing Google Analytics total number of visits. That's when the friendly competition started.

He knew that I would win easily if he wasn't going to post something interesting. So he started following me. That's why I say that blogging is contagious.

Now instead of making around 8 blog post a year, he makes 8+ a month.

Is that THAT contagious or are we the only duo of blogger like that?

Submit this story to DotNetKicks

When would you use delegates in C#?

This is a valid question. Before C# 3.0, you could use delegates or declare full methods to bind to events. Now we can declare event directly through lambda. (See this post on many different examples on how to bind event handlers).

Jon Skeet answered me the following:

    • Event handlers (for GUI and more)
    • Starting threads
    • Callbacks (e.g. for async APIs)
    • LINQ and similar (List.Find etc)
    • Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)

Delegates is a keyword that can be used to declare inline methods. This inline code can be stored inside variables and then executed when necessary. This is exactly what happens when you are binding methods to events. You are storing the signature of the method inside a variable that will store multiple methods signature and call them when an event is happening.

Of course, it's limiting to think about delegates only as events. If we check the standard definition for the word delegation:

In its original usage, delegation refers to one object relying upon another to provide a specified set of functionalities. [...] Delegation is the simple yet powerful concept of handing a task over to another part of the program.

As I already demonstrated inside the StreamProxy class, we can easily give another software the tools  to answer it's solution. But sometimes, the call might not be necessary. Just like when you are sending a data repository to a service class to save a model, delegate is basically just sending any method that match the accepted signature  instead of complete class.

One of the most recent use of Lambda's inside C# is inside Mocking tools. Moq use those to easily describe expectations, returned values, and so on. This allow Moq to be type safe instead of relying on Reflection and string comparison. This has brought us compile time check rather than runtime check.

There is a lot of use for delegates and they are being used more and more. Lots of languages support some form of delegation (.NET, C++, JAVA, and many more)

Hope delegates are not as foreign as they were 1 year ago.

Submit this story to DotNetKicks

Do modern compilers optimize the x * 2 operation to x << 1?

I was wondering wether the C++ compiler inside Visual Studio 2008 was optimizing it the way it would logically be. So I asked the question on Stackoverflow. It was among my first questions and was to see how the community would answer (yeah I'm lazy).

I was promptly answered by Rob Walker. He showed me what the compiler outputted.

32bit:

01391000  push        ecx
  int x = 0;

  scanf("%d", &x);
01391001  lea         eax,[esp]
01391004  push        eax
01391005  push        offset string "%d" (13920F4h)
0139100A  mov         dword ptr [esp+8],0
01391012  call        dword ptr [__imp__scanf (13920A4h)]

  int y = x * 2;
01391018  mov         ecx,dword ptr [esp+8]
0139101C  lea         edx,[ecx+ecx]

64bit:

    int y = x * 2;
000000013FB9101E  mov         edx,dword ptr [x]

  printf("%d", y);
000000013FB91022  lea         rcx,[string "%d" (13FB921B0h)]
000000013FB91029  add         edx,edx

While this gives us a lot of information about what it does, it's normally a pretty bad idea to try to outsmart the compiler. The compiler have it's own way to optimize some operations to make sure that it run best on the targeted platform.

To quote Raymond Chen:

Of course, the compiler is free to recognize this and rewrite your multiplication or shift operation. In fact, it is very likely to do this, because x+x is more easily pairable than a multiplication or shift. Your shift or multiply-by-two is probably going to be rewritten as something closer to an add eax, eax instruction.

The moral of the story is to write what you mean. If you want to divide by two, then write "/2", not ">>1"

Bold was added by me for emphasis. Raymond Chen wrote that in 2005. Write what you mean. Wow. If you want to multiply then write "*2" and if you want to divide write "/". If you are meaning to shift bits, then so! But don't try to outsmart the compiler by doing bit shifting.

If you are doing bit shifting do gain performance, you are doing something wrong.  There is many other way to gain performance in the kind of application we, developers, are building and bit shifting is not one of them.

You are simply losing readability for maybe a few milliseconds.

Submit this story to DotNetKicks