Monday, January 24, 2011

Building a business tier with Nhibernate - Tools

I got a new task: Build Nhibernate based infrastructure, so I decided to check the existing third party tools and my boss gave me a day at home to check them  ;-D .

 I only check tools that:
  • based on existing DB 
  • support oracle 
  • works with NH 3
First tool I got my hands on is NH3SQLLogger

NH3SQLLogger - Nhibernate 3 SQL logger, this is a cool utility that will help you understand what the hell nhibernate is doing , where he is doing his stuff (yes yes a stack trace) and all parameters of queries are also reflected, this is the perfect development time logger.

do not active it on production by default, only if you need to debug prod.

Here is a sample output of this util:

---+ 01/24/2011 10:14:42.57 +---
-- Void Logic.Test.UserRepositoryTest.SaveUser() [File=UserRepositoryTest.cs, Line=86]

INSERT 
    INTO
        "User"
        (FirstName, LastName, BirthDate, Gender, PhoneNumber, IsDeleted, Created, LastUpdated, Name, Address_id, FacebookProfile_id) 
    VALUES
        (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10);

select
        last_insert_rowid();

@p0 = 'Chen' [Type: String (0)]
@p1 = 'Kinnrot' [Type: String (0)]
@p2 = 24/01/2011 00:00:00 [Type: DateTime (0)]
@p3 = 'Male' [Type: String (0)]
@p4 = '0578149177' [Type: String (0)]
@p5 = False [Type: Boolean (0)]
@p6 = 01/01/0001 00:00:00 [Type: DateTime (0)]
@p7 = 01/01/0001 00:00:00 [Type: DateTime (0)]
@p8 = 'kinnrot' [Type: String (0)]
@p9 = 1 [Type: Int64 (0)]
@p10 = 1 [Type: Int64 (0)]


NHibernator

  • Allows you to load db configuration by a key in the configuration file, good for application that works with more than one DB.
  • Wraps sessions and transactions for session per HTTP session and session per thread.  
  • No download available only code

NHibernateIt

  •  Allows you to do some basic crud through a generic repository implementation.
  •  Has the same session and transaction encapsulation as in Nhibernator.
Nhibenrate Mapping Generator - Don't know if working(Need to test on a big DB), but should generate mappings and classes from existing db, support MSSQL,Oracle and Postgre SQL.
If you got a DB and don't go fluent, this is probably good solution for a quick start.

Fluent Nhibernate - Framework with fluent interface based mapping and configuration.
Has an auto map feature with a lot of flexible convention over configuration options. One more thing they supply is an easy to use mapping test classes (called PersistenceSpecification ).

* You should consider auto mapping if your DB got name conventions, but you loose the flexibility of the mapping file per entity built in Nhibernate, and non conventional changes will make you write patches (AutoMappingOverride).



Wednesday, January 5, 2011

WPF Binding and Why you should write defensive code.

I'm overriding equals and implementing IEquatable on some of my objects and bind them as an ObservableCollection to the UI.

Here is a sample: (ugly code do not use)

<Window x:Class="BindingToItemsWithIEquality.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BindingToItemsWithIEquality"
        Title="MainWindow" Height="350" Width="525"
        >
    <Window.DataContext>
        <local:SomeContextWithCollection/>
    </Window.DataContext>
    <StackPanel>
        <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Items}"/>
        <Button Click="Button_Click">clear</Button>
    </StackPanel>
</Window>

//code behind
private void Button_Click(object sender, RoutedEventArgs e)
{
  (this.DataContext as SomeContextWithCollection).Items.Clear();
}

public class SomeContextWithCollection 
{
    public ObservableCollection<SomeIEqutable> Items { get; set; }

    public SomeContextWithCollection()
    {
      Items = new ObservableCollection<SomeIEqutable>();
      Items.Add(new SomeIEqutable() { Name = "1" });
      Items.Add(new SomeIEqutable() { Name = "2" });
    }
}

