Decimal 2 Binary

By DimitriC at February 21, 2012 11:23
Filed Under: Programming, tips & tricks

From time to time I get a fun question. One of them was this: Please provide a list with powers of 2 accompanied by their binary representation, for let’s say up to 50.

 

First version:

 

   1:  int temp=1;
   2:   
   3:  for(int i = 1; i<=50; i++)
   4:  {
   5:      Console.WriteLine(i+": Dec: "+temp+" - Bin: "+Convert.ToString(temp,2));
   6:      temp = temp*2;
   7:  }

 

This gives the following result:

 

image

 

Here we bump into the maximum of information that can be held by an integer. So for going up to 50, it suffices to change the type of the decimal number to long:

 

   1:  long temp=1;
   2:   
   3:  for(int i = 1; i<=50; i++)
   4:  {
   5:      Console.WriteLine(i+": Dec: "+temp+" - Bin: "+Convert.ToString(temp,2));
   6:      temp = temp*2;
   7:  }

image

So, I could answer the question. But the same problem occurs when you come to the limit of the long-data type (which is at 64).

 

Double, float or decimal are not supported by the Convert.ToString(…) implementation where you can define the toBase-parameter.

What is "binding" and what makes it late?

By DimitriC at February 14, 2012 08:39
Filed Under: Programming, Training

Another interesting post on Eric Lipper’s blog. In this post, he explains his understanding of the concept of “late binding” (with a couple of small samples).

 

Read the full article here.

Read geographical information from the Windows Regional and Language Settings

By DimitriC at December 13, 2011 08:19
Filed Under: Programming, tips & tricks

Recently I got a question of how in .NET it was possible to read from the Windows Regional and Language Settings. Rather than messing around with the Windows registry, the best way to get this information is to use the RegionInfo-object in the System.Globalization namespace.

 

The code:

 

First of all, don’t forget to add the correct using statement:

   1:  using System.Globalization;

After that it’s just declaring the RegionInfo object and reading the settings you’d like (for the example, i’m reading all the settings):

 

   1:  RegionInfo local = RegionInfo.CurrentRegion;
   2:   
   3:  Console.WriteLine("CurrentEnglishName: "+local.CurrencyEnglishName);
   4:  Console.WriteLine("CurrencyNativeName: " + local.CurrencyNativeName);
   5:  Console.WriteLine("CurrencySymbol: " + local.CurrencySymbol);
   6:  Console.WriteLine("DisplayName: " + local.DisplayName);
   7:  Console.WriteLine("EnglishName: " + local.EnglishName);
   8:  Console.WriteLine("GeoId: " + local.GeoId);
   9:  Console.WriteLine("IsMetric: " + local.IsMetric);
  10:  Console.WriteLine("ISOCurrencySymbol: " + local.ISOCurrencySymbol);
  11:  Console.WriteLine("Name: " + local.Name);
  12:  Console.WriteLine("NativeName: " + local.NativeName);
  13:  Console.WriteLine("ThreeLetterISORegionName: " + local.ThreeLetterISORegionName);
  14:  Console.WriteLine("ThreeLetterWindowsRegionName: " + local.ThreeLetterWindowsRegionName);
  15:  Console.WriteLine("TwoLetterISORegionName: " + local.TwoLetterISORegionName);
  16:  Console.WriteLine("ToString: " + local.ToString());

 

image

 

NOTE: Notice that the ToString() method is also implemented for this class. So calling RegionInfo.CurrentRegion.ToString() will give you the TwoLetterISORegionName.

Read from the Windows Registry using C#

By DimitriC at December 08, 2011 09:49
Filed Under: Programming, Windows, tips & tricks

I’ve added an example in the MSDN Samples repository which explains how to read values from the Windows Registry.

 

Description:

 

The example is a simple Console-application that shows you how to select the correct RegistryHive, and afterwards navigate to the correct key and read the value. Keep in mind that reading from the Windows registry always returns an object of type 'object' so you'll need to cast this value to something that makes more sense. This means that you'll be expected to know what you're going to read (integer, binary, string,...). And last but not least, don't forget to add the Microsoft.Win32 using statement!

