Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

Entity Framework Code First Fluent Validation

Back to Entity Framework Code First (EFCF) validation. On my previous post I mentioned that EFCF did not support fluent validation. While this is true, it isn’t too hard to implement one such mechanism, which is exactly why I am writing this! Smile

I will be using the SavingChanges event to inject the validation logic, which will be implemented by strongly typed delegates. Let’s see some code:

   1: public static class DbContextExtensions
   2: {
   3:     private static IDictionary<Type, Tuple<Delegate, String>> entityValidations = new ConcurrentDictionary<Type, Tuple<Delegate, String>>();
   4:  
   5:     public static void AddEntityValidation<TEntity>(this DbContext context, Func<TEntity, Boolean> validation, String message) where TEntity : class
   6:     {
   7:         if (context == null)
   8:         {
   9:             throw new ArgumentNullException("context");
  10:         }
  11:  
  12:         if (validation == null)
  13:         {
  14:             throw new ArgumentNullException("validation");
  15:         }
  16:  
  17:         if (String.IsNullOrWhiteSpace(message) == true)
  18:         {
  19:             throw new ArgumentNullException("message");
  20:         }
  21:  
  22:         if (entityValidations.ContainsKey(typeof(TEntity)) == false)
  23:         {
  24:             (context as IObjectContextAdapter).ObjectContext.SavingChanges += delegate
  25:             {
  26:                 if (context.Configuration.ValidateOnSaveEnabled == true)
  27:                 {
  28:                     IEnumerable<TEntity> entities = context.ChangeTracker.Entries<TEntity>().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified).Select(x => x.Entity).ToList();
  29:  
  30:                     foreach (TEntity entity in entities)
  31:                     {
  32:                         String error = ValidateEntity(entity);
  33:  
  34:                         if (String.IsNullOrWhiteSpace(error) == false)
  35:                         {
  36:                             throw (new ValidationException(error));
  37:                         }
  38:                     }
  39:                 }
  40:             };
  41:         }
  42:  
  43:         entityValidations[typeof(TEntity)] = new Tuple<Delegate, String>(validation, message);
  44:     }
  45:  
  46:     private static String ValidateEntity<TEntity>(TEntity entity)
  47:     {
  48:         Type entityType = typeof(TEntity);
  49:  
  50:         if (entityValidations.ContainsKey(entityType) == true)
  51:         {
  52:             Tuple<Delegate, String> entry = entityValidations[entityType];
  53:             Func<TEntity, Boolean> validation = entry.Item1 as Func<TEntity, Boolean>;
  54:  
  55:             if (validation(entity) == false)
  56:             {
  57:                 return (entry.Item2);
  58:             }
  59:         }
  60:  
  61:         return (null);
  62:     }
  63: }

We have an extension method that allows declaring, for an entity type, a validation expression, such as this:

   1: ctx.AddEntityValidation<SomeEntity>(x => x.SomeProperty != null, "SomeProperty is required");

The validation will be fired when the SaveChanges method is called and the errors will be encapsulated in a ValidationException:

   1: try
   2: {
   3:     ctx.SaveChanges();
   4: }
   5: catch (ValidationException ex)
   6: {
   7:     //see content of ex.ValidationResult.ErrorMessage
   8: }

This code can certainly be improved – multiple validations per entity, property-based validations, etc – but I think it is good enough to illustrate my technique.

One final note: the fluent validation will only be fired if the ValidateOnSaveEnabled property is set to true, which is the default.

Entity Framework Code First Validation

Introduction

Most persistence frameworks implement some kind of custom validation of entities before they are sent to the database. By custom I mean something more than just “is not null”, “has XX characters”, etc. This typically includes individual properties as well as validation of the entity as a whole – for example, checking that a property’s value is valid when used together with another property’s value.

Entity Framework Code First is no exception. Out of the box it already offers a number of possibilities for validating entities that cover typical scenarios: validation by attributes or by a validation method. One validation left out is one based on XML, but since Code First doesn’t really use XML, it should be no surprise, and the other is fluent validation, something that really should be supported.

Let’s explore each of these possibilities.

Overriding ValidateEntity

The DbContext class has a virtual method called ShouldValidateEntity that is called for each entity about to be persisted – meaning, inserted or updated –, and, when it returns true – which it does by default – will trigger a call to ValidateEntity, another virtual method. In this method, we have a chance to validate our entities any way we like. An example might be, for instance, checking if the entity to be saved implements IDataErrorInfo and extract validation information from this implementation:

   1: protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<Object, Object> items)
   2: {
   3:     DbEntityValidationResult result = base.ValidateEntity(entityEntry, items);
   4:     IDataErrorInfo dei = entityEntry.Entity as IDataErrorInfo;
   5:     
   6:     foreach (String propertyName in entityEntry.CurrentValues.PropertyNames)
   7:     {
   8:         String errorMessage = dei[propertyName];
   9:  
  10:         if (String.IsNullOrWhiteSpace(errorMessage) == false)
  11:         {
  12:             result.ValidationErrors.Add(new DbValidationError(propertyName, errorMessage));
  13:         }
  14:     }
  15:  
  16:     return (result);
  17: }

