Brendan Enrick

Daily Software Development

Validating Entity objects

While working with an entity object I wanted to validate, I took some time to do some Googling. I was planning on creating an IValidator<T> interface so I could keep the validation separate from my classes, and I was going to implement this interface for every entity that needed it. Since validation is pretty common I figured I would take a look around first to see if there were some good ways of performing validation which differed slightly from how I had done things previously or offered any insight on a good solution similar to what I mention above. I found a link to a blog post that had exactly what I was looking for. It turns out that Jimmy Bogard already had a great post on this topic. His post, Entity validation with visitors and extension methods, demonstrates a very cool IValidator implementation.

He combines a couple of cool interfaces to get this working. He uses an IValidator<T> interface like I mentioned I wanted to use. His implementation of this is pretty nice. (I made a slight adjustment to it here, because his example code had a bug.)

public class OrderPersistenceValidator : IValidator<Order>
{
    public bool IsValid(Order entity)
    {
        return BrokenRules(entity).Count() == 0;
    }

    public IEnumerable<string> BrokenRules(Order entity)
    {
        if (entity.Id < 0)
            yield return "Id cannot be less than 0.";

        if (string.IsNullOrEmpty(entity.Customer))
            yield return "Must include a customer.";

        yield break;
    }
}

 

I look at this an see a fairly nice and elegant solution to the validation problem. He also has an IValidatable<T> interface he uses, which is nice because it sets up a method to pass in the IValidator to use.

public class Order : IValidatable<Order>
{
    public int Id { get; set; }
    public string Customer { get; set; }

    public bool Validate(IValidator<Order> validator, out IEnumerable<string> brokenRules)
    {
        brokenRules = validator.BrokenRules(this);
        return validator.IsValid(this);
    }
}

So I think this code is pretty cool, but the only thing that was still irking me about this code is that now I would have to pass the IValidator object in to the Validate method of the entity. I really don't want to have to pass those in, so I start thinking about how to get around that problem. Well then I just read a little further in his article. He has a very nice solution to this problem using an extension method on a Validator class. (I adjusted this snippet slightly also, because it too had a bug.)

public static class Validator
{
    private static Dictionary<Type, object> _validators = new Dictionary<Type, object>();

    public static void RegisterValidatorFor<T>(T entity, IValidator<T> validator)
        where T : IValidatable<T>
    {
        _validators.Add(entity.GetType(), validator);
    }

    public static IValidator<T> GetValidatorFor<T>(T entity)
        where T : IValidatable<T>
    {
        return _validators[entity.GetType()] as IValidator<T>;
    }

    public static bool Validate<T>(this T entity, out IEnumerable<string> brokenRules)
        where T : IValidatable<T>
    {
        IValidator<T> validator = Validator.GetValidatorFor(entity);

        return entity.Validate(validator, out brokenRules);
    }
}

 

This Validator class reminds me a lot of IOC stuff. You register a validator with the entity type it validates. This lets you set up which validators each class needs so you don't have to specify on use. It also provides a nice extension method which allows you to call the validate method without having to pass in the correct validator. It will use the one it has registered for that entity type.

Great solution in my opinion. Now I am going to add his blog to the blogs I read. I hope some of you do also.

My Article is Popular

As last year was coming to an end I wrote an article on ASP Alliance. Well now to my surprise, my article explaining very simply what the MVC pattern is and why it is useful, has become relatively popular. I wrote the article, because I talked to a bunch of people and they didn't really seem to understand the MVC pattern, what it did for them, or why they should use it. Setting out my goal was to write an article to help people understand exactly that. I am sure there are plenty of ways in which it could have been improved, but I think it turned out pretty well.

How do I know the article is popular? It is currently listed as one of the popular articles on the ASP Alliance home page. As of writing this blog post, that article has had 3964 views in the past 10 days. Not too shabby I'd say since the article is not new. I have noticed that posts usually get more traffic right after they're written. I believe this is because search engines find them and list them higher for a while because they are newer.

So I took a quick screen shot of the list of popular articles, so my readers could see the fame I've reached....

PopularArticleList

Just to show my enthusiasm about this feat, I've taken the same screen shots and added some Batman-style onomatopoeias. This will let everyone know that my blog posts are knocking out other ones to get to the top... or save Gotham... or something like that. Enjoy!

PopularArticleListBatmanStyle