The available RegistryHives you can read from (and their corresponding names in the Registry Editor (Start => Run => regedit.exe):

  • - ClassesRoot (in RegEdit: HKEY_CLASSES_ROOT)
  • - CurrentConfig (in RegEdit:HKEY_CURRENT_CONFIG)
  • - CurrentUser (in RegEdit:HKEY_CURRENT_USER)
  • - DynData (Windows' own hive with dynamic data. Some configuration information in Windows must be stored in RAM because it requires fast modification and retrieval that cannot wait for the registry to send it to the hard disk. You can find all this data in the HKEY_DYN_DATA registry key. The information in this key is newly created every time Windows starts. Not visible in RegEdit)
  • - LocalMachine (in RegEdit:HKEY_LOCAL_MACHINE)
  • - PerformanceData (Is used to access performance counters but is not visible in Regedit)
  • - Users (in RegEdit:HKEY_USERS)

You can find the example here.

Microsoft All-in-one code framework

Something I found that might come in handy:

 

The Microsoft All-In-One Code Framework is a free, centralized code sample library driven by developers' needs. Our goal is to provide typical code samples for all Microsoft development technologies, and reduce developers' efforts in solving typical programming tasks.

 

Codeplex page

Download (from Codeplex)

Request a code sample

 

For a full list of downloads (sorted by technology), please check the Codeplex download page. There are samples available for C++, ASP.NET, Silverlight, Azure, Office, Windows, WPF, Windows Security, and many more…

The Job Interview: Technical questions (Pt. IV)

By DimitriC at March 21, 2011 19:56
Filed Under: Programming, Training

An often requested piece of code is a sort algorithm. Of course, there are many sorting algorithms as you can see with our good friend wikipedia. A popularly one is the Bubble sort. In it’s essence it’s not a difficult algorithm once you know how it works. But in interviews it’s usually the case that you haven’t had to implement it for a long time or maybe you’ve just graduated and have never heard of it (but then you shouldn’t have graduated or the people responsible for your curriculum need a good talking to!) A good alternative for the bubble sort is the Insertion sort.

 

A short description:

 

“…a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. “ – Source: Wikipedia

The algorithm:

   1: void BubbleSort(int[] intArray)
   2: {
   3:     int tmp;
   4:     for (int i = intArray.Length - 1; i >= 0; i--)
   5:     {
   6:         for (int j = 1; j <= i; j++)
   7:         {
   8:             if (intArray[j - 1] > intArray[j])
   9:             {
  10:                 tmp = intArray[j - 1];
  11:                 intArray[j - 1] = intArray[j];
  12:                 intArray[j] = tmp;
  13:             }
  14:         }
  15:     }
  16: }

 

 

An example of using the method above:

 

   1: void Main(string[] args)
   2: {
   3:     int[] intArray = new int[] { 2, 8, 4, 9, 5, 1 };
   4:     PrintArray(intArray);
   5:     BubbleSort(intArray);
   6:     Console.WriteLine();
   7:     PrintArray(intArray);
   8:  
   9:     Console.ReadKey();
  10: }
  11:  
  12: public static void PrintArray(int[] intarray)
  13: {
  14:     foreach (int number in intarray)
  15:     {
  16:         Console.WriteLine(number);
  17:     }
  18: }

 

…gives the following output:

 

image

The Job Interview: Technical questions (Pt. III)

By DimitriC at March 14, 2011 19:22
Filed Under: Programming

Another fun question is when during a technical interview, they ask you to write a recursive program to display Fibonacci numbers.

 

The definition (from wikipedia, link above):

 

“By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.”

 

The definition might give you a clue on how to solve this recursively since every result is the sum of the previous 2 result. What I’ve done is to create a method to calculate this that takes the number of times the recursion has to occur as a parameter:

 

   1: int Fibonacci(int x)
   2: {
   3:     if (x <= 1)
   4:         return 1;
   5:     return Fibonacci(x - 1) + Fibonacci(x - 2);
   6: }

 

Of course, this means that you will have to call this method from a loop-statement where you can say how many recursions you want:

 

   1: public static void Main()
   2: {
   3:     for (int i = 0; i < 10; i++)
   4:     {
   5:         Console.WriteLine(Fibonacci(i));
   6:     }
   7:  
   8:     Console.ReadKey();
   9: }

 

So this main-method will call the Fibonacci method 10 times, which gives the following output:

 

image

The Job Interview: Technical questions (Pt. II)

By DimitriC at March 09, 2011 19:10
Filed Under: Programming, Training, tips & tricks

Let’s have a look at a binary tree. In my implementation of the binary tree, I use a property to keep track of the fact that the node in question is the root node (= the node where the tree begins), the Parent-property. This refers to the node that has the current node as one of it’s children (or leafs). You can of course browse through your entire tree to find the node that’s not referenced by any other node, but that will probably take a lot of checks, especially if you have a big binary tree. Even when it’s a small binary tree I would use this property. It makes it easier to navigate through the tree.

 

   1: public class BTNode
   2: {
   3:     public BTNode LeftNode { get; set; }
   4:     public BTNode RightNode { get; set; }
   5:     public BTNode Parent { get; set; }
   6:  
   7:     public int value;    
   8:  
   9:     public BTNode(int val)
  10:     {
  11:         this.value = val;
  12:     }
  13:  
  14:     public void AddNode(BTNode newNode)
  15:     {
  16:         newNode.Parent = this;
  17:  
  18:         if (newNode.value >= this.value)
  19:         {
  20:             if (RightNode == null)
  21:             {
  22:                 RightNode = newNode;
  23:             }
  24:             else
  25:             {
  26:                 RightNode.AddNode(newNode);
  27:             }
  28:         }
  29:         else
  30:         {
  31:             if (LeftNode == null)
  32:             {
  33:                 LeftNode = newNode;
  34:             }
  35:             else
  36:             {
  37:                 LeftNode.AddNode(newNode);
  38:             }
  39:         }
  40:     }
  41:  
  42:     public BTNode Search(int srchValue)
  43:     {
  44:         if (srchValue == this.value)
  45:         {
  46:             return this;
  47:         }
  48:  
  49:         if (srchValue >= this.value)
  50:         {
  51:             if (this.RightNode == null)
  52:             {
  53:                 return null;
  54:             }
  55:             else
  56:             {
  57:                 return this.RightNode.Search(srchValue);
  58:             }
  59:         }
  60:         else
  61:         {
  62:             if (this.LeftNode == null)
  63:             {
  64:                 return null;
  65:             }
  66:             else
  67:             {
  68:                 return this.LeftNode.Search(srchValue);
  69:             }
  70:         }
  71:     }
  72:  
  73:     public void Delete()
  74:     {
  75:         //bottom of tree
  76:         if (this.LeftNode == null && this.RightNode == null)
  77:         {
  78:             if (this.Parent.LeftNode.value == this.value)
  79:             {
  80:                 this.Parent.LeftNode = null;
  81:             }
  82:             else
  83:             {
  84:                 this.Parent.RightNode = null;
  85:             }
  86:         }
  87:  
  88:         //Middle of tree - RightNode
  89:         if (this.LeftNode == null && this.RightNode != null)
  90:         {
  91:             if (this.Parent.LeftNode.value == this.value)
  92:             {
  93:                 this.Parent.LeftNode = this.RightNode;
  94:             }
  95:             else
  96:             {
  97:                 this.Parent.RightNode = this.RightNode;
  98:             }
  99:         }
 100:  
 101:         //Middle of tree - LeftNode
 102:         if (this.LeftNode != null && this.RightNode == null)
 103:         {
 104:             if (this.Parent.LeftNode.value == this.value)
 105:             {
 106:                 this.Parent.LeftNode = this.LeftNode;
 107:             }
 108:             else
 109:             {
 110:                 this.Parent.RightNode = this.LeftNode;
 111:             }
 112:         }
 113:  
 114:         if (this.LeftNode != null && this.RightNode != null)
 115:         {
 116:             if (this.Parent == null)
 117:             {
 118:                 throw new ApplicationException("You can not delete the root node!");
 119:             }
 120:  
 121:             if (this.Parent.LeftNode.value == this.value)
 122:             {
 123:                 this.Parent.LeftNode = this.LeftNode;
 124:                 this.LeftNode.RightNode = this.RightNode;
 125:             }
 126:             else
 127:             {
 128:                 this.Parent.RightNode = this.RightNode;
 129:                 this.RightNode.LeftNode = this.LeftNode;
 130:             }
 131:         }
 132:     }

 

To use it, you instantiate a node and assign new BTNodes to the leaves. Wherever you are in the tree-structure, you’ll find it easy to search for nodes. Keep in mind that the AddNode and Delete only reflect on the current node.

The Job Interview: Technical questions (Pt. I)

By DimitriC at March 01, 2011 08:56
Filed Under: Programming, Training

Ever since I graduated I’ve been employed as a .NET consultant. When applying for jobs (whether it’s at a consultancy firm or as a representative of your firm getting interviewed by a client) there is often a technical interview. Next to the fun object-orientation questions we all love so much (explain polymorphism, data abstraction, inheritance, Liskov’s substitution principle,…), there were sometimes these little exercises they used to test your approach to problem solving or to see how you react to a very unfamiliar problem. These questions can take different forms. You’ve got you’re here-is-a-piece-of-code-and-tell-me-what-the-output-is-questions, mathematical problems, writing code,…Even brain-teasers can be a part of the interview. 

 

In the “writing code” department you can be asked to write well known data structures yourself (e.g.: write your own linked list/binary tree), write an algorithm (sorting algorithm,search algorithm, reversing collections,…). The meaning of this series is to discuss some of these questions, find out where the pitfalls are and see what side-questions might be added to the exercise.

 

So let’s get to it! As a first exercise, let’s look at an implementation of a linked list.  In the .NET Framework, you can find a linked list in the System.Collections.Generic library.

 

For our basic implementation we need a Node-class where we can hold the references for the previous and the next item in the list. We’ll immediately keep references to both the next and the previous node as we’ll notice that it might be handy to navigate through the list. This is already a more complex version of a linked list (since the most simplistic version only holds the reference to the next node).

 

   1: public class Node
   2: {
   3:     private Node prevNode;
   4:     private Node nxtNode;
   5:     private string strValue;
   6:  
   7:     public Node(Node prevNode, Node nxtNode, string stringValue)
   8:     {
   9:         this.prevNode = prevNode;
  10:         this.nxtNode = nxtNode;
  11:         this.strValue = stringValue;
  12:     }
  13:  
  14:     public Node PrevNode
  15:     {
  16:         get { return this.prevNode; }
  17:         set { this.prevNode = value; }
  18:     }
  19:  
  20:     public Node NxtNode
  21:     {
  22:         get { return this.nxtNode; }
  23:         set { this.nxtNode = value; }
  24:     }
  25:  
  26:     public string StringValue
  27:     {
  28:         get { return this.strValue; }
  29:         set { this.strValue = value; }
  30:     }
  31:  
  32:     public void Delete()
  33:     {
  34:         this.prevNode.nxtNode = this.nxtNode;
  35:         this.nxtNode.prevNode = this.prevNode;
  36:     }
  37: }

 

This is a basic node-class. As a value I chose a string, but of course, that can be anything you want. This node is what we’ll use to create our list. We’ll have a list-object that contains the first node, and of course, since each node points to the next one in the list, the list-object will contain all the methods to navigate through the list.

 

   1: public class LinkedList
   2: {
   3:     public LinkedList(string stringValue)
   4:     {
   5:         nCurrent = new Node(null, null, stringValue);
   6:         nCurrent.NxtNode = null;
   7:         nCurrent.PrevNode = null;
   8:     }
   9:  
  10:     int iCount = 1;
  11:     int iCurrent = 0;
  12:     Node nCurrent;
  13:  
  14:     public int Count 
  15:     { 
  16:         get{return this.iCount; }
  17:     }
  18:  
  19:     public Node CurrentNode 
  20:     { 
  21:         get{return this.nCurrent;}
  22:     }
  23:  
  24:     public Node CurrentNodeIndex 
  25:     { 
  26:         get{return this.nCurrent;}  
  27:     }
  28:  
  29:     public void AddNode(string strValue)
  30:     {
  31:         if (nCurrent.NxtNode == null)
  32:         {
  33:             nCurrent.NxtNode = nCurrent;
  34:             nCurrent = new Node(nCurrent, null, strValue);
  35:         }
  36:         else
  37:         {
  38:             nCurrent.NxtNode = nCurrent;
  39:             nCurrent = new Node(nCurrent, nCurrent.NxtNode, strValue);
  40:         }
  41:         iCount++;
  42:         iCurrent++;
  43:     }
  44:  
  45:     public void ToNext()
  46:     {
  47:         Node tmpNode = null;
  48:  
  49:         if (nCurrent.NxtNode == null)
  50:         {
  51:             throw new Exception("there is no next node!");
  52:         }
  53:         else
  54:         {
  55:             tmpNode = nCurrent;
  56:             nCurrent = nCurrent.NxtNode;
  57:             nCurrent.PrevNode = tmpNode;
  58:             iCurrent++;
  59:         }
  60:     }
  61:  
  62:     public void ToPrevious()
  63:     {
  64:         Node tmpNode = null;
  65:  
  66:         if (nCurrent.PrevNode == null)
  67:         {
  68:             throw new Exception("there is no previous node!");
  69:         }
  70:         else
  71:         {
  72:             tmpNode = nCurrent;
  73:             nCurrent = nCurrent.PrevNode;
  74:             nCurrent.NxtNode = tmpNode;
  75:             iCurrent--;
  76:         }
  77:     }
  78:  
  79:     public void GoTo(int index)
  80:     {
  81:         while (iCurrent != index)
  82:         {
  83:             if (iCurrent < index)
  84:             {
  85:                 ToNext();
  86:             }
  87:             else if (iCurrent > index)
  88:             {
  89:                 ToPrevious();
  90:             }
  91:         }
  92:     }
  93:  
  94:     public void First()
  95:     {
  96:         while (nCurrent.PrevNode != null)
  97:         {
  98:             ToPrevious();
  99:         }
 100:     }
 101: }

Now you can instantiate the list. The constructor also requires a string value to define your first element in the list. Then you’ll find the methods to navigate through the list. And the nCurrent-property of the Linked List will contain the node where you navigated to.

 

A possible variation you might get asked is a circular linked list. This means that the last element you add (which points to null) actually should point to the first element in the list. For a full theoretical explanation I refer to wikipedia.

Free e-books on .NET and architecture

By DimitriC at October 12, 2010 08:07
Filed Under: Architecture, Books, Microsoft, Programming, tools & Utilities, Training

The new MSDN Flash arrived this morning, and it offered 7 free e-books (actually 6 e-books and some reference cards) on .NET and architecture. For the original article that was posted in the newsletter, click here.

 

The books:

 

- Foundations of programming (Karl Seguin)
- Microsoft Application Architecture Guide, 2nd Edition (Microsoft)

- Rob Miles C# Yellow Book 2010 (Rob Miles)

- Threading in C# (Joe Albahari)

- Improving .NET Application Performance and scalability (Microsoft)

- Applying Design Patterns (Anoop Madhusudanan)

 

And some References Cards (RefCardz) from DZone:

 

- Getting Started with WCF 4.0 (Scott Seely)

- Getting Started with Silverlight + Expression Blend (Victor Gaudioso)

- Essential F# (Chance Coble, Ted Neward)

Log4Net logging framework, custom AdoNetAdapter and RollingFileAppender with XML

By DimitriC at October 04, 2010 10:00
Filed Under: Architecture, log4net, Programming, tips & tricks, tools & Utilities

Mike Bevers has done some cool work with log4net. Next to creating his own logging framework using L4N, he also implemented a custom AdoNetAdapter (logging to a database) and a RollingFileAppender with XML.

 

For more information, please check his blog, or the Log4Net posts:

 

- Logging Framework with Log4Net
- Log4Net: custom AdoNetAppender
- Log4Net: RollingFileAppender with XML

Generics part III: Constraints

By DimitriC at October 03, 2010 13:36
Filed Under: Programming

There are three kinds of type parameter constraints. There are primary constraints, secondary constraints and constructor constraints. The number of constraints that you can specify depends on the type of constraint, as shown in this table:

 

Constraint Type Allowed
Primary Constraint 0 or 1
Secondary Constraint 0 or more
Constructor Constraint 0 or 1

 

When applying primary constraints you actually make a deal with your compiler. The deal says that the type parameter you will pass on is of a certain type OR derived from this type. For example: if you have a system where you do the management of vehicles, you might have your model have a base class Vehicle, and some derived types: Car, Truck, Boat and Airplane. The syntax looks like this:

 

   1: internal sealed class ExampleOfConstraintOfVehicle<T> where T : Vehicle
   2: {
   3:     public void DoSomething(T vehicle)
   4:     {
   5:         //...do something with the vehicle
   6:     }
   7:
 

Now, when instantiating this class with something that isn’t a vehicle, you will get an error at compile time:

 

The type '[type]' must be convertible to 'SystemObject.Vehicle' in order to use it as parameter 'T' in the generic type or method 'SystemObject.Program.ExampleOfConstraintOfVehicle<T>'

 

You can also tell your compiler that the type you will pass along as a type parameter is a reference type or a value type. This is done by using the “class” or “struct” keyword. So changing the example above will result in the following:

 

Reference type:

internal sealed class ExampleOfConstraintOfRefType<T> where T : class

 

Value type:

internal sealed class ExampleOfConstraintOfValType<T> where T : struct

 

Secondary constraints represent interface types. Here your deal with the compiler says that any type you pass along as a type argument will implement that interface. The table in the beginning of the post mentions that 0 or more secondary constraints are allowed. This is logical since a class can implement several interfaces and so you can also demand that a secondary constraint checks that a number interfaces is implemented in the type argument.

 
internal sealed class ExampleOfConstraintOfIConstraint<T> where T : ICloneable

 

Again, here the argument is checked at compile time. If you pass a type argument that doesn’t comply with the constraint, you will see the following error:

 

'The type '[type]' must be convertible to '[IConstraint]' in order to use it as parameter 'T' in the generic type or method 'SystemObject.Program.ExampleOfConstraintOfIConstraint<T>'

 

Another type of constraints are the constructor constraints. Here the deal with the compiler is that the type argument you’re passing along implements a default constructor (public and no parameters). Passing a constructor with parameters is not possible.

Generics Part II: internals

By DimitriC at September 26, 2010 17:57
Filed Under: Programming

When the CLR builds our application, it will make an internal structure for each type we use in the application. The generic types we create are no different, on the condition that the generic type parameters have values assigned to them. If these parameters don’t have values (data types) assigned to them they are called an “open type” and the CLR will not allow the construction of such a type (because basically, the CLR doesn’t know what to build exactly). If the data type parameters are properly filled in, the CLR will create internal types for these objects. This is called a “closed type”.

 

When the compiling code that uses generic type parameters, the compiler generates IL, fills in the parameters and generates native code specific to that method for those types. This is exactly the same as how other code is compiled and is an advantage of generics (it behaves as you would expect). Of course, since no good deed goes unpunished, there is a down side to this. The CLR keeps generating native code for every method-type combination possible. This can increase the amount of memory required by your application enormously. This is called “code explosion”.

At Microsoft they were fully aware of this, so the CLR has built in optimizations to counter code explosion. The CLR will keep track of the method-type combinations it generates code for. If the same method-type combination is used somewhere else in the code, it will use the already generated IL-code. If you have several assemblies in your application that use List<string>, the CLR will emit code just once and re-use this code. Also, if you are using reference type arguments, the code for these types are only generated once. This is because the CLR thinks of all reference type arguments as the same (to the CLR these are all just pointers). Unfortunately, the issue with value types remains. Here the CLR must emit code for each type individually. Even if these types are basically the same (e.g.: Int32 and UInt32), every type will have its own native code since different native processor-instructions can be used to work with these values.

 

The following is something that you may not have heard of by name, but you’ve certainly used it, which is “type inference”. This concept is supported by the C# compiler and allows you not to define every type when assigning it.

 

For example:

 

Int32 number = 5;
String someText = “Some text”;

 

Here the compiler will check the type of the value (let’s say: “Some Text”), it will recognize the value as type String and see that you want to assign it to an object of type String, and so the compiler will assign the value to the object without complaining. You can see the problem that might arise when using generics. If you call a generic method without specifying a type, you will get a compiler error (error CS0411). I got a great example for this in Jeffrey Richter's book CLR via C#:

 

   1: private static void Display(String s) 
   2: {
   3:   Console.WriteLine(s);
   4: }
   5:  
   6: private static void Display<T>(T o) 
   7: {
   8:   Display(o.ToString()); 
   9: }
  10:  
  11: //In main:
  12: Display("Jeff"); 
  13: Display(123); 
  14: Display<String>("Aidan"); 

 

The compiler always looks for an exact match when calling methods. So the first call will go directly to the Display()-method that takes a string as an argument. And the third call will go to the generic overload of the Display()-method. The nice thing here is the second call. There is no specific overload of the Display()-method that takes an integer as a parameter. So, the compiler will settle for the generic match. It can define the type of “123” (which is Int32), so it can call the generic overloaded version of the Display()-method and gives the following output (I’ve added some extra text to point out what method is being called):

 

clip_image002

Generics Part I

By DimitriC at September 19, 2010 11:38
Filed Under: Programming

Generics are another feature of the .NET Framework Common Language Runtime (CLR). It was introduced in .NET Framework 2.0 and has been around ever since. The basic principle is the re-use of code. As a developer, you often find yourself with a collection of data (collection of objects) on which you need to perform an action (search, sort, insert at a certain position, comparing,…). What makes generics so useful is that none of these algorithms are defined to a type. It is up to you to define this type. After you’ve defined the type, every action performed on the collection will use that type, so it’s type safe. Everything concerning generics is comprised in the System.Collections.Generic namespace. Often used types are List<T>, Dictionary<TKey,TValue>, LinkedList<T>,… The ‘T’ of course stands for the type argument.

 

Meaning if you want to create a list of strings, you can define one, and use the Add()-method to fill your collection. Do note that here again type safety comes into play. Since you have defined your collection as a collection of strings, the parameter you can assign to the Add()-method will have to be of type string. You can see this when looking at the list of methods that are implemented on List<T>.

 

   1: List<string> listOfStrings = new List<string>();
   2:  
   3: listOfStrings.Add("This is the first string");
   4: listOfStrings.Add("second string");
   5: listOfStrings.Add("third");
   6:             
   7: foreach (string s in listOfStrings)
   8: {
   9:     Console.WriteLine(s);
  10: }

 

Running the application will give the following output:

clip_image002

 

As Jeffrey Richter mentions in his book CLR via C#, the most important benefits of generics are source code protection, type safety, cleaner code and better performance. I’ve already mentioned the topic of type safety earlier. “Source code protection” means that the developer that uses the code, doesn’t has to have access to it. In our case of a List<T>, that means that you can call the Sort()-method, but the source code is hidden from you. Cleaner code is a result of type safety, since you don’t have to cast from one type to another all the time. The better performance benefit is actually a logical consequence of re-using code and code protection.

 

Many algorithms for sorting, searching,… have been implemented thousands of times over the years. And instead of constantly re-inventing these algorithms, one good, re-usable implementation will do. This is what generics provides us. Now of course, you need to tweak these algorithms so they will work for you. As long as you are working with primitives (as in the example above), there won’t be a problem. But if you are working with classes of your own, you will have to do your own implementation of the Equals() and GetHashcode() method. If you don’t have your own implementation of these methods, the default methods (provided by System.Object) will be used. As mentioned in previous posts the Equals()-method’s default implementation compares reference addresses. Microsoft, on its part, has done a great effort to implement generics. They had to create new IL (Intermediate Language) instructions and reflection members, modify metadata tables, modify the language implementations to support the new syntax, modify compilers,…

Objects part IV: something new

By DimitriC at September 12, 2010 16:33
Filed Under: Programming

The “new” operator is generally used to create new objects. When you do something like:

 

Car car1 = new Car("blue", 4, "Volkswagen", "Golf");

 

A new object of that type is created and a reference is saved into “car1”.

What happens here is that every time you use the new-operator, it checks how many bytes of memory you need for your object. This is the sum of the bytes of all properties, references to other objects and the properties of these objects plus some extra information for you object such as the object pointer, which is used by the garbage collector. After figuring out how many bytes are required on the managed heap, it actually allocates these bytes and sets them all to 0. If it can’t allocate enough space that is required for your new object, an OutOfMemory-exception is thrown. Now, before actually creating the object, the extra-information properties (such as the object pointer) are initialized. You can see this as a set of information that is required so the CLR can manage your object. Now the object’s constructor is called. Now if your object is derived from another object, the constructor emits code to call the constructor of the base class. Of course, every constructor is responsible for setting the class’ parameters to an initial (default) value. You can find the list of initial values on MSDN. Even if your class isn’t inherited from another class, the code for calling the System.Object-constructor is emitted, since System.Object is the base for every object created by the CLR. Object’s constructor is empty, and just returns.

 

The “new”-keyword can also be interpreted as a modifier. This can be done if you want to explicitly hide a member from an inherited class. For example, if our Car-class would inherit from a Vehicle-class that had a method defined, and you would implement this same method in the Car-class, you would get a warning.

 

Vehicle class:

   1: public class Vehicle
   2: {
   3:
   4:  
   5:     public void DoSomething()
   6:     {
   7:         Console.WriteLine("I'm doing something in the Vehicle class");
   8:     }
   9:
  10: }

 

 

Car class:

 

   1: public class Car
   2: {
   3:
   4:  
   5:     public void DoSomething()
   6:     {
   7:         Console.WriteLine("I'm doing something in the Car class");
   8:     }
   9:
  10: }

 

The warning:

clip_image002

 

Changing the Car class with the ‘new’ modifier results in resolving the warning:

 

   1: public class Car
   2: {
   3:
   4:  
   5:     new public void DoSomething()
   6:     {
   7:         Console.WriteLine("I'm doing something in the Car class");
   8:     }
   9:
  10: }

 

 

Now that we’ve done all that, we can safely say that if you have to use this ‘new’ modifier…you’re doing something wrong somewhere. A better way is to define the method in your base class as virtual (which basically means that if someone is inheriting your class, that person is allowed to implement his own version of that method in his class). If someone wishes to implement his own version of that method in his class, he can use the override method to do so, without any warnings being generated.

Objects part III: GetHashCode, GetType and ToString

By DimitriC at August 29, 2010 11:41
Filed Under: Programming

GetHashCode

 

A hash code is a number that represents your object. This number is not only used in hashing algorithms but it can help when comparing two objects (if their hash code is equal, the objects are equal). The problem here is that the hash code doesn’t necessarily give you a unique number. This can be seen when working with the TimeSpan or DateTime object since its GetHashCode implementation is based on the Ticks-property. Also, the value returned by this method is platform dependent. Meaning, the method will give you different values depending if you are running on 32-bit or 64-bit versions of the .NET Framework. So, when do we use this? Mostly when working with hash table collections. The GetHashCode() method is called if your object is used as a key in a collection.

Again, MSDN provides us with a list of rules that a decent implementation of the GetHashCode-method must obey to have a desired behavior:

 

· If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

· The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.

· For the best performance, a hash function must generate a random distribution for all input.

· Implementations of GetHashCode must not throw exceptions

· Derived classes that override GetHashCode must also override the Equals method to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly

In our example, we can let GetHashCode return the ChassisNumber-value.

 

GetType

 

This returns an object of type Type, which describes the type of the calling object. This object of type Type gives access to the metadata linked to the class of the calling object. This is very interesting in the context of reflection. This method can’t be overridden which is normal, since it would enable you to change the return value of this method. Basically, allowing you to lie. This can cause many problems concerning type safety. Or can cause strange behavior in a situation where you, at runtime, look at an object using GetType() to see what type it is and extract information from the object. Imagine I could let my Car-class claim it was of type House. Trying to access let’s say the address-property would result in an error at runtime.

 

ToString

 

By default this returns the name of the type of the object on which the method is called. So what it returns is GetType().ToString(). The ToString()-implementations of the Type-object actually returns the full name of the object. This method is frequently overridden. The .NET basisc data types have this method overridden to return a string-representation of their value (Boolean, Char, Double, Decimal,…). When looking at the overridden ToString-methods of numbers (Int, Decimal, Double, Single) using a tool like .NET Reflector, notice that CultureInfo is taken into account in the form of NumberFormatInfo and implementing IFormattable. This will format the value of the object to the correct textual representation (commas, currency information)

 

Implementing this is as easy as for the other methods.

   1: public override string ToString()
   2: {
   3:     return "Chassis Number: " + this.ChassisNumber + " - Brand: " + this.Brand + " - Model: " + this.model;
   4: }

From the main program, you can simply call the ToString() method on the car object:

 

Console.WriteLine(car1.ToString());

 

clip_image002

Objects part II: Equals

By DimitriC at August 22, 2010 14:05
Filed Under: Programming

Note: The code samples are based on Part I of the series.

 

This method returns “True” if both objects have the same value. The default implementation of this method checks if two reference type objects point to the same object. Now this isn’t always the desired behavior. In many cases you want to compare the value(s) of a property/ies within your object to let you know if you’re dealing with the same object. To show the default implementation, I will create two instances of the Car-class with the same values for the properties:

 

   1: private Car car1 = new Car("blue", 4, "Volkswagen", "Golf");
   2: private Car car2 = new Car("blue", 4, "Volkswagen", "Golf");

 

Then compare these objects:

car1.Equals(car2)

Gives as output: False.

Now we know that the parameters are exactly the same, but of course, these are two separate instances of the Car-class so the references are different. Now let’s say we wish to compare these cars based on their properties. This will require me to do my own implementation of the Equals()-method. You probably have noticed that the default implementation takes an object of type Object as a parameter. In my own implementation I will also provide a type-safety, meaning that if I want to compare two objects, the object I give as a parameter is of the same type as the object I’m calling the Equals() from.

 

So I add the following code to the Car-class:

 

   1: public override bool Equals(object obj)
   2: {
   3:         Car c = obj as Car;
   4:                         
   5:          if(c != null)
   6:          {
   7:             if (this.Brand == comp_obj.Brand && 
   8:             this.Color == comp_obj.Color && 
   9:             this.Model == comp_obj.Model && 
  10:             this.NumberOfSeats == comp_obj.NumberOfSeats)
  11:             {
  12:                     return true;
  13:             }
  14:          }
  15:             return false;
  16:         }

 

When I execute the program again, the output now is “True”. Since every property of the car is the same, we can assume that both objects concern the same car. Now think about a car company/dealership/leasing company/… They have probably many cars with the same properties. So it’s interesting here to also have something unique about every car to add to your car-object. A license plate is probably not a good idea since a car that just got off the production chain hasn’t got a license plate yet. Maybe the chassis number is a better idea (In reality that is a 17-character combination of digits and letters, for the ease of the example, let’s keep it an integer).

 

Adding the new property to the car-class:

   1: private int chassisNumber;
   2:  
   3:         public int ChassisNumber
   4:         {
   5:             get { return chassisNumber; }
   6:             set { chassisNumber = value; }
   7:         }

 

Refactoring the Equals() method:

 

   1: public override bool Equals(object obj)
   2: {
   3:          Car c = obj as Car;
   4:                         
   5:          if(c != null)
   6:          {
   7:             if (this.ChassisNumber == comp_obj.ChassisNumber )
   8:             {
   9:                     return true;
  10:             }
  11:          }
  12:         
  13:          return false
  14: }

 

When you run the program again, the output is “False”, which is correct since we are talking about two different cars with the same properties.

A good implementation of the Equals() method can help you a great deal when sorting or searching a collection of objects. To help define what a “good” implementation is, MSDN defines a set of rules that your implementation must obey to:

 

· x.Equals(x) returns true, except in cases that involve floating-point types. See IEC 60559:1989, Binary Floating-point Arithmetic for Microprocessor Systems.

· x.Equals(y) returns the same value as y.Equals(x).

· x.Equals(y) returns true if both x and y are NaN.

· (x.Equals(y) && y.Equals(z)) returns true if and only if x.Equals(z) returns true.

· Successive calls to x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.

· x.Equals(null) returns false

· Implementations of Equals must not throw exceptions

SecureString

By DimitriC at July 29, 2010 17:54
Filed Under: Programming, Security

SecureString is an un-inheritable class which resides in the System.Security namespace. It holds an encrypted string and is disposed of when you’re done using it. This class is mostly used when you want to store a piece of sensitive information in memory (e.g.: social security numbers, bank account information,…). Of course, these are normally stored in encrypted form in the database, but when you are handling a user’s request (he/she is accessing his banking records, or shopping at an online store), at some point you will need the data from the database and use it in your application.

When you want to store some sensitive information in memory, the use of a string raises some issues. It’s immutable (every time you change it a new instance of the string is created) and can’t be deleted from the computer memory at will. So if you’re done using it, the string lives on in memory until it’s cleaned up by the garbage collector. Since you don’t know when this will happen (can be seconds, hours,…) your sensitive information is readable.

Of course, SecureString holds some textual information. Do note that the text you wish to keep in the SecureString-object needs to be added char by char (or when using the constructor, a char pointer and the length as an integer).

 

   1: string aString = "This is a string";
   2: SecureString secureString = new SecureString();
   3:  
   4: foreach (char c in aString)
   5: {
   6:     secureString.AppendChar(c);
   7: }
   8:  
   9: Console.WriteLine(aString);
  10: Console.WriteLine(secureString);

 

 

When you execute that code, you will see that the WriteLine-command using the securestring as a parameter will just give you the base.ToString() value (System.Security.SecureString). This is because SecureString doesn’t override the ToString()-method nor does it provide you with any of the methods available with the regular string-class (substring, indexOf, CompareTo, StartsWith,…)

Let’s have a look at what happens to your text when you use a SecureString. When you have assigned a value to your SecureString class, you can lock it by calling the MakeReadOnly() method. The value is encrypted using DPAPI (Data Protection API) which is the encryption layer used by Microsoft Windows. When you wish to use the value stored in the SecureString object, you will have to use the Marshal class (which can be found in the System.Runtime.InteropServices namespace). Among other things, this class provides methods for allocating unmanaged memory and copying unmanaged memory blocks. This includes methods that will convert the contents of your SecureSting object into an object of type BSTR (basic string or binary string) or a block of ANSI or Unicode memory. Just reading the memory block will only give you the binary data stored in the memory block.

 

   1: string aString = "This is a string";
   2: SecureString secureString = new SecureString();
   3:  
   4: foreach (char c in aString)
   5: {
   6:     secureString.AppendChar(c);
   7: }
   8:  
   9: Console.WriteLine("Reading the regulare string: "+aString);
  10: Console.WriteLine("Reading the secure string: "+secureString);
  11: Console.WriteLine("Reading the secure string (using Marshal.SecureStringToBSTR): " + Marshal.SecureStringToBSTR(secureString));
  12: Console.WriteLine("Reading the secure string (using Marshal.SecureStringToGlobalAllocAnsi): " + Marshal.SecureStringToGlobalAllocAnsi(secureString));
  13: Console.WriteLine("Reading the secure string (using Marshal.SecureStringToGlobalAllocUnicode): " + Marshal.SecureStringToGlobalAllocUnicode(secureString));

 

 

Output:

clip_image002


We can see that the Marshal-methods have gotten something out of the SecureString class, but we can’t do much with those things. To read this memory block in a manner which will present us with a string-representation the Marshal-class provides a PtrToStringBSTR() method. The parameter which you need to provide here is a pointer to the memory-block where your contents are stored. First, we need to create that pointer using the SecureStringToBSTR method (also provided by the Marshal class).

 

   1: IntPtr ptrToString = Marshal.SecureStringToBSTR(secureString);
   2: Console.WriteLine("Contents of ptrToString: " + ptrToString);
   3: Console.WriteLine("Contents of memory at ptrToString as a string: " + Marshal.PtrToStringBSTR(ptrToString));

 


Output:

clip_image002[7]

 

When converting your SecureString object to a pointer , the needed unmanaged memory is allocated to store the string. This means you will always have to clean it up (free the pointer) when you no longer need the object. Again, the Marshal-class provides this possibility in the form of the ZeroFreeBSTR method. This ensures you that the contents of the SecureString object is in plain text only very briefly.

 

   1: Marshal.ZeroFreeBSTR(ptrToString);
   2: Console.WriteLine("Contents of memory at ptrToString as a string: " + Marshal.PtrToStringBSTR(ptrToString));
   3:  
   4: secureString.Dispose();

 

ptrToString still points to the memory allocated, but the contents have been cleared and calling the PtrToStringBSTR results into an empty string. SecureString inherits from CriticalFinalizerObject. This means that the finally-block of the SecureString object is always executed (even when the thread terminates abnormally).

Logging: Log4Net – Part III

By DimitriC at April 27, 2010 11:48
Filed Under: Programming, tools & Utilities

The idea in Part III is to talk about the more advanced features/settings of Log4Net.

 

First of all, in Part II we saw how we can load the log4net configuration from code by first creating a logger object and then reading the App.config file. You can also use the AssemblyInfo file to do this:

 

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

 

The Watch-flag will tell log4net to keep an eye on the configuration file and reload it every time it has changed. Of course you can also specify your own configuration file by using the ConfigFile property:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "LoggingConfiguration.config", Watch = true)].

 

There is also a parameter you can use if you want to load configuration files based on the extension of the file. Do not that the name of the configuration file must be [NameOfYourApp].[ExtensionYouWant]. In my sample application, in the build output, it needs to be Log4NetSample.exe.log4net before I can use the following line in my AssemblyInfo.cs file. This property cannot be used in conjunction with the ConfigFile property.

 

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension="log4net",Watch=true)]

 

