Guidelines for working with ADO.Net Entity Framework

I would like to share with you some Guidelines for working with ADO.Net Entity Framework and other Linq flavored Framework.

  • We should enable all the integrity from the database. The validation of the integrity is not provided by the framework. It will be more effective if the database can return the index or the foreign key that is failing. I will need to do some test on this.
  • Don’t add instance properties or methods to the entities. Entities are not like business objects, they are only data container. Also, using instance properties inside entity reduce the easiness to write queries using the linq syntax.

    Ex: Supposed you’ve add the property MyProperty by code to the entity Employee. Now, supposed someone want to query the employee with your property:

    var q = from e in db.Employees
    where e.MyProperty != null
    select e;

    This will throw an exception at runtime because MyProperty cannot be translated to SQL.
  • Consider not putting validation into the model.
  • Don’t put UI stuff in the model. It may seems evident but ...
  • Use an interface over your model. Consider design for testability.

I will probably add more in the future.

Stay tune!

Dany

WeakEventHandler

I came across a problem this week. I was needing a weak delegate to handle a situation where I have a ListBox and I want it to listen to a property changed on a selected ListBoxItem. This situation need to have a weak delegate because if the ListBoxItem is kept referenced, I want to let the ListBox to be garbage collected.

This is how I have implemented the WeakEventHandler. I thought it was a good implementation because it also supports the anonymous methods even if they are closure.

WeakEventHandler

The WeakEventHandler is a thin class inheriting the WeakHandler<T> and provinding a closure delegate in the CreateHandler.

public sealed class WeakEventHandler : WeakHandler<EventHandler>
{
    public WeakEventHandler(EventHandler handler)
        : base(handler)
    {
    }

    protected override EventHandler CreateHandler(WeakReference weakReference)
    {
        return (sender, e) =>
        {
            var h = (EventHandler)weakReference.Target;
            if (h != null)
                h(sender, e);
        };
    }
}

The WeakHandler base class

The WeakHandler is the based class for all delegate type. It provide automatic translation to a weak delegate build by the CreateHandler.

 
public abstract class WeakHandler<T> where T : class
{
    private T handler;
    private T implicitHandler;

    protected WeakHandler(T handler)
    {
        if (handler == null)
            throw new ArgumentNullException("handler");

        if (!(handler is Delegate))
        {
            throw new InvalidOperationException();
        }

        this.handler = handler;
    }

    protected abstract T CreateHandler(WeakReference weakReference);

    public static implicit operator T(WeakHandler<T> weakHandler)
    {
        if (weakHandler == null)
            return null;

        if (weakHandler.implicitHandler == null)
        {
            lock (weakHandler.handler)
            {
                if (weakHandler.implicitHandler == null)
                {
                    var ih = weakHandler.CreateHandler(new WeakReference(weakHandler.handler));
                    Thread.MemoryBarrier();
                    weakHandler.implicitHandler = ih;
                }
            }
        }

        return weakHandler.implicitHandler;
    }
}

 

How to use it

You can use the WeakEventHandler simply as if you where the EventHandler provided by the framework:


Form f = new Form();
f.SizeChanged += new WeakEventHandler(delegate(object sender, EventArgs e)
    {
        Console.WriteLine("Form changed.");
    });

 

Where are we?

We saw how to implement and reuse weak event handler. This event is very easy to create and reuse.

Happy Programming!

Testability of your Linq For Sql Model

I have already spoke with my friends about this. I think it’s the time to post it in my blog. Here is how I shield my implementation from the model.

Use an interface, not the class

Instead of using directly the DataModel generated by the Linq For Sql designer, you could use an interface representing your model.

public interface IDataContext
{
void SaveChanges();
}

public interface IEmployeeModel : IDataContext
{
void AddEmployee(Employee employee);
void DeleteEmployee(Employee employee);
IQueryable<Employee> Employees { get; }
}

We can see here that we have an interface that represent our model.

Customizing the generated partial class

The model generated by the Linq For Sql Designer is using a partial class. Using this feature, we can support for our IEmployeeModel interface. Here is how we do this:

partial class DataClasses1DataContext : IEmployeeModel
{
#region IEmployeeModel Members

public void AddEmployee(Employee employee)
{
if (employee == null)
throw new ArgumentNullException("employee");

this.Employees.InsertOnSubmit(employee);
}

void IEmployeeModel.DeleteEmployee(Employee employee)
{
if (employee == null)
throw new ArgumentNullException("employee");

this.Employees.DeleteOnSubmit(employee);
}

IQueryable<Employee> IEmployeeModel.Employees
{
get { return this.Employees; }
}

#endregion

#region
IDataContext Members

public void SaveChanges()
{
this.SubmitChanges();
}

#endregion
}

Implement a MockEmployeeModel class

