Boolean parameters

It’s not fun to look at a method call that sends more than 0 boolean parameters. Code SnippetSetBinding(false, false, comboBox); There is 100% guarantee that you will look for the documentation about this parameters and it'll slow your code reading speed. Here is a nice way to avoid the unreadable code and keep on using this meaningless Boolean. Code Snippet SetBinding(/* auto resolve= */ false, /* two way binding? = */ false, comboBox); This is not my idea though, it's from Microsoft pdb's, and I think its awesome.

August 31, 2011 · 1 min · Chen Kinnrot

If you're searching for a good place to grow

http://crossrider.com/pages/jobs I know this guys and worked with them a little, very recommended for any developer.

August 4, 2011 · 1 min · Chen Kinnrot

Dont return and linq on the same line

Just a little tip for writing a friendlier code. If you're method returns an expression, first assign it to a variable and then return him. It'll be much easier to debug inside this method and fetch all results when watching this variable. That's it !

August 2, 2011 · 1 min · Chen Kinnrot

TPLing Background worker in 10 min

Code Snippetusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace WpfApplication1{ public class TBackgroundWorker<TResult, TProgress> {  public static TBackgroundWorker<TResult, TProgress> New() { return new TBackgroundWorker<TResult, TProgress>(); }  public TBackgroundWorker<TResult, TProgress> StartWith(Func<object, CancellationToken, TResult> work) { Start = work; return this; }  public TBackgroundWorker<TResult, TProgress> FinishWith(Action<TResult,object> finish) { Finish = finish; return this; }  private readonly CancellationTokenSource _cancelationTokenSource; private CancellationToken _cancellationToken; private readonly TaskScheduler _uiScheduler;   public TBackgroundWorker() { _cancelationTokenSource = new CancellationTokenSource(); _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); }  protected Func<object, CancellationToken,TResult> Start { get; set; } protected Action<TResult, object> Finish { get; set; }  public void ReportProgress(Action<TProgress> progressReport,TProgress progress) { Task.Factory.StartNew(()=>progressReport(progress),CancellationToken.None,TaskCreationOptions.None,_uiScheduler); }  public TBackgroundWorker<TResult, TProgress> Begin(object state = null) { _cancellationToken = _cancelationTokenSource.Token; Task<TResult>.Factory. StartNew(()=>Start(state,_cancellationToken),_cancellationToken). ContinueWith(x => Finish(x.Result,state), _uiScheduler);  return this; }  public void Cancel() { _cancelationTokenSource.Cancel(true); } }} usage Code Snippetusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes; namespace WpfApplication1{ /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private TBackgroundWorker<string, int> _bg;  public MainWindow() { InitializeComponent(); }  private void a_Click(object sender, RoutedEventArgs e) { _bg = TBackgroundWorker<string, int>.New(). StartWith(StartSomething). FinishWith(ShowResult). Begin(); }  private void ShowResult(string obj,object state) { a.Content = obj; }  private string StartSomething(object arg, CancellationToken cancellationToken) { int i = 0; while (i < 200) { if (cancellationToken.IsCancellationRequested) { return "Cacncelled"; } i++; Thread.Sleep(50); _bg.ReportProgress(Report,i); }  return "Done"; }  private void Report(int obj) { a.Content = obj; }  private void Button_Click(object sender, RoutedEventArgs e) { _bg.Cancel(); }  }}

June 16, 2011 · 2 min · Chen Kinnrot

Passing complex type through WCF header,The simple always work version.

Recently I tried to find a nice code sample for how to pass complex type through WCF, inside the header, meaning I want to send the client execution context to the server side. All of the samples passes strings or uses custom header that needs to write and read the object manually, I didn’t like it. So I wrote one and it’s working! All you need is 2 classes, and one is just a factory for the other, very simple: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Text; namespace debugniv.ComplexTypeOverWcf { class HeaderHandler : IDispatchMessageInspector, IClientMessageInspector { #region Implementation of IDispatchMessageInspector public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { // Read the complex type from header var headerIndex = request.Headers.FindHeader(typeof(MyHeader).Name, typeof(MyHeader).Namespace); if (headerIndex >= 0) // found! { var serializer = GenerateDataContractSerializer<MyHeader>(); var myHeader = request.Headers.GetHeader<MyHeader>(headerIndex, serializer); // here you can do something with your header like push it to a global per request context. } return null; } public void BeforeSendReply(ref Message reply, object correlationState) { // nothing here } #endregion #region Implementation of IClientMessageInspector public object BeforeSendRequest(ref Message request, IClientChannel channel) { var myHeader = GetMyHeader(); request.Headers.Add(myHeader); } public void AfterReceiveReply(ref Message reply, object correlationState) { // nothing to do here } #endregion private DataContractSerializer GenerateDataContractSerializer<T>() { return new DataContractSerializer(typeof(T), typeof(T).Name, typeof(T).Namespace, GetKnownTypes()); } private IEnumerable<Type> GetKnownTypes() { // here return all your types inside the header yield return typeof(MyHeader); yield return typeof(SubType); } private MessageHeader GetMyHeader() { var data = new MyHeader(); var serializer = GenerateDataContractSerializer<MyHeader>(); return MessageHeader.CreateHeader(data.GetType().Name, data.GetType().Namespace, data, serializer); } } // this is the header internal class MyHeader { public SubType InternalData { get; set; } } internal class SubType { } } The second thing you’ll need is to attach this stuff to your service and proxy, here is one way to do this using System; using System.ServiceModel.Configuration; namespace debugniv.ComplexTypeOverWcf { public class HeaderExtensionElement : BehaviorExtensionElement { public override Type BehaviorType { get { return typeof (HeaderHandler); } } protected override object CreateBehavior() { return new HeaderHandler(); } } } In you config file add the following

May 2, 2011 · 2 min · Chen Kinnrot

IOC Container warning

Think about a registered component that implement copy constructor. You’ll get a Stack Overflow Exception! So avoid it.

April 23, 2011 · 1 min · Chen Kinnrot

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