Do note that this attribute can only be used once per assembly. Also note that these attributes are passive, meaning that as long as your application doesn’t need logging, they won’t be read. It is therefore recommended to make a simple call to LogManager.GetLogger() to read and process the attributes(for example: an informational log-statement saying the application has started). And on recommendation of the log4net-people themselves:

 

Therefore it is imperative to make a logging call as early as possible during the application start-up, and certainly before any external assemblies have been loaded and invoked.

 

There is another way to load a configuration file. You can do this by using the DOMConfigurator located in the log4net.Config class. The DOMConfigurator takes a FileInfo parameter. Using this does exactly the same thing as loading a file using an attribute in the AssemblyInfo. Two methods are provided: Configure(…) and ConfigureAndWatch(…).

 

log4net.Config.DOMConfigurator.Configure(new FileInfo("Log4netSample.exe.config"));

log4net.Config.DOMConfigurator.ConfigureAndWatch(new FileInfo("Log4netSample.exe.config"));

 

 

Threading and Log4net

Since Log4net is thread-safe, you can use it in your multithreaded applications. Next to all the logging information described in the Part II you can also let log4net know on which thread your application has thrown an exception. If your application/component is accessed by multiple clients (which can also be other components), you would like to know what client caused the exception to fire. To get all this information, log4net uses a context. Since debugging a multithreaded application is really hard and inconvenient, logging can give you all the information you need to research an error. Contextual information can be contained in different scopes:

 

