WPF Validation with Enterprise Library 5

Every application needs validation. However, in WPF it still costs too much effort to implement it.
For instance, an ErrorProvider like in Winforms is not supported.

There are several conditions my validation should satisfy:
* I want to be able to specify validation in the data object. I consider this to be business logic and in this way, all errors are catched.
* It should be easy to check whether or not the object is valid; this to support enabling/disabling commands.
* I want a list of validation errors.

I’ve chosen to use the Validation Application Block of the Enterprise Library 5. It has many advantages:
* It has a lot of built-in validators
* You can use attributes
* You can specify your own custom validators (and use these in attributes)
* You can store validation rules in configuration files (using a designer)

When you only need validation on single properties, the data annotations are very clean.
For more complex validation rules, you can use the self-validation feature.

To implement this, you need to:
* add the HasSelfValidation attribute to the class
* add a void method that accepts a single ValidationResults input param, and decorate it with a SelfValidation attribute

The end result of my business entity:

[HasSelfValidation]
public class Person
{
    [StringLengthValidator(7, MessageTemplate="FirstName is too long")]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [SelfValidation]
    public void Check(VAB.ValidationResults results)
    {
        if (FirstName != "Jowen" || LastName != "Mei")
            results.AddResult(new VAB.ValidationResult("Name is not Jowen Mei", this, "", "", null));
    }
}

Check out my example to see it in action!
I’ve made a simple ValidationSummary control which displays the error messages.

Note: due to this bug I can’t modify the assembly references as usual. So you have to have Enterprise Library installed!

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

ConnectionString in Linq-to-Sql

I noticed that the dbml file stores the connection string in a Settings file, stored in the same project.
I use multiple projects to separate the entities from the ui, so this is unwanted behavior. I want it to read the connection string from the app.config.

This can be easily achieved:

  • Go to the Connection properties of your dataContext
  • Set the Connection string to None
  • Set Application Setting to False

This will prevent the generator to create a default constructor. This makes it possible to add your own, which will read the connection string from the config file.

public YourDataContext()
   : base(ConfigurationManager.ConnectionStrings["connString"].ConnectionString, mappingSource)
{
}

Thanks go to David Klein

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

VS2010 Productivity Power Tools

When you’re working with Visual Studio 2010, these tools are a must have!

The name says it all, but I must emphasize there really is a lot of added value. I already work with CodeRush and Refactor Pro, so usually I’m not interested in all those new pluggins/tools.

This free tool from Microsoft has some cool new features, of which my favorites are:
- Solution Navigator (nice!)
- decent tab management
- CTRL + Click to go to definition

Check them out!

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Get the windows uptime

A true note-to-self:

How to get the windows uptime

in short: execute the command net stats srv

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Looping (and modifying) a collection

Ok, back to basics with this one.

I have a collection of strings:

List<string> someStrings = new List<string>() { "aaaaaaa", "bbb", "ccc", "dddddddd" };

And I want to remove the shorter items (with length < 4), so there should remain two items left.

My first (and amateuristic) attempt was this:

foreach (string s in someStrings)
{
   if (s.Length < 4)
      someStrings.Remove(s);
}

I always use the foreach loop, but it can’t be used when modifying the collection. (You CAN modify properties of the items in the loop, but not the item reference itself!).
When you do try, you’ll get the “InvalidOperationException: Collection was modified; enumeration operation may not execute.

Somewhere in my gray mass, I reminded to use the for-loop. My second (and dangerous) attempt was this:

for (int i = 0; i < someStrings.Count; i++)
{
   if (someStrings[i].Length < 4)
      someStrings.RemoveAt(i);
}

No exceptions were thrown, but the outcome is not what you’d expect!! Due to the fact that someStrings.Count and i are out of sync, the item “ccc” is skipped.

So, here’s the correct code:

for (int i = someStrings.Count - 1; i >= 0; i--)
{
    if(someStrings[i].Length < 4)
        someStrings.RemoveAt(i);
}

Conclusion: use the for-loop and iterate backwards! :p

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Linq to Sql Profiler

I just wanted to give a shot out to the Linq to Sql Profiler.

It’s a simple but invaluable tool to watch what happens behind the scenes with linq to sql.
It’s a realtime visual debugger, and gives immediate feedback about the sql statements and their performance.

In linq to sql, you must always profile your stuff, and check what the consequences are of your code modifications.
For instance, using compiled queries everywhere doesn’t always increase performance.

Check it out!

Note: if you’re using the MS Sql Profiler, turn on these two events:
T-SQL: Sql-StmtCompleted
Stored Procedures: RPC:Completed

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Generic and fast Detach() in Linq-to-Sql