Have a great day. I hope everyone enjoyed reminiscing about their childhood batman-watching days.

Tune in for the exciting conclusion on a different blog time on the same blog site. (yes, I mean here later)

Write a Test Before Fixing a Bug

As I've said in previous posts, it is important to write tests for your code. A lot of the time I am talking about when refactoring code or when writing new code. Now I agree that bug fixing could be considered refactoring, but people seem to treat it differently. When fixing bugs they want to go in and quickly make the bug go away. That is a dangerous way to solve things, because it doesn't prevent the bug from returning.

If a bug exists in your system then there are test cases missing from the system. When you fix a bug, even if you do write a test case to handle the bug how do you know you've tested the right thing? If your test is not right it will not prevent the bug from returning. I know of only one way to be fairly confident that a bug is tested well. The test needs to be written before the fix. If it isn't written first you will not know. If you follow the TDD practice of Red, Green, Refactor, the Red lets you know that you've found the bug. Then when you make it green you can have confidence that you've fixed the bug.

RedGreenRefactor

If you had not tested first you don't even know that your test is accurate. How do you know you actually found what is causing the bug? You can't really be sure with any confidence, because all you saw were green tests. Your test couldn't fail. Either the test didn't actually test the bug or because you fixed it. You hope the latter, but it could be the former.

GreenGreenRefactor

This will not work. For other things I can agree with you that you can write code and then test it, but not for bugs. With bugs the test needs to be written first, so there is some confidence that the bug is being tested. Since code already exists the test needs to be in place first. This same practice should be adhered to when doing refactorings of working code as well. The point in that case is also to prevent software regressions caused by the refactoring. Tests help you hold existing functionality, and in the case of bug fixing they help to ensure that the bug has truly been fixed and tested to prevent a return.

Software bugs are like bad musicians. If you don't actively prevent them, they will make a comeback.

Example

As an example of this. We can assume that we have two classes. One of them is called Student and the other is called Course. To represent this example we are going to have some badly written code which is going to cause us to have a few nasty bugs (Badly written code makes for easier examples). From our knowledge  of the domain, we know that students take a few courses at a time, so there is a collection of courses associated with a student.

Say our student has a property called Courses and that property holds the collection.

public class Student
{
    public int ID { get; set; }
    public List<Course> Courses { get; set; }
}

Now we say that somewhere we are caching the Student objects based on their IDs. We want to make sure that if the student object is changed that we expire the cache, so we will cache it with a SqlCacheDependency on the database table for the Student object.

Assume we have a "View my courses" page for the student to get information about the courses. For ease, it will obviously grab the student object out of cache and use its collection of courses to display the information if the information is already there.

What bug have we created here?

Well we've now made it so that if any of the courses change this change will not be reflected on the courses page of any student currently in the cache. There are literally probably a dozen ways of fixing this bug. Plenty of ways we could have prevented it, but then we wouldn't have this nice example now would we?

All I am saying is that some unit tests and integration tests be written for these before we fix the problem. This lets us be sure that we've fixed the problem correctly.

The first test I would write is one that loads a student object (making sure that is gets cached) and then separately loads one of the courses the student is in and alters that course. I would then make sure that the change to the course succeeded and then I would get the student again, (it would come out of cache this time) and I would verify that it had the change I made to the course. I would expect that the first time I run it that the test will fail. If it doesn't fail, or fails for a reason other than what I expected, I need to fix it so it fails the way I expect.

Once it is failing correctly I can adjust the code to make it work correctly. I would call this an issue violating the single responsibility principle, because the Student object in my opinion shouldn't be holding a local copy of the Courses. If it doesn't have that then it will not be able to cache it. I think that property should just be a getter calling through to some Course-related class which can cache it if it wants to. Even though these are obviously domain objects, we should try to keep them separated a little bit better, because keeping them too close can cause some annoying bugs.

As always, have a great day, and keep testing your code.

Handling msbuild File Paths in Visual Studio Project Files

Yesterday, a co-worker of mine and I were working on a task which required that we work in the xml of a Visual Studio project file. We were setting up a target with an exec statement, and ran into a little annoyance. The file we were trying to execute was in a folder with a space in the name.