- Global (shared by all threads in the current AppDomain)

- Thread (visible only to the current managed thread)

- Logical Thread (a logical thread can jump from one managed thread to another)

- Event (only visible to the code generating the event itself)

 

This information can also be found on the log4net web site.

 

To support logging on multithreaded applications, Log4net provides a ThreadContext. This has a properties map (formerly the Mapped Diagnostic Context or MDC, which has been deprecated) and a stack (formerly the Nested Diagnostic Context or NDC, which has also been deprecated). The use of a context is very interesting when dealing with client server architectures. Here the typical configuration is that you have many clients and only a few servers. Each client will be served by a thread on a server.

 

The properties map (Mapped Diagnostic Context)

 

The properties map allows you to store thread-specific information. In the configuration file, you can access these properties and add them in the PatternLayout-section. For example, let’s say you want to register who’s thread is causing an exception, you can add the username to the log by first inserting it as a property in the context:

 

   1: ThreadContext.Properties["user"] = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

 

You can show it in the logging output by adapting the PatternLayout-section and calling the user-property in the App.config file:

 

<layout type="log4net.Layout.PatternLayout">

             <conversionPattern value="%date %-5level %logger (User: %property{user}): %message%newline" />

</layout>

 

Now, where is this information stored? As previously mentioned, the Mapped Diagnostic Context is deprecated and has been replaced with the Properties-collection. Keep in mind that when inserting your properties to this collection will override any properties with the same name in the GlobalContext class. Here is where all the global debugging information is stored. When your properties are read for use in the log-output (so when using the PatternLayout), they are read from the GlobalContext.

 

 

 