After doing our real model, we can create a mock of our model to simulate database for very specific cases without touching the database. This way, we will be able to test even our Linq queries.



public class MockEmployeeModel : IEmployeeModel
{
private List<Employee> employees;

public MockEmployeeModel()
{
this.employees = new List<Employee>();
}

#region IEmployeeModel Members

public void AddEmployee(Employee employee)
{
if (employee == null)
throw new ArgumentNullException("employee");

this.employees.Add(employee);
}

public void DeleteEmployee(Employee employee)
{
if (employee == null)
throw new ArgumentNullException("employee");

this.employees.Remove(employee);
}

public IQueryable<Employee> Employees
{
get { return this.employees.AsQueryable(); }
}

#endregion

#region
IDataContext Members

public void SaveChanges()
{
// Nothing special to do here.
}

#endregion
}

Limitations


  • Compiled Linq queries are not supported. I will probably show you in a next post how to support it.


  • The MockModel is very limited. We would probably benefit having a mocking framework here.

Conclusion

As a typical use, we can now use normal linq queries over our model and test our queries in the very same manner using our MockEmployeeModel. This approach works with ADO.Net Entity Framework as well.



Happy Programming!

WPF: ComboBox and Null Values

When binding a ComboBox in WPF, you don’t have access to select a null value. There is several ways to allow ComboBox to select a null value:

  1. By Code: You can create a list of items and add a null item (not a null value but and item instance representing the null value). This is not reusable.
  2. By using a Converter: This is a bit more reusable but is not the best for scenario that already needs a converter. Also, this method require a convert from and a convert back of the value.
  3. By using an Attached Property: To me, this seems the ideal way (unless it is implemented directly by the ComboBox) to manage null value and this will be the technique describe here.

Here is how to create the Attached property:

public static class ComboUtil
{
private static readonly CommandBinding DeleteCommandBinding = new CommandBinding(ApplicationCommands.Delete, HandleExecuteDeleteCommand);

private static void HandleExecuteDeleteCommand(object sender, ExecutedRoutedEventArgs e)
{
var combo = e.Source as ComboBox;
if (combo != null)
combo.SelectedIndex = -1;
}

#region AllowNull Property

public static bool GetAllowNull(ComboBox combo)
{
if (combo == null)
throw new ArgumentNullException("combo");

return (bool)combo.GetValue(AllowNullProperty);
}

public static void SetAllowNull(ComboBox combo, bool value)
{
if (combo == null)
throw new ArgumentNullException("combo");

combo.SetValue(AllowNullProperty, value);
}

public static readonly DependencyProperty AllowNullProperty =
DependencyProperty.RegisterAttached(
"AllowNull",
typeof(bool),
typeof(ComboUtil),
new UIPropertyMetadata(HandleAllowNullPropertyChanged));

private static void HandleAllowNullPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var combo = (ComboBox)o;
if (true.Equals(e.NewValue))
{
if (!combo.CommandBindings.Contains(DeleteCommandBinding))
combo.CommandBindings.Add(DeleteCommandBinding);
}
else
{
combo.CommandBindings.Remove(DeleteCommandBinding);
}
}

#endregion
}



By using the above code, you will now be able to create a nullable comboBox by xaml only:



<ComboBox local:ComboUtil.AllowNull="true">
<
ComboBoxItem>Hello</ComboBoxItem>
<
ComboBoxItem>Hi</ComboBoxItem>
</
ComboBox>





and reset the combo by hitting the <DELETE> key when the ComboBox has the input focus.



Happy WPF programming!



Dany

Anonymous Types and Linq Compiled Queries revisited!

I have undertaken recently to bring a project coded with sql queries and stored procs in Linq and tried to eliminate all stored procs. The code need to be very efficient because the amount of data to be processed is huge. I came across the linq queries and found that we can compiled them in order that only the parameters can change and the query and the reading delegate are reused over and over. This is the best approach in my case because queries are not dynamic and it is very near as efficient as direct sql. What I need is create a query, and compile it using

System.Data.Linq.CompiledQuery.Compile…

But wait, this is not that simple. There is a problem. You can’t use a compiled query with an anonymous type! How would you store the resulting delegate func. You can’t reuse the anonymous type outside of the scope of the method.

Really?