For the validation to occur, the ValidateOnSave property must be true, which it is by default.
Don’t forget to always call the base implementation!

Applying Validation Attributes

Another option, which also applies to ASP.NET MVC validation (see http://weblogs.asp.net/ricardoperes/archive/2012/06/03/asp-net-mvc-validation-complete.aspx) is using validation attributes, that is, attributes that inherit from ValidationAttribute. The base ValidateEntity method of DbContext also checks for these attributes, another reason why you should always call it. Let’s see an example:

   1: [Serializable]
   2: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
   3: public sealed class PositiveAttribute : ValidationAttribute
   4: {
   5:     protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
   6:     {
   7:         Int64 longValue = Convert.ToInt64(value);
   8:  
   9:         if (longValue <= 0)
  10:         {
  11:             return (new ValidationResult("Value cannot be negative or zero"));
  12:         }
  13:  
  14:         return (ValidationResult.Success);
  15:     }
  16: }

You would then apply this to some property in your entity:

   1: public class MyEntity
   2: {
   3:     [Positive]
   4:     public Int64 MyAlwaysPositiveNumber { get; set; }
   5: }

The “problem” with this approach is that you must include any assemblies containing these custom validation attributes together with your model. If they are on the same assembly, there’s no problem.

By the way, you can specify multiple validation attributes and you can even apply them to the whole class, not just a property.

Implementing IValidatableObject

Another option, also common to MVC, is having your entities implement IValidatableObject. This interface defines a contract for returning a collection of validation errors for an entity. Here’s a sample implementation:

   1: public class Contract : IValidatableObject
   2: {
   3:     public String Name { get; set; }
   4:     public DateTime StartDate { get; set; }
   5:     public DateTime EndDate { get; set; }
   6:  
   7:     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
   8:     {
   9:         if (this.StartDate >= this.EndDate)
  10:         {
  11:             yield return (new ValidationResult("The end date is before or the same as the start date", new String[] { "StartDate", "EndDate" }));
  12:         }
  13:     }
  14: }

Handling SavingChanges Event

The “underlying” ObjectContext – which, in fact, is only created if requested – exposes a SavingChanges event which is triggered whenever Entity Framework is about to send changes to the database, typically whenever the SaveChanges method is called. If we handle this event, we can perform our custom validation before our entities are saved, and in case something is wrong we can throw an exception to cancel the saving process:

   1: (ctx as IObjectContextAdapter).ObjectContext.SavingChanges += ObjectContext_SavingChanges;
   2:  
   3: void ObjectContext_SavingChanges(Object sender, EventArgs e)
   4: {
   5:     ObjectContext octx = sender as ObjectContext;
   6:     IEnumerable<Object> entities = octx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).Select(x => x.Entity);
   7:  
   8:     //do custom validation and throw an exception if something wrong is found
   9:  
  10: }

This has the arguable advantage that it decouples the validation process from the entities and the context themselves.

Conclusion

In case you are using any of these validation techniques, always surround calls to SaveChanges inside a try…catch block and look out for a DbEntityValidationException or your own exception, if you followed the SavingChanges approach. Inside DbEntityValidationException you have an EntityValidationErrors that contains all the details:

   1: try
   2: {
   3:     ctx.SaveChanges();
   4: }
   5: catch (DbEntityValidationException ex)
   6: {
   7:     foreach (DbEntityValidationResult result in ex.EntityValidationErrors)
   8:     {
   9:         //..
  10:     }
  11: }

Alternatively, you can explicitly call GetValidationErrors and see the collection of errors from all sources, except, of course, SavingChanges, because the context is not actually in the process of saving changes, for all entities currently being tracked by the context.

