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. 




Passing Command-line arguments on Visual Studio

When running an application, you often need to pass arguments to the Main method. On Visual Studio, you can pass in command-line argument via Property setting for the StartUp project (If you have more than one project in the solution, this will be the project in bold. You can right click on a project name and select "Set as StartUp Project" to make it one).


Double-click on the project's Property, and the screen should display something similar to the above picture.


Then go to Debug tab on the right, and write in command-line parameter in "Command line arguments" section (each argument must be separated by a whitespace).

Thursday, 6 June 2013

[Error resolved]: Unable to read data from the transport connection: net_io_connectionclosed

 I was testing a report generator that sends reports to associated clients. Other parts of the project worked okay, but at runtime, it threw an exception with a message "Failure sending email" and the inner exception message "Unable to read data from the transport connection: net_io_connectionclosed", neither of which did not help much.

 After searching through the web and asking around people, I finally realised that, because the project was built few years ago and had the old SMTP server configuration passed into it, it was failing to connect to the server to send the emails. Changing the SMTP server sorted out the problem straight away in my case, but there may be other problems responsible for the same exception being thrown. Sender email address and its credentials must be correctly set (for example, if you are using gmail's SMTP server, you should set the username and password to send as the particular user), or use default credential (Property for SmtpClient).



Tuesday, 4 June 2013

Variable Arguments (Varargs) in C# and Java

Variable arguments are useful when you do not want to restrict the method usage by setting a definite number of arguments, or simplify implementation of the method if there are many arguments that need to be passed in.


 In C#, params keyword lets you use variable number of arguments. Only one params is permitted for one method, and it must come last. The method would take zero or more arguments into the list, which can be used in the method implementation.

 In Java, '...' is added after the argument type to specify varargs. Otherwise, it is similar to params keyword in C#.

Both example uses for-each loop in the language specific syntax to go through the arguments passed in to the method.

Optional arguments (default arguments) in C#

C# has a syntax for defining optional/default arguments for a method, thus minimising the number of necessary method overloads. Usually, to provide a method that takes in a variety of argument combinations, you would have to have many overloads with different method signatures (arguments).


However, this means you will often end up with methods that do nothing except calling their overload with default arguments specified. So, rather than filling up your class with redundant methods, you can use optional argument syntax in C#.

There is no restriction on how many optional arguments you can use, but all of them have to come after other non-optional parameters. When they are omitted on a method call, default value specified in the method signature will be used automatically. It is also possible to explicitly choose the order in which the arguments comes in the method call, making it much more flexible and sometimes more clear. This is called 'Named Arguments', and the syntax is;  method(arg: value).

 Imagine you have 7 optional arguments, and you only want to provide 1st and 4th arguments. It would be much simpler both to use and to understand if you use Named arguments.

Sunday, 2 June 2013

Using enum as Bit field in C#

Bit field allocates meaning or name to each bit in a word (e.g. 32-bit machine word), and use bitwise operators to check conditions and combinations or them. For example, if you have 4-bit word (i.e. each memory address stores a 4-bit value), you could have;

option 1 = 0001
option 2 = 0010
option 3 = 0100

and check which option has been selected by checking which bit out of four has been set to 1.
In this case, 0111 will indicate that all of the options has been chosen, and 0011 would mean option 1 and 2.


In C#, you can indicate an enum as a bit field by using [Flags] attribute as follows;


In this example, the bits indicate whether certain sections are showing on a window. By using bitwise operators, you can check conditions. Applying bitwise-OR (|) to enum values mean that all of the mentioned values are included, and testing whether the result of bitwise-AND (&) with desired value is 0 can tell if the particular bit is set.

'setting' value above has both Panel1 and Panel2 flags set to 1, so checking if the setting includes Panel1 would be true. This is because 'setting' would have value 0001 | 0010, which is equal to 0011, and 0011 & 0001 is equal to 0001 (as bitwise-AND operator leaves only the 1s that occur in both right-hand side and left-hand side of the equation). 0001 is not equal to 0, so the if-case would be evaluated to true.


Wednesday, 29 May 2013

Installing Visual Studio 2012 and starting with C#

C# is not too difficult to learn if you are familiar with the concept of object-oriented programming. When I first started learning C#, I had been programming in Java for most of my projects, with a little bit of experience in C and C++. It didn't take long to feel almost as natural as Java, and to actually appreciate some neat features it provides. 

You can start by installing an IDE for C#. If you are running Linux, you can use MonoDevelop or some other tools of your choice, but I would recommend using Visual Studio on Windows as there is a large support base and many useful extensions available. 



1. Install Visual Studio

Visual Studio Express can be downloaded from official MS website for free. You will be required to register after 30-day trial period, but you can continue to use the product for free after registration.



2. Create a solution

 Click "Create New Project" to create a solution (a collection of projects, such as Class Library or Windows application, that forms a program), select "Console Application"  and you will see there is one project (called ConsoleApplication1 by default) created with a class file called Program.cs.





3. Write the code



Now that we are ready, we can start with a "Hello World" program (as usual). You only need to add one line of code in the template created;


System.Console.WriteLine() is similar to printf() in C, or System.out.println() in Java. It simply means that 'WriteLine()' method is defined within the namespace called System.Console and need to be accessed by specifying it, unlike built-in function 'printf()' in C. Namespaces are used to organise methods into groups, or to disambiguate methods with the same name (you can think of it as a method/class group, or like packages in Java). Namespaces can be omitted by having 'using' clauses at the top instead.


Now the hello-world program is ready. Press Ctrl+F5 to build and run the project.