Archive for the '.NET' Category

LINQ bites back

Today I found some odd behavior when working with LINQ. It is hard to describe, so here is the code.

public void Foo(IEnumerable<string> strings)
{
	IEnumberable<string> stringsInDb = strings.Where(s => this.QueryTheDbAndTakeALongTime(s));
 
	foreach(string str in stringsInDb)
	{
		//Where clause in LINQ is actually executed 
	}
 
	foreach(string str in stringsInDb)
	{
		//Where clause in LINQ is actually executed  AGAIN
	}
}

Luckily, some unit tests detected this behavior. It actually isn’t surprising when you think about it though. The proper thing to do for this case is actually call ToList() after the Where().

IEnumberable<string> stringsInDb = strings.Where(s => this.QueryTheDbAndTakeALongTime(s)).ToList();

Don’t let this behavior bite you.

LINQ’d up

I just used LINQ for the first time ever in code. Pretty exciting. For me, it doesn’t get much better than transforming some mundane 6 liner into an elegant one liner.

This…

int count = 0;
foreach (string email in this.emails)
{
    if (email.EndsWith("@mydomain.com")) count++;
}
return count;

becomes this…

return this.emails.Count(email => email.EndsWith("@mydomain.com"));

In some weird kind of way, I feel like an emo Ruby developer. Maybe I’ll start wearing some tighter clothes.

NUnit and RowTest

I have been researching different unit testing tools for .NET lately. Obviously, NUnit was the first I came across, but MbUnit had the RowTest attribute, which allows parameters to be added to tests. This saves a lot of code and is really a must have feature. Luckily, I found an NUnit addin for RowTest here. The latest version here is linked to NUnit 2.4.6, so I rebuilt it from source to use NUnit 2.4.7.

To install for TestDriven.NET, just create an addins folder in the %install root%\TestDriven.NET 2.0\NUnit\2.4\ and copy NUnitExtension.RowTest.AddIn.dll to the newly created folder. Then in your test project, just reference NUnitExtensino.RowTest and you are set to go.

Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace TestExample
{
     [TestFixture]
     public class Tests
     {
          [RowTest]
          [Row(-4,4)]
          [Row(-5,5)]
          [Row(-6,6)]
          public void TestAddEqualsZero(int x, int y)
          {
               Assert.IsTrue((x + y) == 0);
          }
}

C# Destructors and IDisposable

This week I found myself somewhat confused on when to use destructor. Originally I assumed that anytime you implement IDisposable you should have a destructor that calls Dispose().

This is not the case though. The only time you really need a destructor is when a class directly contains unmanaged resources, like file handles.

A good example of when not to use a destructor is a wrapper class. For instance, if you have a database connection class wrapped with some sort of adapter class, the adapter class doesn’t need a destructor. It still needs to implement IDisposable to enable early disposal of resources, but the destructor of the underlying database connection class will handle any potential leak cases if Dispose() isn’t called.

Here is a quote from a very good article on C# traps:

The destructor should only release unmanaged resources that your object holds on to, and it should not reference other objects. If you have only managed references you do not need to (and should not) implement a destructor. You want this only for handling unmanaged resources. Because there is some cost to having a destructor, you ought to implement this only on methods that consume valuable, unmanaged resources.

The really powerful statement is “it should not reference other objects” which basically backs up my previous statement on wrapper classes.

Here is another good article on destructors and IDisposable.

How to actually use trigonometry in web applications

Disclaimer: my teammate Dellanoce actually coded this, but is too cool to blog, so I am blogging for him.

Mailtrust has many different customers, some of which like to have their own branded control panel or webmail interface. We allow them to customize many different facets of the user interface, including colors. This has some unintended consequences though. Sometimes, a user might select a white font color on top of a white background. This in turns causes support to get involved in fixing the problem, which wastes time on such a trivial problem.

But there is a better way. Use trigonometry, or more specifically the Pythagorean theorem! I had no idea how this worked, but Dellanoce coded up a few lines of C# to compare two colors. It returns a distance value which can be compared to a threshold value you can set.

1
2
3
4
5
6
7
8
9
10
11
        private static double ColorDifference(string htmlColor1, string htmlColor2)
        {
            Color color1 = ColorTranslator.FromHtml(htmlColor1);
            Color color2 = ColorTranslator.FromHtml(htmlColor2);
 
            double rDiff = Convert.ToDouble(color1.R) - Convert.ToDouble(color2.R);
            double gDiff = Convert.ToDouble(color1.G) - Convert.ToDouble(color2.G);
            double bDiff = Convert.ToDouble(color1.B) - Convert.ToDouble(color2.B);
 
            return Math.Sqrt((rDiff * rDiff) + (gDiff * gDiff) + (bDiff * bDiff));
        }

I was quite impressed with the simplicity and elegance this solution provided. I should probably go give my, or his, trig teacher a hug.

If you want to learn more about how powerful Pythagorean theorem is to compare distance values of really any type of object, check this article out.