The stacks (Nested Diagnostic Context)

 

As the name might give away, this is a stack implementation. Meaning, you can push a stamp (which is preferably something unique like a clientID/ServerID/user/machine name/… or a combination of these kinds of information) on the stack and every log call (whether it’s a informational, error or warning call) is marked with the stamp you provided. This will ensure you that you can recognize the entries in the log by the stamps attached to it. And just like with the properties map, you can add the stamp to the log output by configuring the PatternLayout, and this time using the ndc-property to include the stamp to the message:

 

<layout type="log4net.Layout.PatternLayout">

                  <conversionPattern value="%date %-5level %logger %ndc : %message%newline" />

</layout>

 

You can add messages to the stack in two ways. These are actually the same, but syntactically different.  You can either first push your stamp to the stack, then log what you need to log and pop the messages back from the stack.

   1: ThreadContext.Stacks["NDC"].Push("RecognizableStampOnNDCStack")
   2: ...
   3: log.ERROR("something went wrong");
   4: ThreadContext.Stacks["NDC"].Pop();

Or you can accomplish the same behavior with a using-statement. At the end of the using-statement, the Pop()-method is called automatically.

   1: using (ThreadContext.Stacks["NDC"].Push("RecognizableStampOnNDCStack"))
   2: {
   3:     ...
   4:     log.Error("something went wrong");
   5: }

 

