Prevent setting a property value after already been set

Let’s say we write an infrastructure of entities and their interaction with Nhibernate and the rest of the server side logic. We want Nhibernate to do whatever it needs. But we also want to limit the application programmer from doing crazy things, for example: Setting the Unique Identifier of an existing entity to another value. I know it sounds crazy but in a medium-sized team, anything can happen and this stuff is critical for the future. So I thought about a very KIS way to implement this kind of protection. * What I write here is the most readable version of my code, you can extract method, use interceptor, AOP, whatever works for you. private long _id; public long ID { get { return _id; } set { if (!_id.Equals(default(long)) && !_id.Equals(value)) { throw new InvalidOperationException( “You can’t set this property, it has already been set”); } _id = value; } } Very simple, easy to test, and it works with NHibernate proxy.

April 4, 2011 · 1 min · Chen Kinnrot

Per DB Conventions With FluentNhibernate

I need to support 2 db types on my app, so I thought about a nice pattern that will help me achieve this. // I’m working with latest Fluent Nhibernate version. Define a folder for each db type you want to support like this: contain conventions for MSSQLCE and the second will contain conventions for OracleClient. For example: Oracle support schemas and sequences, SQLCE does not. lets define some simple conventions For Oracle: public class SchemaConvention : IClassConvention { public void Apply(IClassInstance instance) { instance.Schema(“MY_ORACLE_SPECIFIC_SCHEMA”); } } public class SequenceConvention : IIdConvention { public void Apply(IIdentityInstance instance) { instance.GeneratedBy.Sequence(instance.Columns.First().Name + “_SEQ”); } } And for SqlCe: class IdentityConvention : IIdConvention { public void Apply(IIdentityInstance instance) { instance.GeneratedBy.Identity(); } } So the folders will look like this: Next thing that we will need is some kind of type retriever that knows what conventions to load according to the db we are currently configuring his nhibernate stuff. Lets call it PerDBConventionSource and this is how its implemented: internal class PerDBConventionSource : ITypeSource { private readonly string _name; private IEnumerable<Type> _types; public PerDBConventionSource(string name) { _name = name; } public IEnumerable<Type> GetTypes() { _types = typeof (PerDBConventionSource).Assembly.GetTypes().Where(t => t.Namespace.EndsWith(_name)); return _types; } /// <summary> /// Logs the activity of this type source. /// </summary> /// <param name=“logger”>The logger.</param> public void LogSource(IDiagnosticLogger logger) { // TODO : Log if you want } public string GetIdentifier() { return _name; } } Notice that i’m implementing ITypeSource, an interface belong to FluentNhibernate, this is how i tell FluentNhibernate to use this as a convention source: (I used only fluentMappings so I add the conventions only on fluentMappings) private static IPersistenceConfigurer _persistenceConfigurer; private static void ConfigureNH(IPersistenceConfigurer persistenceConfigurer) { _persistenceConfigurer = persistenceConfigurer; Fluently. Configure(). Database(persistenceConfigurer). Diagnostics(x => x.Enable(true).OutputToConsole()). Mappings(SomeMappings). BuildConfiguration(); } private static void SomeMappings(MappingConfiguration mappingConfiguration) { string name = _persistenceConfigurer.GetType().Name.Replace(“Configuration”, string.Empty); mappingConfiguration.FluentMappings.Conventions.AddSource(new PerDBConventionSource(name)); } So when I’ll run the following code: Console.BackgroundColor = ConsoleColor.DarkGreen; Console.ForegroundColor= ConsoleColor.Green; ConfigureNH(OracleClientConfiguration.Oracle10.ConnectionString(“some OracleClient connection”)); Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.Blue; ConfigureNH(MsSqlCeConfiguration.Standard.ConnectionString(“some MsSqlCe connection”)); The result will be Why you should use his pattern anyway(even if you work with 1 db): 1. unit testing with sqlite in memory will not work with sequence conventions, so you shouldn’t load them when you are unit testing. 2. If you’ll some day change the db type, you’ll know where to add its own conventions, just create a folder with db name and add it’s conventions inside no other change is necessary. You can find the source here:

February 18, 2011 · 2 min · Chen Kinnrot

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 3First 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 codeNHibernateIt 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).

January 24, 2011 · 2 min · Chen Kinnrot

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 instead 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.

January 5, 2011 · 2 min · Chen Kinnrot

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?

January 5, 2011 · 1 min · Chen Kinnrot

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 :)

January 3, 2011 · 2 min · Chen Kinnrot

Nice PHP IDE

Recently a friend recommend me to check the PHP Storm IDE. I must say that its a grate IDE, almost same capabilities as IntelliJ, I’v never seen a PHP IDE with this refactoring and navigation features. So check it out. Thank you Gal Batat for the recommendation. Features and download is here

December 24, 2010 · 1 min · Chen Kinnrot

Unit testing with mock framework and IEquatable<>

This post is relevant for the one’s who write tests, all you other programmers, you should learn unit testing and read it. One of the most useful tools in unit testing is a good mocking framework. (I’m currently using Moq, and before that I used rhino) We all know that for mocking we need interfaces. My tip is very simple, if you have a class Foo and you wanna mock it, first you should have Interface IFoo (this should be obvious to most of you).Implement on Foo IEquatable<IFoo>, so if you test a list of IFoo and you want to assert Contains() you won’t have any problems with the proxy of IFoo that mocking framework generates on the interface and no one will blame you for your awful class that throws cast exception in its equals method :). Hope it’ll save you time in future. That it, KIS.

November 17, 2010 · 1 min · Chen Kinnrot

Event Base WPF Navigation

Hello, My Recent problem was: How can I implement minimal decoupling navigation between views? I thought about using the EventAggregator already built in my system and create some kind of event that represents a navigation request, so I created a NavigationRequestEvent that contains the view model I want to activate and view. Next question I asked myself was: Who needs to request for navigation? This is easy navigation is caused 99% of the times by user interaction, views is a good answer, through their view models or some commands (if not DelegateCommands or SmarterStuff). The problem is that my view models are being created from my IOC Container (not a problem) and I don’t want all of my view models to have access to my container cause this is an anti pattern. Who’ll construct the view model and fire the event? Create a view models factory that will be responsible for creating the view models, he is not the actual factory, just a mediator between the request and the container. So far we got: NavigationRequestEvent that holds the view model to showViewModelsFactory - can create view models Now I just need someone to listen, this is the advantage of this pattern, anyone can listen and no one is also an option, but nothing will happen of course. In my case the shell is the default listener and each event would be translated to a view shown at the main region of the ui , there is also an option of a split view, when split view activated the main region unregister from event and secondary view is listening to the event. We can also expend this behavior and allow user to choose where next views will be opened. IsNice = True;

October 12, 2010 · 2 min · Chen Kinnrot

Simple abstraction and decoupling example

Just code. We have a logger and a log viewer, could be better but I wanted it to be simple. This is the window that is also the log viewer /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, ILogViewer { public MainWindow() { InitializeComponent(); Logger.RegisterViewer(this); } public void Log(string message) { // do the write logic } } This is the interface of viewers public interface ILogViewer { void Log(string message); } This is logger public static class Logger { static List<ILogViewer> viewers = new List<ILogViewer>(); public static void RegisterViewer(ILogViewer viewer) { viewers.Add(viewer); } public static void Log(string message) { foreach (ILogViewer viewer in viewers) { viewer.Log(message); } } }

September 22, 2010 · 1 min · Chen Kinnrot