No, we can do something about it. Here is how I resolve the issue:

  • Create a query holder. I have create a struct that will hold the func delegate but as an object.
    public struct CompiledQuery
    {
    private object query;
    }



  • Now, I have created a bunch of methods on that struct that will execute the query. This is the best because it manage automatically the lifetime of the query.



    public TResult Execute<TDbContext, TResult>(
    TDbContext context,
    Expression<Func<TDbContext, TResult>> query) where TDbContext : DataContext
    {
    if (context == null)
    throw new ArgumentNullException("context");

    if (query == null)
    throw new ArgumentNullException("query");

    Func<TDbContext, TResult> func;

    if (this.query == null)
    {
    func = System.Data.Linq.CompiledQuery.Compile<TDbContext, TResult>(query);
    this.query = func;
    }
    else
    func = (Func<TDbContext, TResult>)this.query;

    return func(context);
    }


    This works because we are using the compiler type inference to help us finding the type of the delegate and casting is as a valid as func.





  • After that, I can use the code to query the data directly. Really simple isn’t it?



    public class MyClass
    {
    private CompiledQuery myQuery;

    public void MyMethod()
    {
    using (var context = new DbDataContext())
    {
    var items = this.myQuery.Execute(context,
    c =>
    from e in c.Employees
    select new
    {
    e.FirstName,
    e.LastName,
    e.EmployeeNumber
    });

    foreach (var item in items)
    {
    Console.WriteLine("FirstName = {0}, LastName = {1}, Number = {2}", item.FirstName, item.LastName, item.EmployeeNumber);
    }
    }
    }
    }









 



Happy Linq programming! Have a nice week!

Dany


A better context container

Suppose you want to share some context info between multiple methods / objects. In WCF you must use OperationContext.Current to store the data. In ASP.Net, you can use the session, or better the HttpContext.Items. For Windows Forms, you will have the ThreadStatic attribute. With my new implementation of an AmbientContext, we have a single store to share the context data in all of theses scenarios.

I've picked the idea here:

http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/

and here:

http://msdn.microsoft.com/msdnmag/issues/06/09/NETMatters/default.aspx

OK, here is a sample code to use it:

public void Method1()
{
using (new AmbientContextScope())
{
AmbientContext.Current.SetLogicalValue(
"userInfo",
new UserInfo()
{
DisplayName = "Dany Laporte",
Username = "danlap"
});

this.ShowUserInContext();
}
}

public void ShowUserInContext()
{
if (AmbientContext.Current != null)
{
UserInfo userInfo = (UserInfo)AmbientContext.Current.GetLogicalValue("userInfo");
Console.WriteLine(userInfo.DisplayName);
}
}

With a context scope, you can copy the data upon multiple contexts or multiple threads easily. You can also create delegate that are scoped based on the current context.


using (new AmbientContextScope())
{
AmbientContext.Current.SetLogicalValue("myKey", "myValue");

ThreadPool.QueueUserWorkItem(
AmbientContext.Current.CreateScopedDelegate(
delegate(object state)
{
Console.WriteLine(AmbientContext.Current.GetLogicalValue("myKey"));
}));
}

Here is a simple class diagram of the actual implementation:



AmbientContextDiagram

Please tell me what you think?

Pourquoi on ne devrait pas utiliser l'héritage de classe

Voici un article intéressant décrivant une facette négative de l'héritage de classe. http://www.berniecode.com/writing/inheritance/

C# 3.0 - Méthodes d'extensions et exceptions

Pour ceux et celles qui commencent à utiliser le C# 3.0, vous avez sans doute commencé à utiliser les méthodes d'extensions. Cette nouvelle possibilité nous permet maintenant d'étendre les classes, structures et interfaces en leur ajoutant de nouvelles méthodes.

Aujourd'hui, j'aimerais utiliser les méthodes d'extensions afin de pouvoir réduire le code pour lever des exceptions. La plupart d'entre nous, lorsque nous voulons lever une exception, nous écrivons le code suivant:

public Employee CreateEmployee(string employeeNumber)
{
if (employeeNumber == null)
throw new ArgumentNullException("employeeNumber");

if (employeeNumber.Length == 0)
throw new ArgumentException(string.Format(Properties.Resources.ArgumentStringCannotBeEmtpy, "employeeNumber"), "employeeNumber");

return new Employee(employeeNumber);
}



Ce code très simple mais est souvent redondant et tellement long à écrire que certain programmeur préfère omettre ce code et ne pas lever d'exceptions.



J'ai décidé de me pencher sur le problème et d'essayer de trouver une solution pour écrire moins de code. Voici la solution que je propose:



public Employee CreateEmployee(string employeeNumber)
{
employeeNumber.Check("employeeNumber").ThrowNull().ThrowEmpty();
return new Employee(employeeNumber);
}


C'est beaucoup plus compact et permet de réutiliser le code qui lève les exceptions. La méthode d'extension Check est ajoutée à tous les types de classe et permet d'introduire le nom du paramètre à vérifier. Ensuite, le ThrowNull (réservé aux classes) lève un ArgumentNullException si le paramètre est null. Le ThrowEmpty (réservé aux Strings) lève le ArgumentException.


Qu'en pensez-vous?


Il est possible de pousser les validations encore plus loin et d'ajouter des lambdas. J'en parlerai dans un prochain billet. A+


Dany.