Hierarchical logging

 

You can define a hierarchy of logging. This means you first define a default level of logging and every definition of logging that is placed after it, gives a more narrowing definition. For example:

 

<root>
<level value="ERROR" />
</root>
<logger name="MyAssembly">
	<level value="WARN" />
</logger>

 

This piece of XML in the configuration file (placed inside the log4net-tags) will ensure that every error in your application is logged and all the warnings in the MyAssembly-namespace too. In the name property you can also provide a class name. If the name in the example above would be “MyAssembly.MyClass”, then all the warnings in MyClass will be logged.

Get application version, build and build date

By DimitriC at April 13, 2010 15:09
Filed Under: Programming, tips & tricks

In one of my console applications I wanted to show the assembly version, build and build date in the console window.

 

For getting the assembly version and build, the System-namespace has a Version-object which has properties like MajorVersion, MinorVersion and Build that you can use. When you call the ToString()-method on this object, you will get the full version information.

   1: Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

Now you can use the properties to build your text message:

   1: string versionMsg = "Version: " + version.ToString() + " - Build: " + version.Build + ";

 

The problem is that the Build-property remains 0. To solve this, you must use wildcards in the AssemblyInfo.cs file. This will allow for a build-number to be generated:

   1: [assembly: AssemblyVersion("1.0.*")]

 

If you re-run the program, a build number will be visible.

 

Now getting the build date from all of this is tricky too. The Version.Build consists the number of days since January 1, 2000. The Version.Revision property counts the seconds since midnight which you have to multiply by 2 to get the original:

   1: DateTime buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + // days since January 1, 2000 
   2:     TimeSpan.TicksPerSecond * 2 * version.Revision)); // seconds since midnight, today

 

Now you have all the information you need to build the final versionMsg:

   1: string versionMsg = "Version: " + version.ToString() + " - Build: " + version.Build + " - Build Date: " + buildDateTime.ToString();