Vadim's Weblog

Never stop learning.

Archive for the ‘Coding’ Category

Shortcut Key to Comment code in VS and SQL Server Management Studio

Posted by Vadim on October 16, 2008

When we learn any programming language, one of the firsCtrl+Ct thing  we discover is the syntax how to comment our code.  Some of you probably already have been using this shortcut key for awhile.

Select multiple lines of code and press Ctrl+K,Ctrl+C, and you hard work is going to be ignored. To reverse just press Ctrl+K,Ctrl+U

These keystrokes will comment/uncomment your code only with line comment like // in C# or — in SQL.  I’m not aware how to comment code with block comment (/**/) without using a plug-in for VS.

One more thing.  If you need to comment/uncomment a single line, you don’t need to select the whole line.  Just move the cursor to any position on the line you want to comment, and let you fingers press the magic combination.

If you like me (there’s nothing wrong to be different from me) and use ReSharper, than you would like to use Ctrl+Alt+/ with line comment and Ctrl+Shift+/ with block comment.

kick it on DotNetKicks.com

Posted in .Net, Coding, ReSharper, Tips And Tricks, Visual Studio | Tagged: , , , | 5 Comments »

How big is null in Nullable types?

Posted by Vadim on July 28, 2008

I use often Nullable types in my code.  However, when today I was debugging my code I was surprised to learn that the expression bellow equals to false:

   1: int? n1 = null;
   2: int? n2 = null;
   3: if (n1 <= n2)
   4:     Console.WriteLine("not going to happen");

I decided to dig deeper to see what the reason for this behavior.

I learned that when you have a Nullable type variable that is null (int? n1 = null) in relation comparison expression, the expression is always false.  By relation comparison I mean binary comparison with one of following operators: <, >, <= , =>.

Let me try to explain why this happens.   Let assume that we have two Nullable integers n1 and n2.  n1 is null and n2 has value of 5.  When you compare (n1 < n2), behind the scene the following comparison happens:

(
    (n1.GetValueOrDefault() < n2.GetValueOrDefault()) && 
    (n1.HasValue & n2.HasValue)
)

n1.GetValueOrDefault() will return 0.

n2.GetValueOrDefault() will return 5.

That means the first part of our expression will be true because 0 is less than 5.  However the second part of our expression will be translated into (false & true) which equals to false.  So the first expression is true and the second one is false that means that the whole expression is false too.

That explains why any relation comparison with null value will be false.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, Nullable Types | 1 Comment »

Explaining GetHashCode method.

Posted by Vadim on July 5, 2008

Every object you ever created or used in .NET has GetHashCode method along with Equals, GetType, and ToString methods.  This method is an instance method of an Object class from which any other class derives.

GetHashCodeIntelisense

GetHashCode() method returns an integer that identifies an object instance.  I also can repeat MSDN documentation but you can read it on your own.

You would want to override this method along with Equals() method in your class if the object of your class is going to be used as a key in Hashtable.

The best way to explain it is to show an example. In I was using class Point as an example.  I’m going to continue with this class.  So let assume that we have class like this:

   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   5:
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11: }

Next we want to use Point as a key in a Hashtable.  Remember that the key of the Hasthable must be unique.  In the code bellow we have two identical keys (line 2 & 4). We should expect ArgumentException.

   1: Hashtable hashtable = new Hashtable();
   2: hashtable.Add(new Point(2, 3), "Point 1");
   3: hashtable.Add(new Point(5, 3), "Point 2");
   4: hashtable.Add(new Point(2, 3), "Point 3");

However, no exception was thrown.  There are two reasons why exception is not thrown:

  1. Equals() method that is also an instance method of Object class will always indicate that Point in line 2 and line 4 are different. This expected because two objects have different references.
  2. GetHashCode() method returns different number for these objects.

Try to execute code bellow:

   1: static void Main(string[] args)
   2:  {
   3:    var point1 = new Point(2, 3);
   4:    var point2 = new Point(2, 3);
   5:    Console.WriteLine("point1 Hash: {0}"
   6:         , point1.GetHashCode());
   7:    Console.WriteLine("point2 Hash: {0}"
   8:         , point2.GetHashCode());
   9:    Console.WriteLine("point1 equal to point2: {0}"
  10:         , point1.Equals(point2));
  11:  }

You will get output similar to this one:

point1 Hash: 58225482
point2 Hash: 54267293
point1 equal to point2: False

You can see that we got different hash codes.

To solve this problem we override Equal() and GetHashCode() in our Point class.