If we were typing this into a command prompt window it would be easy. We would simply wrap the statement in quotes. Working in the project file our brains sort of stopped working. We tried to find a way to escape the spaces in the file path. Instead of doing this in the end we used the xml encoding for a quote. We used &quot; to wrap the path in quotes. Yipee everything worked!

Today we were doing some similar work, and ran into another problem in these files. We want our msbuild stuff to work with both 32-bit and 64-bit machines. The code we are calling is always 32-bit, so we need to use a different file path depending on which type of machine we are using. We found this post on stack overflow from a person who found a way to specify the 32bit directory for program files in msbuild. The post on there is asking for a better solution, so I will also ask people to provide a better solution.

This is how Wimmel solved the problem.

<PropertyGroup>
  <ProgramFiles32 
    Condition="Exists('$(PROGRAMFILES) (x86)')">$(PROGRAMFILES) (x86)</ProgramFiles32>
  <ProgramFiles32 
    Condition="$(ProgramFiles32) == ''">$(PROGRAMFILES)</ProgramFiles32>
</PropertyGroup>

<Exec WorkingDirectory="src\app1" 
  Command='"$(ProgramFiles32)\doxygen\bin\doxygen" Doxyfile' />

All he did is create a variable called ProgramFiles32 which would contain one of two file paths depending on whether the (x86) program files exists. He then uses that variable in his file path. It works reasonably well, and since I am not concerned with running this in any language other than English I am not too concerned with any problems which might arise from this. If this bites me down the road please point me back to this blog post.

Change Local SQL Server Used By Visual Studio

A while back I ran into a problem when setting up SQL Server on a computer and using it along with a database project in Visual Studio. It isn’t really a big deal, but I needed to change which locally installed instance of SQL Server I was using by default with Visual Studio. Since I blogged about this previously it is a very nice reference for where to find that setting should the need to change it arise again.

Today I just sat down at a computer which had Visual Studio pointing to a SQL Express instance. Yesterday I installed SQL Server on the computer, so I went to change to the new SQL Server instance. What was my first step? I Googled for my blog post I’d previously written, because I knew it had nice screen shots to show me exactly what I was looking for.

I simply searched for, “change database Brendan Enrick”. The top hit on Google was my previous post explaining how to change the SQL Server Instance for a Visual Studio Database Project. As I mention in that post, I expected the setting to be DB Project specific not VS specific. Now I know better, and I just use the blog post for a quick solution.

Step one is to go to the Tools menu in Visual Studio and choose Options…

Change SQL Server Instance Menu Selection

Now that the Options windows is open in the left side navigation tree select Database Tools and then Design-time Validation Database. Once that screen is visible there is a text box to change the SQL Server Instance Name. Set that to the name of your desired SQL Server Instance. In my case the default one, so I erased the existing value.

Change SQL ServerInstance Options Change

 

 

 

This is one of the big reasons why I am a strong believer in blogging. It is a quick easy way to get this information out for others to use. Posts like this often get a few comments of thanks from people they helped. If helping others in the development community is not enough of a reason, you also always have a record to help you if you run into the same problem again.

Earned My First MVP Award

A couple of days ago I received an email informing me that I received the 2009 Microsoft® MVP Award.

Thanks Microsoft. I am very honored.

Thank you everyone who reads the articles and blog posts I write as well as the other things I am involved in.

I hope everyone has a happy new year. Everyone at my office should not worry, because I am not really going to uphold the random resolution I mentioned in my previous post.

The year 2009 is turning out well. I hope everyone has enjoyed their first couple of days of the new year.

My Randomly Selected New Year's Resolution

I am quite certain that plenty of resolution randomizers exist, so I will just jump straight in to things. Here is a link to a resolution randomizer created using Silverlight.

Now everyone will feel sorry for my coworkers who have to listen to this, because the random resolution machine said I have to.

ResolutionRandomizer

Have fun celebrating the coming of the new year everyone.

Comparing Nullable DateTimes

A couple of days ago I was working on some code when I noticed a comparisons of two DateTime? variables. So I wondered what would happen if either or both of those variables had gotten null values. Since I had never tried it before I figured I would just take a couple of minutes and test some things. Since I already had visual studio open I just created a unit test and wrote some code in there to test the behavior. I've not done it in a console application since it is easier for most people to use the console app version of the code.

