Wednesday, November 16, 2011

End of job check list

I'm about to end my first gig(already end! yay I'm free!) as a programmer, and want to leave a clean desk. So here is a list of things I'm doing and suggest you all do before you move to your next gig:

1. Write about your major infrastructure developments on your wiki or any other system you got, in an easy to understand language.
2. Start lecturing your co-workers about complex parts you developed.
3. Make sure you got full code coverage with unit tests.
4. Search for to-do comments and make sure you do those todo's.
5. If you got unfinished work and think it's worth something make sure someone complete.

And the most important: change your phone number :-) (Bazinga).

Tuesday, September 27, 2011

Rubymine recommended font for windows

Didn't find a lot about it on internet so:

File->Settings->Editor->colors & fonts->Font
 first save as current schema
than click the  ... button choose Consolas and set size to 14

looks much better!

MVC Frameworks and dynamic languages

Warning! just figure out a mistake that can happen to every other programmer, and even brogrammers.

I defined a method on my model that has the same name as one of the field of the model, because I used a dynamic language (ruby on rails) it was pretty hard to understand this issue (took me more than 1 hour).

So a little tip:

When thinking about names of actions and fields of your model, work with conventions and guidelines like:
Don't name your fields after action names!!!


that's it.

Wednesday, August 31, 2011

Boolean parameters

It's not fun to look at a method call that sends more than 0 boolean parameters.

Code Snippet
  1. SetBinding(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
  1. 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.

Thursday, August 4, 2011

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.

Tuesday, August 2, 2011

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 !

Thursday, June 16, 2011

TPLing Background worker in 10 min

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7.  
  8. namespace WpfApplication1
  9. {
  10.     public class TBackgroundWorker<TResult, TProgress>
  11.     {
  12.  
  13.         public static TBackgroundWorker<TResult, TProgress> New()
  14.         {
  15.             return new TBackgroundWorker<TResult, TProgress>();
  16.         }
  17.  
  18.         public TBackgroundWorker<TResult, TProgress> StartWith(Func<object, CancellationToken, TResult> work)
  19.         {
  20.             Start = work;
  21.             return this;
  22.         }
  23.  
  24.         public TBackgroundWorker<TResult, TProgress> FinishWith(Action<TResult,object> finish)
  25.         {
  26.             Finish = finish;
  27.             return this;
  28.         }
  29.  
  30.         private readonly CancellationTokenSource _cancelationTokenSource;
  31.         private CancellationToken _cancellationToken;
  32.         private readonly TaskScheduler _uiScheduler;
  33.  
  34.  
  35.         public TBackgroundWorker()
  36.         {
  37.             _cancelationTokenSource = new CancellationTokenSource();
  38.             _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  39.         }
  40.  
  41.         protected Func<object, CancellationToken,TResult> Start { get; set; }
  42.         protected Action<TResult, object> Finish { get; set; }
  43.  
  44.         public void ReportProgress(Action<TProgress> progressReport,TProgress progress)
  45.         {
  46.             Task.Factory.StartNew(()=>progressReport(progress),CancellationToken.None,TaskCreationOptions.None,_uiScheduler);
  47.         }
  48.  
  49.         public TBackgroundWorker<TResult, TProgress> Begin(object state = null)
  50.         {
  51.             _cancellationToken = _cancelationTokenSource.Token;
  52.             Task<TResult>.Factory.
  53.                 StartNew(()=>Start(state,_cancellationToken),_cancellationToken).
  54.                 ContinueWith(x =>
  55.                                  Finish(x.Result,state),
  56.                                  _uiScheduler);
  57.  
  58.             return this;
  59.         }
  60.  
  61.         public void Cancel()
  62.         {
  63.             _cancelationTokenSource.Cancel(true);
  64.         }
  65.     }
  66. }


usage

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15.  
  16. namespace WpfApplication1
  17. {
  18.     /// <summary>
  19.     /// Interaction logic for MainWindow.xaml
  20.     /// </summary>
  21.     public partial class MainWindow : Window
  22.     {
  23.         
  24.         private TBackgroundWorker<string, int> _bg;
  25.  
  26.         public MainWindow()
  27.         {
  28.             InitializeComponent();
  29.         }
  30.  
  31.         private void a_Click(object sender, RoutedEventArgs e)
  32.         {
  33.             _bg = TBackgroundWorker<string, int>.New().
  34.                 StartWith(StartSomething).
  35.                 FinishWith(ShowResult).
  36.                 Begin();
  37.          }
  38.  
  39.         private void ShowResult(string obj,object state)
  40.         {
  41.             a.Content = obj;
  42.         }
  43.  
  44.         private string StartSomething(object arg, CancellationToken cancellationToken)
  45.         {
  46.             int i = 0;
  47.             while (i < 200)
  48.             {
  49.                 if (cancellationToken.IsCancellationRequested)
  50.                 {
  51.                     return "Cacncelled";
  52.                     
  53.                 }
  54.                 i++;
  55.                 Thread.Sleep(50);
  56.                 _bg.ReportProgress(Report,i);
  57.             }
  58.  
  59.             return "Done";
  60.         }
  61.  
  62.         private void Report(int obj)
  63.         {
  64.             a.Content = obj;
  65.         }
  66.  
  67.         private void Button_Click(object sender, RoutedEventArgs e)
  68.         {
  69.             _bg.Cancel();
  70.         }
  71.  
  72.         
  73.     }
  74. }

Monday, May 2, 2011

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



Saturday, April 23, 2011

IOC Container warning

Think about a registered component that implement copy constructor.

You'll get a Stack Overflow Exception!

So avoid it.


assembla.com

Monday, April 4, 2011

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.

Friday, February 18, 2011

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:

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