First we override Equals() method:

   1: public override bool Equals(object obj)
   2: {
   3:   if (ReferenceEquals(null, obj)) return false;
   4:   if (ReferenceEquals(this, obj)) return true;
   5:   return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
   6: }

You can see that I use ReferenceEquals() method that is static method of Object class.  It checks if the specified objects are the same.

Next we override GetHashCode() method:

   1: public override int GetHashCode()
   2: {
   3:   unchecked
   4:   {
   5:     return (_x * 397) ^ _y;
   6:   }
   7: }

The whole Point would look like this:

   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   5:
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11:
  12:   public override bool Equals(object obj)
  13:   {
  14:     if (ReferenceEquals(null, obj)) return false;
  15:     if (ReferenceEquals(this, obj)) return true;
  16:     return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
  17:   }
  18:
  19:   public override int GetHashCode()
  20:   {
  21:     unchecked
  22:     {
  23:       return (_x * 397) ^ _y;
  24:     }
  25:   }
  26: }

Now if you try to execute the application the output should look exactly like this:

point1 Hash: 793
point2 Hash: 793
point1 equal to point2: True

Also if we try to add new Point(2, 3) twice, we get an ArgumentException as expected.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, GetHashTable, VS2005, VS2008 | 14 Comments »

Take control of DateTime’s ToString() method.

Posted by Vadim on June 19, 2008

DateTime_ToString Today I had to write to the database a string that satisfies  following format: DDMMYYYY-CountryCode.  For example if DateTime object equal to 06/19/2008 and country code is USA, the value written to the database must be “06192008-USA“. 

The best way I found to do that is to use ToString() method of DateTime object with custom date and time format.

someDate.ToString("MMddyyy-") + CountryCode;

NOTE: In the format above I used two ‘M’s and two ‘d’s.  If only one ‘M’ and one ‘d’ was used, no month or date would be padded with zero.

someDate.ToString("Mdyyy-") + CountryCode;

The output for the code above would be “6192008-USA” assuming that the date is 06/19/2008 and the country code is USA.

UPDATE: I had to change the lines of code above because it had a bug.  Thanks to Alexey Romanov for pointing it out.  I put one line of code for the world to see and it was buggy.

The previous code looked like this:

someDate.ToString(String.Format("MMddyyy-{0}"), CountryCode);

Let assume that CountryCode is MEX.  In this case it’s the same as:

someDate.ToString("MMddyyy-MEX");

Remember that “M” is a special character for DateTime object.  The output for this code would be “06192008-6EX“.  It definitely is a problem.

Posted in .Net, C#, Coding, DateTime | 4 Comments »

Mock DataTable

Posted by Vadim on June 16, 2008

Today I had to work with some legacy code.  It was originally written in Delphi and then converted line by line to C#.  Before changing anything in the code I decided to create unit tests and make sure that I have 100% coverage.

One of the thing I had to do in my unit test is to mock DataTable.  Here are the steps I made during mocking.

  1. Create needed columns in a DataTable.
  2. Create a new DataRow.
  3. Assign values to the row.
  4. Finally add the row to the DataTable.

Repeat steps 2- 4 for each row you want to add to your DataTable.

Here’s the example:

   1: [Test]
   2: public void HolidayTest()
   3: {
   4:   MockRepository mocks = new MockRepository();
   5:   ICompanyDAL dalMock = mocks.CreateMock<ICompanyDAL>();
   6:   // Create DataTable
   7:   DataTable fakeHolidays = new DataTable();
   8:   // 1. Add Columns
   9:   fakeHolidays.Columns.Add("Holiday", typeof (DateTime));
  10:   fakeHolidays.Columns.Add("Name", typeof(string));
  11:   // 2. Create new DataRow
  12:   DataRow dayRow = fakeHolidays.NewRow();
  13:   // 3. Assign values to the row
  14:   dayRow["Holiday"] = DateTime.Parse("07/04/2008");
  15:   dayRow["Name"] = "Independence Day";
  16:   // 4. Add the row to the DataTable
  17:   fakeHolidays.Rows.Add(dayRow);
  18:   _pgDate.CompanyDal = dalMock;
  19:   using (mocks.Record())
  20:   {
  21:     Expect.Call(dalMock.GetHolidays()).Return(fakeHolidays);
  22:   }
  23:   using (mocks.Playback())
  24:   {
  25:     DataTable holidays = _pgDate.Holidays;
  26:     Assert.GreaterThan(holidays.Rows.Count, 0);
  27:   }
  28: }

I used Rhino.Mocks as my mocking framework in the example above.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, MbUnit, Rhino.Mocks, TDD | Tagged: , , | 2 Comments »