So the first thing to do is to create a few Nullable DateTime variables. I then wrote a small amount of completely unnecessary code. I did this to assure the readers of this post that the assumption that the Nullable variables' HasValue properties is correct. I then proceed with a bunch of test cases some of which are unnecessary, but I believe they help demonstrate the point.

My task for readers of this post is to try to figure out the results of this code before reading the answer below.

int? lesserDateTime = 1;
int? greaterDateTime = 2;
int? nullDateTime1 = null;
int? nullDateTime2 = null;

if (!lesserDateTime.HasValue || !greaterDateTime.HasValue 
    || nullDateTime1.HasValue || nullDateTime2.HasValue)
{
    throw new Exception("Something is very wrong here!");
}

Console.WriteLine("\n lesserDateTime > greaterDateTime = " 
    + (lesserDateTime > greaterDateTime));
Console.WriteLine("\n greaterDateTime > lesserDateTime = " 
    + (greaterDateTime > lesserDateTime));
Console.WriteLine("\n lesserDateTime == lesserDateTime = " 
    + (lesserDateTime == lesserDateTime));
Console.WriteLine("\n lesserDateTime > nullDateTime1 = " 
    + (lesserDateTime > nullDateTime1));
Console.WriteLine("\n greaterDateTime > nullDateTime1 = " 
    + (greaterDateTime > nullDateTime1));
Console.WriteLine("\n lesserDateTime == nullDateTime1 = " 
    + (lesserDateTime == nullDateTime1));
Console.WriteLine("\n greaterDateTime == nullDateTime1 = " 
    + (greaterDateTime == nullDateTime1));
Console.WriteLine("\n nullDateTime1 > greaterDateTime = " 
    + (nullDateTime1 > greaterDateTime));
Console.WriteLine("\n nullDateTime1 > lesserDateTime = " 
    + (nullDateTime1 > lesserDateTime));
Console.WriteLine("\n nullDateTime1 == greaterDateTime = " 
    + (nullDateTime1 == greaterDateTime));
Console.WriteLine("\n nullDateTime1 == lesserDateTime = " 
    + (nullDateTime1 == lesserDateTime));
Console.WriteLine("\n nullDateTime1 > nullDateTime2 = " 
    + (nullDateTime1 > nullDateTime2));
Console.WriteLine("\n nullDateTime2 > nullDateTime1 = " 
    + (nullDateTime2 > nullDateTime1));
Console.WriteLine("\n nullDateTime1 == nullDateTime2 = " 
    + (nullDateTime1 == nullDateTime2));
Console.WriteLine("\n nullDateTime2 == nullDateTime1 = " 
    + (nullDateTime2 == nullDateTime1));

Console.WriteLine("\n");

Answer below.

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

NullableCompareConsoleResults

And just to show that this has to do with Nullable really and not the DateTime part, I did the test with int? also.

NullableCompareIntResults

This is why you need to be a little bit careful with Nullable types. Make sure that you are always checking the HasValue property when working with Nullable types so you can handle the situation in the desired fashion. If you didn't know or check the type of that variable the results could be disastrous.

Don't make too many assumptions about behavior. I asked a few people what they might expect to get when comparing with the null value, and they guessed that the null would be treated as the default value for the data type. That guess makes a lot of sense, but it is not the case. Notice that every time a null was involved the result was false. The only time this is not the case is when comparing the equality of two null values.

As a final note I will say that if you want to do comparisons of Nullable values I recommend doing the following. Since Nullable's are a little bit special, we need to compare them this way.

Console.WriteLine("\n Nullable.Compare(lesserDateTime, nullDateTime1) = "
    + Nullable.Compare(lesserDateTime, nullDateTime1));
Console.WriteLine("\n Nullable.Compare(nullDateTime1, lesserDateTime) = "
    + Nullable.Compare(nullDateTime1, lesserDateTime));

If we don't do the comparison in this manner we are likely to get the above unexpected results. If you want to see the specifics of the Nullable.Compare method, read the MSDN Nullable.Compare documentation.

Old Blog Favorites

I am somewhat partial to a few of the posts from my previous blog. For some of these posts, I just like the post, some the content about which the post was written, and some were just popular posts.

Installing SQL Server Management Studio with SQL Server: My most popular post is one written about a painful experience installing SQL Server's client tools. Sadly the popular post is out of date. My first post about the topic I found a solution that worked and managed to install the software. I late found out that there was a better way and I updated the post. The problem is that Google continued to send traffic to the old one. For my blog it was a pretty popular post. it has had over 25,000 views.