public class SomeIEqutable : IEquatable<SomeIEqutable>
{
  public string Name { get; set; }

  public override bool Equals(object obj)
  {
    if (obj == null)
    {
      return false;
    }
          
    return Equals((SomeIEqutable)obj);
  }

  public bool Equals(SomeIEqutable other)
  {
    if (object.ReferenceEquals(this, other))
    {
      return true;
    }

    return Name == other.Name;
  }

  public override int GetHashCode()
  {
    return Name.GetHashCode();
  }
}

When calling collection.Clear() I get an invalid cast inside my equals method, when trying to cast to SomeIEquatable.

This is pretty strange, object is not null and not SomeIEquatlabe, how did it get to my Equals?

The answer is WPF, when working with binding and clearing a bounded collection WPF will compare his internal new MSInternal.NamedObject(named DisconnectedItem) to your SomeIEquatable object and will fail if you try to implicitly cast it to your type.

The simple solution is to use the "as" keyword istead of cast.

If my code didn't smell from the start, I would never got to this dark place. But I'm glad it happened, now I have another excuse to write defensive code.

What do you think?

About a year ago I asked the following question
This week I got one more answer and I wanna ask you guys what do you think is the best practice?

Monday, January 3, 2011

Simple way to avoid hard coded strings in xaml

Hard coded strings are annoying,
In XAML, we have a lot of cases of hard coded strings.

Here is a simple way of implementing static naming class, and use it instead of hard coded strings.

Suppose this is my xaml:

<Window x:Class="How.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:How"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="{x:Type Button}" x:Key="LazyGuyMeaninglessName">
            <Setter Property="Margin" Value="30"/>
            <Setter Property="Height" Value="30"/>
            <Setter Property="Width" Value="200"/>
        </Style>
    </Window.Resources>
    <StackPanel>
            <Button Click="Button_Click">Click me to activate my style</Button>
        <Button Style="{DynamicResource LazyGuyMeaninglessName}"/>
    </StackPanel>
</Window>


This is code behind:

private void Button_Click(object sender, RoutedEventArgs e)
{
  var button = sender as Button;
  if (button != null)
  {
    button.Style = (Style)this.FindResource("LazyGuyMeaninglessNameWithMistake");
  }
}

I have a mistake in my code behind, and the program will crash, not so fun, and not simple to test this kind of stuff.

There is a very simple solution, Lets define this class:

public static class StyleNames
{
  public static string ButtonStyleName = "Some Hard To write style name";
}

The benefits of using this class instead of hard coded strings are:

  • No need to avoid long meaningful names, cause you have auto complete built in the IDE.
  • The obvious: avoid type mistakes, and unexpected crashes.
  • Make your programmers less lazy, they'll be able to change the resource name in a single place, and even his member name if needed, VS will rename it in all references and in XAML(VS 2010) (with a "Ctrl + ." after editing the member name).
  • If the style name is not readonly(like in my sample), I'm sure there is a simple way to support theming and dynamic style changing, by just assigning new names for all the resource names inside StyleNames class, and telling the app to do something that will reload all styles, I'm not sure about it, so don't count on it.
  • No crashes of "could not find resource bla bla".

Here is the code after the use of static class:

<Window x:Class="How.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:How"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Style TargetType="{x:Type Button}" x:Key="{x:Static local:StyleNames.ButtonStyleName}">
        <Setter Property="Margin" Value="30"/>
        <Setter Property="Height" Value="30"/>
        <Setter Property="Width" Value="200"/>
    </Style>
</Window.Resources>
<StackPanel>
        <Button Click="Button_Click">Click me to activate my style</Button>
    <Button Style="{DynamicResource ResourceKey={x:Static local:StyleNames.ButtonStyleName}}"/>
</StackPanel>
</Window>

private void Button_Click(object sender, RoutedEventArgs e)
{
  var button = sender as Button;
  if (button != null)
  {
    button.Style = (Style)this.FindResource(StyleNames.ButtonStyleName);
  }
}

Enjoy :)