GetAttribute Generics way.

Posted by Vadim on March 26, 2008

As developers we often need to work with Xml.  In my case I found myself writing code like this one:
   1: public void Main()
   2: {
   3:   string name;
   4:   bool required;
   5:   XmlDocument _xmlDoc = new XmlDocument();
   6:   _xmlDoc.LoadXml("<column name=\"colName\" required=\"true\"/>");
   7:   if (_xmlDoc.DocumentElement.HasAttribute("name"))
   8:     name = _xmlDoc.DocumentElement.GetAttribute("name");
   9:   if (_xmlDoc.DocumentElement.HasAttribute("required"))
  10:     required = Convert.ToBoolean(_xmlDoc.DocumentElement.GetAttribute("required"));
  11: }
I hated the fact that I have to for every attribute use two lines in my Main function.  Below you can see refactored code.
 
Note: You will need to pass XmlNamespaceManager if you’re using namespaces.
   1: public void Main()
   2: {
   3:   XmlDocument _xmlDoc = new XmlDocument();
   4:   _xmlDoc.LoadXml("<column name=\"colName\" required=\"true\"/>");
   5:   string name = GetAttribute<string>(_xmlDoc.DocumentElement, "name");
   6:   bool required = GetAttribute<bool>(_xmlDoc.DocumentElement, "required");
   7: }
   1: private T GetAttribute<T>(XmlElement columnElement, string attributeName)
   2:   where T : IConvertible
   3: {
   4:   if (columnElement.HasAttribute(attributeName))
   5:     return (T) Convert.ChangeType(columnElement.GetAttribute(attributeName), typeof (T));
   6:   return default(T);
   7: }
I hope you’ll find it useful.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, Generics, XML | Tagged: | Leave a Comment »

Testing internals members with InternalsVisibleTo attribute.

Posted by Vadim on December 9, 2007

I posted previously about testing non-public members with MbUnit.  I recently found out about InternalsVisibleTo attribute by reading Roy Osherove‘s book The Art of Unit Testing.

To use this attribute, your test assembly must be strong-named.  Then you put InternalsVisibleTo attribute with public key of test assembly into AssemblyInfo.cs file of assembly under test.

 1: [assembly: InternalsVisibleTo("MyAssembly.Tests, PublicKey=XXX")]

I created an Assembly Helper tool that creates the syntax for you.  The tool is working (or should work) with following languages:

  • C#AssemblyHelper
  • Visual Basic
  • Delphi
  • MS C++
  • Chrome

You can get the tool from here.

Steps to use InternalsVisibleTo attribute with the tool.

Let assume that you have Assm_A and Assm_ATests.

  1. Sign Assm_A and Assm_ATests with a Strong Name. You can read about that here.
  2. Compile your assemblies.
  3. Launch Assembly Helper tool .
  4. Select desired language and press on ‘Get Assemblies’ button and navigate to Assm_ATests.dll.
  5. Copy the text into AssemblyInfo file of Assm_A assembly.

Now your tests can access internals members of the assembly under test.

Note: With Assembly Helper tool you can select multiple assemblies at once.

kick it on DotNetKicks.com

Posted in .Net, Coding, TDD | 12 Comments »

Explaining MbUnit GUI tree.

Posted by Vadim on September 29, 2007

When the first time I looked at MbUnit GUI tool, I was overwhelmed with complex tree structure. The root has five branches: Authors, MbUnitGuiColapsedTreeCategories, Importances, Namespaces, and TestsOns. I was able relate to Namespaces and Categories; I’ve seen something similar in NUnit. But what for are other three branches. Well, MbUnit GUI shows the branches in alphabetical order. There for I’ll try explain the branches in the same order. I’ll start with Authors and end with TestsOns.

Authors