The original version - Installing SQL Server Management Studio with SQL Server

The current version - SQL Server Client Tools Installation

Visible Whitespace in Visual Studio: Another post written about a traumatic experience was when I accidentally used a keyboard shortcut and enabled visible white space. It caused a blue dot to show for every space character in visual studio. Wow was it hard to read my code with that on. Well I Googled for it, and at the time I didn't receive any results. There are some now my post is one of them. I also didn't notice the option to turn it off. I used an algorithm I like to call brute force to figure out the keyboard shortcut I typed. It was Ctrl + E + S. Comments let me know of a bunch of other ways to solve the problem for different configurations and versions of Visual Studio.

Visible Whitespace in Visual Studio

Return Within a C# Using Statement: IDisposable objects are nice to work with. I prefer not dealing with external resources, which is generally what you're doing with disposable objects, but having this interface makes it a little bit nicer. I wrote a post telling people it was safe to return from within the using statement, because the using statement will make sure that the object is disposed. In the lifetime of the post only one person actually challenged me on it and asked me to provide code showing that what I said is true. I of course responded to that comment and then posted a response on this blog. My response includes sample code showing that using statements make sure that the object is disposed.

If you like the second post make sure you thank Lambros Kaliakatsos for commenting on the first one.

The original post - Return Within a C# using Statement

The follow up including sample code - Returning From Inside a Using Statement

Performance with DropDownLists and ViewState: One thing that it seems a lot of ASP.NET developers still don't understand very well is ViewState. Page lifecycle stuff seems to really be fueling the MVC craze these days. I wrote a post talking about how ViewState can hurt the performance of your applications if you let it get out of hand. The example I used is the drop down list, but it can certainly get a bit crazy from grids, repeaters, etc. I wrote an article basically saying that you should try to avoid ViewState if you're going to have too much of it. I later followed up with a post about how to use a DropDownList without ViewState. Some people are concerned that you will not be able to use the SelectedValue property, but you can if you wire it up correctly. It is all about understanding that painful Page Lifecycle.

Performance with DropDownLists and ViewState

Using a DropDownList without ViewState

There are plenty of other posts I like in there, but I think I've bored my readers enough for one day. I've got a couple of posts lined up which should be a little bit more interesting than this one, so keep reading. As always, have a great day.

One Reason to Test Before Creating a Method

Most people who know about Test Driven Development have heard the phrase, "Red, Green, Refactor". When it comes to actual implementation of this technique there seems to be a bit of a disagreement. By following the rules of RGR we all agree that we start by writing a failing test (Red), we write the code to make the test pass (Green), and then we make the code better and remove duplication (Refactor). The point of contention I hear about most often is in the Red stage. Some people say to write the failing test before writing any code. Some people say that you can make a skeleton of the code and write the test for that.

In practice I tend to agree with the people that make the skeleton code first. I really just don't like having the compiler error be how my test fails. What I do instead is create the code I am going to test and have it throw a NotImplementedException. This lets me make sure the test is failing so I am sure to flesh out the code.

Now I can certainly see reasons to do both. That is just what I prefer. One interesting problem which can arise from doing my method is the following. Say that I am going to create a new method on a class, so I create the method and write the failing test. Perhaps this is a non-tested project I am working on, so only the new stuff is tested. I write my code and everything passes now. But I've created a new bug. How?

I am kind of cheating here because there is a compiler warning. Since not everyone treats compiler warnings as errors it is certainly possible to have missed this problem. Here is some example code including an extra base class I didn't mention yet.

class Program
{
    static void Main(string[] args)
    {
        Foo myFoo = new Foo();

        myFoo.Bar();
    }
}

internal class BaseFoo
{
    public void Bar()
    {
        Console.WriteLine("Base Bar!!");
    }
}

internal class Foo : BaseFoo
{
    public void Bar()
    {
        Console.WriteLine("Bar!!");
    }
}

So now if I create a method called Bar without realizing there was already one on the parent class I will be hiding the parent one and breaking the existing logic. Since the old code isn't tested I will not know about it. If I had written a test before the code, I would have noticed something odd when the compiler didn't throw an error.

I think it is an interesting debate. Not very important, but interesting. Perhaps people have some more reasons why it should be one way or the other.