The order by which these validation processes are applied is:

  1. ValidateEntity
  2. ValidationAttribute (from base ValidateEntity)
  3. IValidatableObject (from base ValidateEntity
  4. SavingChanges (only if no errors are found)

Pick the one that better suits your needs!

Blogs Portugueses Sobre SharePoint

This post is in portuguese only, sorry!

A partir de um comentário no LinkedIn, no grupo da Comunidade Portuguesa de SharePoint (http://www.linkedin.com/groups?home=&gid=996587&trk=anet_ug_hm) foi começada uma lista dos blogs de autores portugueses e brasileiros sobre SharePoint, ainda que não exclusivamente. Vou publicar essa lista aqui, e tentarei mantê-la actualizada.

Se conhecerem mais, por favor, comuniquem-mos!

Using the Enterprise Library 6 Configuration Console with Visual Studio 2012

You will have to download and run the Configuration Console from http://www.microsoft.com/en-us/download/details.aspx?id=38789, there is no NuGet package for it. After that, you will get a context menu for each project on the solution for editing the configuration:

image

Filter Collections Automatically With Entity Framework Code First

Introduction

In some O/RMs, it is possible to specify automatic filters for entity collections such as one-to-many or many-to-many. These are applied automatically whenever these collections are being populated. Entity Framework does not offer one such mechanism, however, it is possible to implement it.

Context Collections

In Entity Framework Code First, entities are exposed as IDbSet<T> or DbSet<T> collections on a context, a DbContext-derived class. There is no way to automatically set a filter that will apply to all queries coming from these collections, unless we create our own IDbSet<T> class. Let’s call it FilteredDbSet<T> and have it implement the same interfaces as DbSet<T> so that it can be used instead of it transparently:

   1: public class FilteredDbSet<TEntity> : IDbSet<TEntity>, IOrderedQueryable<TEntity> where TEntity : class
   2: {
   3:     #region Private readonly fields
   4:     private readonly DbSet<TEntity> set;
   5:     private readonly Func<TEntity, Boolean> matchesFilter;
   6:     #endregion
   7:  
   8:     #region Public constructors
   9:     public FilteredDbSet(DbContext context, Expression<Func<TEntity, Boolean>> filter)
  10:     {
  11:         this.set = set;
  12:         this.Filter = filter;
  13:         this.matchesFilter = filter.Compile();
  14:     }
  15:  
  16:     #endregion
  17:  
  18:     #region Public properties
  19:     public Expression<Func<TEntity, Boolean>> Filter
  20:     {
  21:         get;
  22:         protected set;
  23:     }
  24:  
  25:     public IQueryable<TEntity> Unfiltered
  26:     {
  27:         get
  28:         {
  29:             return (this.set);
  30:         }
  31:     }
  32:     #endregion
  33:  
  34:     #region Public methods
  35:     public IQueryable<TEntity> Include(String path)
  36:     {
  37:         return (this.set.Include(path).Where(this.Filter));
  38:     }
  39:  
  40:     public DbSqlQuery<TEntity> SqlQuery(String sql, params Object[] parameters)
  41:     {
  42:         return (this.set.SqlQuery(sql, parameters));
  43:     }
  44:     #endregion
  45:  
  46:     #region IDbSet<TEntity> Members
  47:     TEntity IDbSet<TEntity>.Add(TEntity entity)
  48:     {
  49:         this.ThrowIfEntityDoesNotMatchFilter(entity);
  50:         return (this.set.Add(entity));
  51:     }
  52:  
  53:     TEntity IDbSet<TEntity>.Attach(TEntity entity)
  54:     {
  55:         this.ThrowIfEntityDoesNotMatchFilter(entity);
  56:         return (this.set.Attach(entity));
  57:     }
  58:  
  59:     TDerivedEntity IDbSet<TEntity>.Create<TDerivedEntity>()
  60:     {
  61:         var entity = this.set.Create<TDerivedEntity>();
  62:         return (entity as TDerivedEntity);
  63:     }
  64:  
  65:     TEntity IDbSet<TEntity>.Create()
  66:     {
  67:         var entity = this.set.Create();
  68:         return (entity);
  69:     }
  70:  
  71:     TEntity IDbSet<TEntity>.Find(params Object[] keyValues)
  72:     {
  73:         var entity = this.set.Find(keyValues);
  74:         ThrowIfEntityDoesNotMatchFilter(entity);
  75:         return (entity);
  76:     }
  77:  
  78:     TEntity IDbSet<TEntity>.Remove(TEntity entity)
  79:     {
  80:         ThrowIfEntityDoesNotMatchFilter(entity);
  81:         return (this.set.Remove(entity));
  82:     }
  83:  
  84:     ObservableCollection<TEntity> IDbSet<TEntity>.Local
  85:     {
  86:         get { return (this.set.Local); }
  87:     }
  88:     #endregion
  89:  
  90:     #region IEnumerable<TEntity> Members
  91:     IEnumerator<TEntity> IEnumerable<TEntity>.GetEnumerator()
  92:     {
  93:         return (this.set.Where(this.Filter).GetEnumerator());
  94:     }
  95:     #endregion
  96:  
  97:     #region IEnumerable Members
  98:     IEnumerator IEnumerable.GetEnumerator()
  99:     {
 100:         return ((this as IEnumerable<TEntity>).GetEnumerator());
 101:     }
 102:     #endregion
 103:  
 104:     #region IQueryable Members
 105:     Type IQueryable.ElementType
 106:     {
 107:         get { return ((this.set as IQueryable).ElementType); }
 108:     }
 109:  
 110:     Expression IQueryable.Expression
 111:     {
 112:         get
 113:         {
 114:             return (this.set.Where(this.Filter).Expression);
 115:         }
 116:     }
 117:  
 118:     IQueryProvider IQueryable.Provider
 119:     {
 120:         get
 121:         {
 122:             return ((this.set as IQueryable).Provider);
 123:         }
 124:     }
 125:     #endregion
 126:  
 127:     #region Private methods
 128:     private void ThrowIfEntityDoesNotMatchFilter(TEntity entity)
 129:     {
 130:         if ((entity != null) && (this.matchesFilter(entity) == false))
 131:         {
 132:             throw (new ArgumentException("Entity does not match filter", "entity"));
 133:         }
 134:     }
 135:  
 136:     #endregion
 137: }

In the constructor of our DbContext, we create instances of this class, and pass a LINQ restriction query on its constructor:

   1: public MyContext : DbContext
   2: {
   3:     public MyContext()
   4:     {
   5:         this.Bases = new FilteredDbSet<Base>(this, x => x.SomeProperty == 1);
   6:     }
   7:  
   8:     public IDbSet<Base> Bases { get; protected set; }
   9: }

From now on, all queries over the Bases collection will be restricted.

Entity Collections

A different matter is collections on entities. For these, we usually declare a property of ICollection<T> and let Entity Framework create an instance for us, when it is loading the entity. The class responsible for creating this instance is DbCollectionEntry, which unfortunately does not allow subclassing, because it doesn’t have any public or protected constructors or virtual methods. Let’s take a different path and create our own collection class instead:

   1: [Serializable]
   2: public class FilteredCollection<T> : ICollection<T>
   3: {
   4:     private readonly DbCollectionEntry collectionEntry;
   5:     private readonly Func<T, Boolean> compiledFilter;
   6:     private ICollection<T> collection;
   7:  
   8:     public FilteredCollection(ICollection<T> collection, DbCollectionEntry collectionEntry, Expression<Func<T, Boolean>> filter)
   9:     {
  10:         this.Filter = filter;
  11:         this.collection = collection ?? new HashSet<T>();
  12:         this.collectionEntry = collectionEntry;
  13:         this.compiledFilter = filter.Compile();
  14:  
  15:         if (collection != null)
  16:         {
  17:             foreach (T entity in collection)
  18:             {
  19:                 this.collection.Add(entity);
  20:             }
  21:  
  22:             this.collectionEntry.CurrentValue = this;
  23:         }
  24:         else
  25:         {
  26:             this.LoadIfNecessary();
  27:         }
  28:     }
  29:  
  30:     public Expression<Func<T, Boolean>> Filter
  31:     {
  32:         get;
  33:         private set;
  34:     }
  35:  
  36:     protected void ThrowIfInvalid(T entity)
  37:     {
  38:         if (this.compiledFilter(entity) == false)
  39:         {
  40:             throw (new ArgumentException("entity"));
  41:         }
  42:     }
  43:  
  44:     protected void LoadIfNecessary()
  45:     {
  46:         if (this.collectionEntry.IsLoaded == false)
  47:         {
  48:             IQueryable<T> query = this.collectionEntry.Query().Cast<T>().Where(this.Filter);
  49:  
  50:             this.collection = query.ToList();
  51:  
  52:             this.collectionEntry.CurrentValue = this;
  53:  
  54:             var _internalCollectionEntry = this.collectionEntry.GetType().GetField("_internalCollectionEntry", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this.collectionEntry);
  55:             var _relatedEnd = _internalCollectionEntry.GetType().BaseType.GetField("_relatedEnd", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(_internalCollectionEntry);
  56:             _relatedEnd.GetType().GetField("_isLoaded", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(_relatedEnd, true);
  57:         }
  58:     }
  59:  
  60:     #region ICollection<T> Members
  61:  
  62:     void ICollection<T>.Add(T item)
  63:     {
  64:         this.LoadIfNecessary();
  65:         this.ThrowIfInvalid(item);
  66:         this.collection.Add(item);
  67:     }
  68:  
  69:     void ICollection<T>.Clear()
  70:     {
  71:         this.LoadIfNecessary();
  72:         this.collection.Clear();
  73:     }
  74:  
  75:     Boolean ICollection<T>.Contains(T item)
  76:     {
  77:         this.LoadIfNecessary();
  78:         return (this.collection.Contains(item));
  79:     }
  80:  
  81:     void ICollection<T>.CopyTo(T[] array, Int32 arrayIndex)
  82:     {
  83:         this.LoadIfNecessary();
  84:         this.collection.CopyTo(array, arrayIndex);
  85:     }
  86:  
  87:     Int32 ICollection<T>.Count
  88:     {
  89:         get
  90:         {
  91:             this.LoadIfNecessary();
  92:             return (this.collection.Count);
  93:         }
  94:     }
  95:  
  96:     Boolean ICollection<T>.IsReadOnly
  97:     {
  98:         get
  99:         {
 100:             this.LoadIfNecessary();
 101:             return (this.collection.IsReadOnly);
 102:         }
 103:     }
 104:  
 105:     Boolean ICollection<T>.Remove(T item)
 106:     {
 107:         this.LoadIfNecessary();
 108:         return (this.collection.Remove(item));
 109:     }
 110:  
 111:     #endregion
 112:  
 113:     #region IEnumerable<T> Members
 114:  
 115:     IEnumerator<T> IEnumerable<T>.GetEnumerator()
 116:     {
 117:         this.LoadIfNecessary();
 118:         return (this.collection.GetEnumerator());
 119:     }
 120:  
 121:     #endregion
 122:  
 123:     #region IEnumerable Members
 124:  
 125:     IEnumerator IEnumerable.GetEnumerator()
 126:     {
 127:         return ((this as IEnumerable<T>).GetEnumerator());
 128:     }
 129:  
 130:     #endregion
 131: }

This collection receives a pointer to a possibly existing collection and a DbCollectionEntry responsible for loading this collection. We must use a bit of reflection magic to let DbCollectionEntry think that the collection was already loaded (IsLoaded), and instead load it ourselves, by applying our custom restriction to the expression returned by its Query method.

Now, in order to use this collection, we must intercept the ObjectMaterialized event of the underlying ObjectContext. We set up the filter through an extension method over DbContext:

   1: public static class DbContextExtensions
   2: {
   3:      public static void Filter<TContext, TParentEntity, TCollectionEntity>(this TContext context, Expression<Func<TContext, IDbSet<TParentEntity>>> path, Expression<Func<TParentEntity, ICollection<TCollectionEntity>>> collection, Expression<Func<TCollectionEntity, Boolean>> filter)
   4:         where TContext : DbContext
   5:         where TParentEntity : class, new()
   6:         where TCollectionEntity : class
   7:     {
   8:          (context as IObjectContextAdapter).ObjectContext.ObjectMaterialized += delegate(Object sender, ObjectMaterializedEventArgs e)
   9:         {
  10:             if (e.Entity is TParentEntity)
  11:             {
  12:                 String navigationProperty = collection.ToString().Split('.')[1];
  13:                 DbCollectionEntry col = context.Entry(e.Entity).Collection(navigationProperty);
  14:                 col.CurrentValue = new FilteredCollection<TCollectionEntity>(null, col, filter);
  15:             }
  16:         };
  17:     }
  18: }

The actual ICollection<T> is returned by setting a value to the DbCollectionEntry.CurrentValue property, and we set it to our collection

We use this extension method like this:

   1: ctx.Filter(p => p.Products, p => p.Details, p => p.SomeProperty == 0);

This will pick the Product entity from the Products context collection and filter its Details collection.

Conclusion

As you can see, even though Entity Framework does not have all functionality that we might be used to, it still offers enough extensibility points that allow us to built it ourselves. The same technique that I presented here can be used for building lazy loaded or even IQueryable<T> collections, both interesting ideas that I leave as an exercise to you!Winking smile

Querying Entity Framework Code First Inheritance

This is a short post to complement my previous one on Entity Framework Code First Inheritance: how to query for a specific class. The options are:

  1. From the DbContext collection:
       1: IEnumerable<DerivedA> derived = ctx.Bases.OfType<DerivedA>().ToList();
  2. From the inner ObjectContext, using Entity SQL and the OFTYPE operator:
       1: IEnumerable<DerivedA> derived = (ctx as IObjectContextAdapter).ObjectContext.CreateQuery<DerivedA>("SELECT VAlUE b FROM OFTYPE(Bases, MyNamespace.DerivedA) AS b").OfType<DerivedA>().ToList();
  3. Also in Entity SQL, using TREAT and IS OF:
       1: IEnumerable<DerivedA> derived = (ctx as IObjectContextAdapter).ObjectContext.CreateQuery<DerivedA>("SELECT VAlUE TREAT(b AS MyNamespace.DerivedA) FROM Bases AS b WHERE b IS OF (ConsoleApplication1.DerivedA)").OfType<DerivedA>().ToList();
  4. Using LINQ to Entities:
       1: IEnumerable<DerivedA> derived = (from d in ctx.Bases where d is DerivedA select d as DerivedA).ToList();
  5. Using pure SQL:
       1: IEnumerable<DerivedA> derived = ctx.Database.SqlQuery<DerivedA>("SELECT * FROM Bases AS b WHERE b.Discriminator = 'DerivedA'").ToList();
Visual Studio 2012 and .NET 4.5 Expert Development Cookbook Review
Visual Studio 2012 and .NET 4.5 Expert Development Cookbook

Visual Studio 2012 and .NET 4.5 Expert Development Cookbook

I recently started reading Packt Publishing’s Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. It is a book focused primarily on the new features of .NET 4.5 and Visual Studio 2012. Although some concepts already existed in previous versions (some Visual Studio IDE elements, for example), others are quit new (take Windows 8 programming APIs and the new asynchronous syntax). It follows the now classic recipes or cookbook approach, where for each category, a number of recipes are presented with a brief description of their purpose and some code to illustrate the solution. It is a very focused book, it doesn’t cover anything that shouldn’t be there.

The first chapter is about the IDE, how to use it effectively and how to extend it without using code. It walks us through creating templates and code snippets and in the process we get to know smart tags, refactoring options, UML diagrams and other nice functionality.

On second chapter, the focus is .NET application and memory management. We learn about the internal structure of a .NET assembly (actually, its various types), garbage collection and memory management and even how to disassemble it with ILMerge or Reflector. Talking about disassembling, some tips for protecting an assembly against it are also presented by means of Dotfuscator. Also includes an interesting tip on detecting memory leaks. This is the one chapter that mostly deals with pre-.NET 4.5 concepts.

Next comes asynchronous programming, something that most people (including myself) are looking with increased interest since the arrival of .NET 4.5. The chapter presents all programming models currently available for .NET developers and talks about some not well known thread synchronization objects and techniques of the .NET world, including guidelines on choosing the appropriate mechanisms. Finally it covers the new async and await pattern.

Following is a chapter on the new enhancements to ASP.NET, which go from HTML5 editor and syntax support to working with strongly-typed models in data-bound controls. In the middle, it also covers using asynchronous programming techniques in pages, modules and handlers and effectively using jQuery. There’s also a recipe on actually using some of HTML5’s new features, which is not strictly on ASP.NET, but is useful nevertheless.

WPF is next. The very popular MVVM patter is presented together with the new improvements like Ribbon support, a feature which seems to be becoming ubiquitous in Microsoft products.

The final chapters are all about Windows 8 applications. The first focuses on building touch-sensitive applications. It was a fun read, because I knew absolutely nothing on the subject. It actually covers more than just touch-sensitive applications, and covers WinRT, JavaScript and XAML.

The last chapter talks about the various options for communicating and sharing contained within Windows 8. Also a very interesting one, of which I knew nothing about. It covers the ways by which we can share data between Windows 8 applications, writing notification services in WCF and displaying notifications in tiles or toasts.

It was a very pleasant read, I am sure to return to it very often, for some of the topics are very wide.

Entity Framework Code First Inheritance

Introduction

Another post for self reference, this time, how to map inheritance strategies with Entity Framework Code First.

Single Table Inheritance / Table Per Class Hierarchy

First, the default strategy: one table for all classes in the hierarchy. Will store all columns on the same table, so all properties on derived classes must be nullable, and there will be lots of nulls. An additional column will be created, which will contain a discriminator value for deciding which type corresponds to each row.

   1: [Table("Base")]
   2: public abstract class Base
   3: {
   4:     public Int32 BaseId { get; set; }
   5:  
   6:     public String InheritedColumn { get; set; }
   7: }

 

   1: public class DerivedA : Base
   2: {
   3:     public String A { get; set; }
   4: }

 

   1: public class DerivedB : Base
   2: {
   3:     public String B { get; set; }
   4: }

 

image

 

Class Table Inheritance / Table Per Type

This will map all properties of the base class into a table of its own and each derived class in its own table, connected to the base table by a foreign key. No duplication will occur and properties on derived classes can be mapped as not nullable.

   1: [Table("Base")]
   2: public abstract class Base
   3: {
   4:     public Int32 BaseId { get; set; }
   5:  
   6:     public String InheritedColumn { get; set; }
   7: }

 

   1: [Table("DerivedA")]
   2: public class DerivedA : Base
   3: {
   4:     public String ColumnA { get; set; }
   5: }

 

   1: [Table("DerivedB")]
   2: public class DerivedB : Base
   3: {
   4:     public String ColumnB { get; set; }
   5: }

 

image

 

Concrete Table Inheritance / Table Per Concrete Type

No table for the base class, each concrete class will have its own table, which will contain columns for all of the class’ properties, including inherited ones. One record will only exist in one of the tables, so usage of IDENTITY columns as primary keys is not possible, because there will be records with the same ID on all of the tables, unless different seeds and/or increments are used.

   1: public abstract class Base
   2: {
   3:     public Int32 BaseId { get; set; }
   4:  
   5:     public String InheritedColumn { get; set; }
   6: }

 

   1: [Table("DerivedA")]
   2: public class DerivedA : Base
   3: {
   4:     public String ColumnA { get; set; }
   5: }

 

   1: [Table("DerivedB")]
   2: public class DerivedB : Base
   3: {
   4:     public String ColumnB { get; set; }
   5: }

This will require additional configuration at the context level, this strategy is not possible just with attributes:

   1: public class Context : DbContext
   2: {
   3:     protected override void OnModelCreating(DbModelBuilder modelBuilder)
   4:     {
   5:         modelBuilder.Entity<DerivedA>().Map(m =>
   6:         {
   7:             m.MapInheritedProperties();
   8:         });
   9:         modelBuilder.Entity<DerivedB>().Map(m =>
  10:         {
  11:             m.MapInheritedProperties();
  12:         });
  13:     }
  14:  
  15:     public DbSet<Base> Bases { get; set; }
  16: }

 

image

Entity Framework Code First Relations

Introduction

This post is more for self-reference than anything else. Basically, I tend to forget some options for mapping relations with Entity Framework Code First, so I wrote this. If in doing so it helps someone, even better! Winking smile

One-to-Many

First, the most basic: one-to-many/many-to-one: an instance of the Master class has lots of Details.

   1: public class Master
   2: {
   3:     public Int32 MasterId { get; set; }
   4:  
   5:     public virtual ICollection<Detail> Details { get; protected set; }
   6: }

 

   1: public class Detail
   2: {
   3:     public Int32 DetailId { get; set; }
   4:  
   5:     public virtual Master Master { get; set; }
   6: }

image

One-to-One

The stepchild of database relations. Sometimes it is useful, though: a single Master has an optional Detail, which always refers to an existing Master.

   1: public class Master
   2: {
   3:     public Int32 MasterId { get; set; }
   4:  
   5:     public virtual Detail Detail { get; set; }
   6: }

 

   1: public class Detail
   2: {
   3:     [Key]
   4:     [ForeignKey("Master")]
   5:     public Int32 MasterId { get; set; }
   6:  
   7:     [Required]
   8:     public virtual Master Master { get; set; }
   9: }

image

Many-to-Many

A single Master can have many Details; each Detail can itself be connected to multiple Masters.

   1: public class Master
   2: {
   3:     public Master()
   4:     {
   5:         this.Details = new List<Detail>();
   6:     }
   7:  
   8:     public Int32 MasterId { get; set; }
   9:  
  10:     public virtual ICollection<Detail> Details { get; protected set; }
  11: }

 

   1: public class Detail
   2: {
   3:     public Detail()
   4:     {
   5:         this.Masters = new List<Master>();
   6:     }
   7:  
   8:     public Int32 DetailId { get; set; }
   9:  
  10:     public virtual ICollection<Master> Masters { get; protected set; }
  11: }

image

One-to-Many With Composite Key

In this case we have a composite primary key constituted by a foreign key and a scalar column: a Master instance is related with many Details and each Detail is identified by both a single Master and a timestamp.

   1: public class Master
   2: {
   3:     public Master()
   4:     {
   5:         this.Details = new List<Detail>();
   6:     }
   7:  
   8:     public Int32 MasterId { get; set; }
   9:  
  10:     public virtual ICollection<Detail> Details { get; protected set; }
  11: }

 

   1: public class Detail
   2: {
   3:     [Key]
   4:     [ForeignKey("Master")]
   5:     [Column(Order = 0)]
   6:     public Int32 MasterId { get; set; }
   7:  
   8:     [Required]
   9:     public virtual Master Master { get; set; }
  10:  
  11:     [Key]
  12:     [Column(Order = 1)]
  13:     public DateTime Timestamp { get; set; }
  14: }

image

Have I forgotten something? Let me know!

Unity – Part 3: Aspect Oriented Programming

AOP

This is my third post on Unity. See the first here for an introduction and the second here for how to apply dependency injection.

Aspect Oriented Programming (AOP) is a technique for applying cross-cutting concerns to existing implementations, without modifying them. Some examples of it are:

  • Wrapping method calls that go to the database in transactions automatically;
  • Logging all calls to some method, including the input parameters and return value;
  • Catching exceptions thrown in a method automatically and doing something with them.

AOP is supported in the Enterprise Library (of which Unity is part) by the Policy Injection application block, and it can be integrated with Unity. You must install this application block, perhaps by using NuGet:

image

We need to add the interception behavior – which is the one that actually applies aspects – to Unity, either by code:

   1: unity.AddNewExtension<Interception>();

Or by XML configuration:

   1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
   2:     <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
   3: </unity>

Having said that, the first concept we need to know is that of an interceptor. An interceptor in the Policy Injection block is an implementation of Microsoft.Practices.Unity.InterceptionExtension.IInterceptor interface, and there are three implementations:

It is required that, when you are going to apply an aspect to a registration, you choose an interceptor suitable for that registration, based on what type we are registering.

An aspect itself is an implementation of Microsoft.Practices.Unity.InterceptionExtension.ICallHandler, Unity includes five out of the box such handlers:

The ICallHandler interface only defines a single method, Invoke, which wraps a method’s arguments and allows having code run before, after or even instead of the target method, and an Order property, for specifying the order by which the aspect should be applied, in case there are many.

A simple call handler, for outputting some string before or after a method call, might be:

   1: public class OutputCallHandler : ICallHandler
   2: {
   3:     public Boolean Before
   4:     {
   5:         get;
   6:         set;
   7:     }
   8:  
   9:     public Boolean After
  10:     {
  11:         get;
  12:         set;
  13:     }
  14:  
  15:     public String Message
  16:     {
  17:         get;
  18:         set;
  19:     }
  20:  
  21:     Int32 ICallHandler.Order
  22:     {
  23:         get;
  24:         set;
  25:     }
  26:  
  27:     IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
  28:     {
  29:         if (this.Before == true)
  30:         {
  31:             Console.WriteLine(this.Message);
  32:         }
  33:  
  34:         IMethodReturn result = getNext()(input, getNext);
  35:  
  36:         if (result.Exception != null)
  37:         {
  38:             Console.Error.WriteLine(result.Exception.Message);
  39:         }
  40:         else
  41:         {
  42:             if (this.After == true)
  43:             {
  44:                 Console.WriteLine(this.Message);
  45:             }
  46:         }
  47:  
  48:         return (result);
  49:     }
  50: }

Another option is to have interception for all methods of the target registration, which can be achieved by implementing Microsoft.Practices.Unity.InterceptionExtension.IInterceptionBehavior in a concrete class, such as this:

   1: public class MyInterceptionBehavior : IInterceptionBehavior
   2: {
   3:     IEnumerable<Type> IInterceptionBehavior.GetRequiredInterfaces()
   4:     {
   5:         return (Type.EmptyTypes);
   6:     }
   7:  
   8:     IMethodReturn IInterceptionBehavior.Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
   9:     {
  10:         //before target method call
  11:  
  12:         if (input.MethodBase == typeof(MyService).GetMethod("DoSomething"))
  13:         {
  14:             //do something
  15:         }
  16:  
  17:         IMethodReturn methodReturn = getNext().Invoke(input, getNext);
  18:  
  19:         //after target method call
  20:  
  21:         return (methodReturn);
  22:     }
  23:  
  24:     Boolean IInterceptionBehavior.WillExecute
  25:     {
  26:         get
  27:         {
  28:             return (true);
  29:         }
  30:     }
  31: }

If we want to cancel the default method call, if it is non void, we must return an appropriate value:

   1: IMethodReturn methodReturn = input.CreateMethodReturn(someValue, input.Arguments);

Or if we want to return an exception:

   1: IMethodReturn methodReturn = input.CreateExceptionMethodReturn(new SomeException());

There are three ways by which we can apply an aspect to a registration:

  • By applying an attribute to a method on the declaring or target type;
  • By code configuration;
  • By XML configuration.

Interception By Attributes

We need to create an attribute that derives from Microsoft.Practices.Unity.InterceptionExtension.HandlerAttribute and which instantiates our call handler:

   1: [Serializable]
   2: [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
   3: public sealed class OutputCallHandlerAttribute : HandlerAttribute
   4: {
   5:     public Boolean Before
   6:     {
   7:         get;
   8:         set;
   9:     }
  10:  
  11:     public Boolean After
  12:     {
  13:         get;
  14:         set;
  15:     }
  16:  
  17:     public String Message
  18:     {
  19:         get;
  20:         private set;
  21:     }
  22:  
  23:     public OutputCallHandlerAttribute(String message)
  24:     {
  25:         this.Message = message;
  26:     }
  27:  
  28:     public override ICallHandler CreateHandler(IUnityContainer container)
  29:     {
  30:         return (new OutputCallHandler() { After = this.After, Before = this.Before, Message = this.Message });
  31:     }        
  32: }

And we apply it to any method declaration:

   1: public interface IMyService
   2: {
   3:     [OutputCallHandler("Before", Before = true)]
   4:     [OutputCallHandler("After", After = true)]
   5:     void DoSomething();
   6: }

But before this works, we need to tell Unity to use interface interception for our type:

   1: unity.Configure<Interception>().SetDefaultInterceptorFor<IMyService>(new InterfaceInterceptor());

Interception By Code

For intercepting by code, whenever we register something with Unity, we also tell it to use interface interception and to include a behavior instance – it is not possible to specify a call handler for a specific method:

   1: unity.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager(), new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<OutputInterceptionBehavior>());

Interception By Configuration

When applying interception by configuration we also cannot target a specific method, but instead specify an interception behavior, which will apply to all method – of course, inside of it we can do our own filtering, by looking at the IMethodInvocation.MethodBase property:

   1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
   2:     <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
   3:     <container>
   4:         <extension type="Microsoft.Practices.Unity.InterceptionExtension.Interception, Microsoft.Practices.Unity.Interception"/>
   5:         <interceptors>
   6:             <interceptor type="InterfaceInterceptor">
   7:                 <default type="MyNamespace.IMyService, MyAssembly"/>
   8:             </interceptor>
   9:         </interceptors>
  10:         <register type="MyNamespace.IMyService, MyAssembly" mapTo="MyNamespace.MyService, MyAssembly">
  11:             <lifetime type="singleton"/>
  12:             <interceptionBehavior type="MyNamespace.OutputInterceptionBehavior, MyAssembly"/>
  13:         </register>
  14:         </register>
  15:     </container>
  16: </unity>

Executing

You must Unity to retrieve an instance, which will be properly wrapped in a proxy, and from there all of your configured interceptors will be called:

   1: IMyService svc = ServiceLocator.Current.GetInstance<IMyService>();
   2: svc.DoSomething();

Next in line: extending Unity.

More Posts Next page »