It’s pretty clear that if you want to claim ownership of the test fixture you need to put it inside the Authors. It’s not hard to do. What you need to do is to use Author attribute on your fixture. Author attribute has three overloads:

   1: [TestFixture]

   2: [Author("Vadim")]
   3: public class MyTest {}

 

   1: [Author("Vadim", "vadim@domain.com")]

   2: [Author("Vadim", "vadim@domain.com", http://vkreynin.wordpress.com/)]

MbUnitGuiAuthors Before we added Author(“Vadim”), we had “Anonymous” leaf inside the Authors branch. “Anonymous” always will have test fixtures that don’t have an Author attribute. I believe it’s a good practice to use this attribute on big projects. However, instead of a person name I would use a team name. The reason I think it should be a team name because a developer can switch a team, find a better job or win a lottery and leave the team. A team is responsible for the part of the project they are working on and there for they also should be responsible for the tests. Also a team probably would like to run all the tests related to the team before checking in the code.

Categories

Categories branch is obviously for categorized test fixtures. You can assign multiple categories to a test fixture. Here how you do it using FixtureCategory attribute.

   1: [TestFixture]
   2: [FixtureCategory("Demo")]
   3: [FixtureCategory("WebPayroll")]

MbUnitGuiCategories

All the test fixtures that don’t have a category assigned can be found in Categories/Misc branch.

Importances

This branch specifies the importance of the test fixture. MbUnit Framework defines five different types of test fixture importance.

  • Critical
  • Default
  • NoOneReallyCaresAbout
  • Serious
  • Severe

Importance can be defined by Importance attribute.

   1: [TestFixture]
   2: [Importance(TestImportance.Severe)]

The test fixtures that don’t have importance can be found in Default importance. To be honest I didn’t find it very useful yet. Let me know how you use this attribute.

Namespaces

I don’t think that I need to explain this. Anybody who develops using .NET know what Namespace is.

TestsOns

For some reason this one took me the longest to figure out. Using TestsOn attribute you can specify what class the test fixture is testing.

   1: [TestFixture]
   2: [TestsOn(typeof(Employee))]

MbUnitGuiTestsOns

In the example above we are saying that the test fixture is testing Employee class. All the test fixtures that don’t use TestsOn attribute can be found in Unknown branch.

kick it on DotNetKicks.com

Posted in .Net, C#, Coding, MbUnit, TDD | 9 Comments »

MbUnit: Testing Internal classes

Posted by Vadim on September 5, 2007

Jonathan ‘Peli’ de Halleux wrote an article ‘Pex It: Testing Internal classes‘.   I just want to let the world know that you also can test non-public classes with MbUnit.  You need  version 2.4.1.220 or higher to use this feature.

In example bellow we test IsWhite(Char) method of System.Number class inside mscorlib assembly.  Using Reflector you can see that Number is an internal class and IsWhite is a private method of this class.  We can test this method event if we don’t have the source code.

private static readonly string MSCorLibAssembly = 
    Environment.GetEnvironmentVariable("SystemRoot")
    + @"\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll";
 
[Test]
public void InternalClassTest()
{
    string className = "System.Number";
    object obj = 
        Reflector.CreateInstance(MSCorLibAssembly, className);
    Assert.IsNotNull(obj);
    Assert.AreEqual(true,
        Reflector.InvokeMethod(
            AccessModifier.Default, obj, "IsWhite", ' '));
    Assert.AreEqual(false,
        Reflector.InvokeMethod(
            AccessModifier.Default, obj, "IsWhite", 'V'));
}

The Number class has only default constructor.  It means we don’t need to send parameters when creating an instance.

Let’s look at another example.  This time we’re going to write test for the Key and Value properties of System.Collections.KeyValuePairs class.  This class is also internal.  If you don’t believe me, use Reflector.  KeyValuePairs class has only one constructor that takes two Object parameters.

[Test]
public void InternalClassNonDefaultConstructor()
{
    string className = "System.Collections.KeyValuePairs";
    object obj = 
        Reflector.CreateInstance(MSCorLibAssembly, className, 1, 'A');
    Assert.IsNotNull(obj);
    Assert.AreEqual(1, Reflector.GetProperty(obj, "Key"));
    Assert.AreEqual('A', Reflector.GetProperty(obj, "Value"));
}

 Happy Testing :)

Posted in .Net, C#, Coding, MbUnit, TDD | 3 Comments »

Get Array type.

Posted by Vadim on September 5, 2007

Let assume that you have an int array.

int[] intArr = new int[] { 1, 2 };

If you try to get the type of the array, you’ll get int[] type.

Assert.AreEqual(typeof(int[]), intArr.GetType());

So far so good.  But what if code needs to perform different logic for array of ValueType and Reference Type elements.  We all know that int is a ValueType. However, array of int is not. So the if statement below will output ‘Reference Type’.

if (intArr.GetType().IsValueType)
    Console.Write("ValueType");
else
    Console.Write("Reference Type");

Microsoft provided us with GetElementType method that returns the Type of the object encompassed by the array.

if (intArr.GetType().GetElementType().IsValueType)
    Console.Write("ValueType");
else
    Console.Write("Reference Type");

The code above outputs ‘ValueType’ as expected.

Posted in .Net, C#, Coding, Visual Studio | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.