Saturday, 10 August 2013

Debugging in C# using #if DEBUG and [Conditional("DEBUG")]

1.  Configuring Debug/Release build

You can set condition on certain code blocks to only execute on debug mode. This does not mean running Debug (F5), but building the solution as a debug build rather than a release build. The type of build can be set in Build -> Configuration Manager;


When the solution is build in release mode, codes surrounded by #if DEBUG and #endif will be ignored. Similarly, if a method is marked as [Conditional("DEBUG")], it will be ignored, too.

2. Using #if DEBUG


Simply surround the code you want to execute only in Debug build in #if Debug and #endif. In the example above, Console.WriteLine("number: " + i); will be ignored in Release build, and the program will not  print anything. In certain IDEs, you will see the ignored part of the code gets greyed out. 

Variables introduced within the region will not be accessible from outside. (It will give you a compile error)


3. Using [Conditional("Debug")]


Marking a method with [Conditional("Debug")] will not be called on Debug build. It produces a cleaner code since it does need any markers around the method caller, and the behaviour is taken care of automatically depending on the build type.
[Conditional("Debug")] requires System.Diagnostics library.



Tuesday, 11 June 2013

Debugging code in Visual Studio (Using breakpoints - 2)

Continuing from the previous article on debugging, there are more advanced settings you can set on breakpoints if you want a finer-grained control over when to pause the program execution.

0. Test program



 The program above simply prints out a random number in a loop until the number generated is equal to 1. 

1. Setting Conditions

 You can set conditions on when to pause the program execution. Right-click on the breakpoint circle and you will see the context menu containing several options;


 If you click on the Condition, you will be prompted with a dialog window in which you can enter a boolean expression. As an example, let's insert a breakpoint at the line Console.WriteLine(...) and set the condition as;
i == 1
 Now if you run the program in debugging mode, it will start printing random numbers until the generated number becomes equal to 1 and pauses at the breakpoint.If the condition is not met, the breakpoint will be ignored.

2. Hit Count


 Hit count setting takes into account the number of times the breakpoint is being "hit". It is basically setting a condition on the hit count, pausing when the count is either equal to a number, a multiple of a number, or greater than or equal to a number. This setting can also be changed during debugging, where you can see the current hit count and set a new condition as you wish.



3. Filter


You can also set the filter to break for certain processes or threads if you are running multi-threaded program. if your thread Id is 111, then setting;
ThreadId = 111 
on the dialog window for Filter will make the thread pause at the breakpoint, but other threads will ignore it. 

Sunday, 9 June 2013

Using Stopwatch to measure execution speed in C#

 There are a number of ways to measure execution time in C# (including using DateTime class to get two "current" times, one at the start of the target code block and another at the end, and subtracting the former from the latter), and Stopwatch class in System.Diagnostics namespace is a fairly convenient one.

 You can initialise a Stopwatch instance and use it in the same way as the physical stopwatch; Start, Stop, and Reset it.

1. Instantiating 

 Make sure you include System.Diagnostics namespace by writing;
using System.Diagnostics;
  at the top of the file. This will then allow you to use Stopwatch class;
Stopwatch watch = new Stopwatch();

 2. Start, Stop, Reset

 Start the stopwatch at the beginning of the code block you want to measure execution time for, by invoking Start() method on "watch" object. This should come before you enter the code block. 
watch.Start();
 Then at the end of the code block, invoke Stop() method to stop the stopwatch.
watch.Stop();
 The stopwatch has now stopped running and has an elapsed time stored within the "watch" instance as its property. Stopwatch class provides three basic formats; firstly, a TimeSpan value which keeps values formatted in hours, minutes, seconds, etc.. Secondly, time in milliseconds as a long value. And thirdly, elapsed 'tick's as a long value.
 The first format would be useful if the expected execution time is more than a few seconds (or maybe few hours long) and you only need to visually see the result, or need to get each unit (year, hour...) separately.
 The second ElalsedMilliseconds format, on the other hand, would be useful if you are expecting very short execution time or need to deal with the result value in milliseconds as a whole number (for example, you may only need accuracy up to a millisecond and do not need any trailing values).

 You can reset or restart the timer in similar ways;