For the first time I’m experimenting with Linq-to-Sql (L2S).
Microsoft targets L2S for the simpler scenario’s/architectures (if that scares you, just let me say that stackoverflow.com is running on L2S!).
Because of this, a Detach() method is not supported. For these kind of scenario’s, Microsoft wants developers to use the Entity Framework.

One could argue if you should even use Detach() in the first place.
Here’s a nice discussion between Rick Strahl and Ian Cooper, where the latter suggests you should be sending messages across boundaries, not objects.
Steve Michelotti suggests to exclude reference data from your context.
I agree with the fact that you should be aware of what is contained in the dataContext. It’s not a garbage can, keep it small. The datacontext represents a unit of work.
However, I think this is not a complete solution. It’s not transparant, and doesn’t work every time.

In my search for a generic Detach() method, I came across this post of Jonas Stawski. It’s a generic solution with excellent performance.

You only have to add this base class method:

public void Detach()
{
   GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
}

The method uses reflection to call the Initialize() method, which will reset all the assocation properties. It can now be added to another dataContext, which will not try to save the assocation properties.

Jonas comes with a huge warning that the OnCreated() method is called after Initialize(), which could lead to unwanted behavior. I fixed this problem modifying the T4 template from which the entities are generated.

Normally, the Initialize() method is only included if you have turned on serialization. (By setting the Serialization Mode to Unidirectional). I modified the template so that it always generates these Initialize() methods.

#region Construction
public <#=class1.Name#>()
{
	Initialize();

<# if (class1.HasPrimaryKey) {#>
	OnCreated();
<# } #>
}

private void Initialize()
{
<# 		  foreach(Association association in class1.Associations) { #>
	<#=association.Storage#> = <#
	if (association.IsMany) {
		#>new EntitySet<<#=association.Type.Name#>>(attach_<#=association.Member#>, detach_<#=association.Member#>);
<#			} else {
		#>default(EntityRef<<#=association.Type.Name#>>);
<#			}
}
#>
}
#endregion

And I moved the call to OnCreated() to the constructor. Now, the code behaves exactly the same, and I’m able to call Detach() without any side effects! Nice….

Btw, here’s a free T4 editor if you need one.

I’ve seen other solutions that involved copying the entity properties using reflection or using serialization.
They’re simply a lot slower. In my test, they both took around 60 ms. This Detach() method takes 0 ms! :p

Download my custom T4 template, which is based on this Codeplex project. You have to rename the file to Model.tt.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Intellisense broken in Visual Studio 2010

I recently installed a new laptop with all the dev software. Most importantly, Visual Studio 2010 and the DevExpress productivity tools.

At some point, intellisense was working strange. I didn’t give it much attention at the time. But after a while it really started to annoy me.
At first, I thought it was some kind of new feature of CodeRush. But it turns out to Visual Studio 2010 has different modes for intellisense.

The new Suggestion mode has lower impact. This mode was added to make intelliSense completion less aggressive in certain cases, most notably test-driven development scenarios. While in this mode, intelliSense will still show a completion list but will also show what you’re typing in a box at the top of the completion list. It will not auto-complete unless you explicitly select an entry in the list.

And you toggle between these modes with Ctrl + Alt + Space. Ah! ……

See it in action

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Timestamp and Rowversion columns

To check concurrency violations, it’s common to have a Timestamp column. This column represents some kind of version of that row, and has nothing to do with the actual time. In fact, the information is stored as binary(8) when non-nullable, and varbinary(8) when nullable.

Anyway, the value in this column is being used to check if the row has been changed after it has been fetched.
However, the timestamp column is deprecated and we should use the rowversion column whenever possible.

The thing that really confused me was that this type is not available in the designer. So when you add a column with the version type, you must do it in script like this:

CREATE TABLE Test (Id int PRIMARY KEY, Version rowversion);

I really don’t understand why it’s not there, but its pretty annoying. I created a script, and added the rowversion column. But after running the script, I had to manually add the FK’s again. Grrr…

I found this stuff after searching for performance optimizations for Linq to Sql.
Normally, a query would check for concurrency violations using all the columns. With the rowversion column in place, only a single column is checked, which is a lot faster.

When you’ve added the rowversion column, and update the dbml, the following output has been generated automatically:

So you don’t have to worry setting these properties manually.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter

Linebreak in a tooltip in xaml

Here’s a quick tip how to show linebreaks in a tooltip in xaml.

I wanted to show properties on multiple lines (in a multibinding):

'

This results in the following tooltip (where the mouse hovers on the text “FTP”):

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • email
  • Hyves
  • LinkedIn
  • DotNetKicks
  • eKudos
  • Live
  • Slashdot
  • Twitter