watch.Reset(); 
watch.Restart(); 
 Resetting the stopwatch would set the elapsed values to 0 and stop it too, whereas restarting would only set the values to 0 and continue running (if not started yet, it will start the watch).

3. Printing out the values

 These properties can be printed out via Console.WriteLine(). 

4. Alternative way of creating StopWatch instance

You can also create and start a StopWatch instance directly from static method "StopWatch.StartNew()".
Stopwatch watch = Stopwatch.StartNew();
 This simply replaces lines 11 and 12 of the example code above.



Saturday, 8 June 2013

Debugging code in Visual Studio (using Breakpoints)

 Debugging code in Visual Studio is much simpler than it sounds. I remember using print methods (e.g. Console.WriteLine()) to print out values in the middle of the code execution to see what was the cause of the errors occurring, simply because it felt more straightforward to use. If I had carried on doing that for my recent projects, it would have taken far more time to resolve each error and to discover holes in the complex logic behind the programs.

 In this article, I will explain a simple, but very useful technique of debugging using Breakpoints.



 The example code above simple sets credentials for a SMTP server and sends an email.
 Now, set a "breakpoint" by clicking the grey bar on the left of the line of code.





 When a line of code is set as a breakpoint, the program execution will pause every time that line is getting invoked. This lets you stop the program at the desired point and examine the intermediate state of the program. The background colour of the line changes to indicate the breakpoint. Now, Debug the code by pressing F5. 

The program execution stops at breakpoint. The current program execution point is highlighted in yellow, and some information is displayed at the bottom panel.



  Locals panel shows all local variables that exists (even if null) and you can look into object instances for the values they contain, too. If the breakpoint is within an object instance, "this" object contains all its fields.
 Call Stack panel shows the method calls that led to the current breakpoint. In other words, you can go down the call stack to see what method call steps were involved in eventually invoking the current breakpoint.


 When you are done exploring the state at the breakpoint, you can continue executing the program by pressing F5. If there are any other breakpoints after the current one, it will automatically jump to that breakpoint and pause (this can also happen when you set only one breakpoint, in the case where the line of code you set as a breakpoint is a part of a loop, therefore is getting invoked multiple times). 

 Clicking the red circle on the breakpoint will deselect the line. Alternatively, you can press Ctrl+Shift+F9 to remove all breakpoints. 

 To stop debugging and exit the program, press Shift + F5.


 Continue reading about more advanced usage of breakpoints


Friday, 7 June 2013

Using NuGet PowerShell to reference a lower version of a package in Visual Studio

(This article assumes you have installed NuGet on Visual Studio via Tools -> Extensions and Updates)

NuGet is a great tool to reference a package without requiring the user to download one in their local machine, and its repository lets you reference the latest version of a particular package with only a few mouse clicks. However, you may want a lower version of the package because of compatibility issues (for example, Microsoft EnterpriseLibrary v6.0 is not compatible with .Net 3.5). 
 This can be done via NuGet's PowerShell (command prompt) quite conveniently. 


Firstly, check the ID of the package you want;
    Right-click on Reference for the project -> Manage NuGet Package -> Online (panel on the right)
and search for the package name. 




Clicking on the package will display details on the right-hand side panel, and Id is what you want to note down.



Now, Go to Tools -> Library Package Manager -> Package Manager Console



It will open a command-line prompt at the bottom of the screen. Type in;
Get-Package -ListAvailable -AllVersions PACKAGE_ID
You will see a list of versions for the package.




Make sure "Default project" selected on the command prompt is the project you want to install reference.
Then type in;
Install-Package Newtonsoft.Json -Version 5.0.5
Where Newtonsoft.Json should be substituted by your package id, and 5.0.5 with your desired version.

The reference has been made, so you can now use the package in your code.