Manage trees with entity framework part II

Manage Tree With Entity Framework – The basic

One of the most obvious problem showed in previous post is the need to issue a single Select for each node to rebuild the tree, but the good thing is that there are a lot of solutions over there to solve this problem. One of the most interesting technique was developed by Joe Celko, first of all I added two field to the table, one field is named hierarchyLevel and the other is named fullpath, then I setup a couple of triggers.

Both triggers manages these two columns, the first fire on insert

ALTER TRIGGER [dbo].[trg_EmployeeInsert] ON [dbo].[Employee] FOR INSERT AS BEGIN DECLARE @numrows int SET @numrows = @@ROWCOUNT if @numrows > 1 BEGIN RAISERROR('Only single row insertion is supported', 16, 1) ROLLBACK TRAN END ELSE BEGIN UPDATE E SET hierarchyLevel = CASE WHEN E.parentId IS NULL THEN 0 ELSE Parent.hierarchyLevel + 1 END, fullPath = CASE WHEN E.parentId IS NULL THEN '.' ELSE Parent.fullPath END + CAST( AS varchar(10)) + '.' FROM Employee AS E INNER JOIN inserted AS I ON = LEFT OUTER JOIN Employee AS Parent ON = E.parentId END END

It is really simple, for each node that I insert into the table it simply finds the parent and updates hierarchylevel and fullpath accordingly. The other trigger updates a whole subtree during an update of the parentId property

ALTER TRIGGER [dbo].[trg_EmployeeUpdate] ON [dbo].[Employee] FOR UPDATE AS BEGIN IF @@ROWCOUNT = 0 RETURN if UPDATE(parentid) BEGIN UPDATE E SET hierarchyLevel = E.hierarchyLevel - I.hierarchyLevel + CASE WHEN I.parentId IS NULL THEN 0 ELSE Parent.hierarchyLevel + 1 END, fullPath = ISNULL(Parent.fullPath, '.') + CAST( as varchar(10)) + '.' + RIGHT(E.fullPath, len(E.fullPath) - len(I.fullPath)) FROM Employee AS E INNER JOIN inserted AS I ON E.fullPath LIKE I.fullPath + '%' LEFT OUTER JOIN Employee AS Parent ON I.parentId = END END

Et voilà, with this simple solution you will solve a lot of problems, first of all these two extra fields are completely transparent to the application because all the work is made by the two triggers, the next step is to update the model, and finally modify the two extra properties to have private setter, to avoid update to the additional columns.

With this new structure here is the code to load the whole subtree from a node.

Employee root = context.Employee.Where(e => e.Parent == null).First(); IList<Employee> childs = context.Employee .Where(e => e.fullPath.StartsWith(root.fullPath)) .OrderBy(e => e.fullPath) .ToList(); foreach (Employee child in childs) { Console.WriteLine("{0}{1}", new String('-', child.hierarchyLevel.Value), child.Name); } Console.WriteLine("print tree recursively."); PrintNoLoad(root, 0);

Thansk to the fullPath property each descendant of a given node can be find simply with the condition fullPath.StartsWith(root.fullPath) and the beautiful thing is that you need only a single SELECT to find all descendant nodes ;). To make things more interesting, Entity Framework resolves all references for you, this means that the whole tree structure is reconstructed in memory, you can verify this with the PrintNoLoad function that print the whole subtree recursively.

public static void PrintNoLoad(Employee employee, Int32 level) { Console.WriteLine("{0}{1}", new String('-', level), employee.Name); foreach (Employee child in employee.Childs) { PrintNoLoad(child, level + 1); } }

This function differs from the old Print routine because it does not check the employee.Childs.IsLoaded condition because it is evaluated to False even if the childs are already loaded. This happens because EF had not explicitly loaded all the childs for tree nodes. We are sure that all descendants are loaded because of the fullpath column, but EF could not know it, so it consider the collection "not loaded" and if you check it you still ends with the N select. As you can verify in the following image, the IsLoaded property is false, but the collection of childs contains all the elements. We are sure that this node contains only 2 nodes because we loaded all nodes whose fullpath starts with the root path, so we did not miss any node.


Thus if you use the fullpath trick, be sure not to explicitly load again references. To make everything clearer you can create a method LoadSubtree with partial class to shield the user from a deep knowledge of the fullpath structure.

public partial class Employee { public void LoadSubtree(TestEntities context) { context.Employee .Where(e => e.fullPath.StartsWith(this.fullPath)) .ToList(); } ... using (TestEntities context = new TestEntities()) { Employee root = context.Employee.Where(e => e.Parent == null).First(); root.LoadSubtree(context); PrintNoLoad(root, 0);

Now you can simply call LoadSubtree to issue only one select that will load all descendants of a node :D. Update of nodes is a breeze thanks to the trigger, if you run this code

Employee daniele = context.Employee.Where(e => e.Name == "Daniele").First(); Employee guardian = context.Employee.Where(e => e.Name == "Guardian").First(); daniele.Parent = guardian; context.SaveChanges();

you will obtain this output if you the tree before and after the update

Original Tree Alkampfer -Guardian --Peppe --Giuseppe -Daniele --Fabio Tree after update Alkampfer -Guardian --Daniele ---Fabio --Peppe --Giuseppe


As you can see, moving Daniele under the Guardian node correctly moved the whole subtree, the hierarchyLevel and the fullpath are correct thanks to the trigger.

You can also find the root with this method.

public Employee GetRoot(TestEntities context) { String rootId = fullPath.Substring(1, fullPath.IndexOf('.', 1) - 1); return context.LoadByKey<Employee>(Int32.Parse(rootId)); }

It consists of a single query ;) and immediately find the root without the need to traverse the tree. You can also find all nodes that are sons of the same father.

public List<Employee> GetSiblings(TestEntities context) { String parentPath = fullPath.Substring(0, fullPath.LastIndexOf('.', fullPath.Length - 2)); return context.Employee .Where(e => e.fullPath.StartsWith(parentPath) && e.hierarchyLevel == hierarchyLevel) .ToList(); }

Each operation consists of only one query, and if you put an index on the fullpath column you can expect high speed tree operation ;).



Unity and AOP in enterprise library

Part 1 – Basic of IoC unity container
Part 2 – Basic of resolving dependencies and configure objects.
Part 3 – AOP with Policy Injection Application Block
Part 4 – Custom Handler to use with Policy Injection Application Block
Part 5 – Combine policy Injection Application Block with Unity

In last post I showed how Policy Injection Application Block is now only a tiny wrapper around Unity. So Unity is the enterprise library section that does both AOP and Dependency Injection, this make me a little bit confused :) so I decided to forget about PIAB, just to avoid confusion.

To use AOP with unity without PIAB one of the possible solution is using custom attributes, suppose you write an handler called MyLogHandler, you can just create this attribute.

public class MyLogHandlerAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new MyLogHandler(); } }

This one is a particular attribute because it inherit from HandlerAttribute and it needs only to override the CreateHandler method and returns an instance of the handler you want to use. You can apply this attribute to every class or method you want to intercept, if you apply it to a class every method will be intercepted, if you apply it to a single method you will intercept only that method. Here is an example.

[MyLogHandler] interface ILogger { void Log(String message); }

This is not enough to make interception happens, Unity should be instructed that you want the ILogger interface to be intercepted and you must also specify the type of interception.

container.Configure<Interception>().SetDefaultInterceptorFor<ILogger>(new TransparentProxyInterceptor());

You can call SetDefaultInterceptorFor or simply SetInterceptorFor; the first one tells unity container to apply interception every time that a specific type is resolved: when the user calls Resolve<T> or when the type is resolved for some dependency. In the example , this means that when you resolve TestB class, since is has a dependency to ILogger, the Ilogger object that will get resolved will be intercepted. (this is the configuration section for the TestB object)


When unity resolve the object named OtherTest it resolves also the dependency to the ILogger interface and creates the SuperLogger, but since I asked to set a default interceptor for the ILogger interface it gets intercepted and wrapped.


If you change the code and call SetInterceptorFor instead of SetDefaultInterceptorFor, the situation is different.


As you can verify the logger variable contains a transparent proxy because it gets resolved directly, the Logger property of the TestB object is not intercepted because it is resolved for a dependency. Keep in mind this distinction because it is one of the most important in the unity interception structure.

I do not like the code+attributes approach to AOP, because if I need to intercept some other methods I need to modify code and recompile, in a AOP world I want to use only configuration files to specify everything, let’s see how to do it. First of all I set up some alias to make the configuration more readable

<typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" /> <typeAlias alias="transparentProxy" type="Microsoft.Practices.Unity.InterceptionExtension.TransparentProxyInterceptor, Microsoft.Practices.Unity.Interception" /> <typeAlias alias="typeMatchingRule" type="Microsoft.Practices.Unity.InterceptionExtension.TypeMatchingRule, Microsoft.Practices.Unity.Interception"/>

These aliases permits me to use shorter name in the config. Here is the first part of the config


Container configuration has an extension node that permits to add extensions, then you add the corresponding extensionConfig to configure specific extension you’ve added. For interceptors you add a series of <interceptor> node. Each interceptor node must have a type attribute that specify the type of interceptor to use, then you must add a series of <key> or <default> nodes to specify the types to intercept. Each <key> elements will call the SetInterceptorFor, each <default> element calls a SetDefaultConfigurationFor.

Now that interception is configured you need to specify types or methods that should be intercepted, this is done with the Policy element. Each policy element is composed by a series of matching rules that are used to identify methods to be intercepted and a list of handlers to use, here is an example.


Unity gives you some basic matching rules, in this example I’ve used a typeMatchingRule (look to the aliases section to verify the exact type). This class permits you to specify a Name of a class that will be intercepted. To specify the name of the class in code you must pass a string to the constructor of the matching rule, in configuration file you can obtain the same result with an <injection> node.

The resulting config file is really verbose, and I must admit that is not so readable, compare it with code configuration

container.Configure<Interception>() .SetDefaultInterceptorFor<ILogger>(new TransparentProxyInterceptor()) .AddPolicy("LogMethod") .AddMatchingRule(new TypeMatchingRule("ILogger")) .AddCallHandler(typeof(MyLogHandler));

Configuration API for Unity permits you to use a simple fluent syntax to configure interception, this kind of configuration is more readable, more manteniable and less error prone. To set interception I needs only five lines, the XML file is really longer an more complex. If you want to use interception in your project, you could configure everything in code and accept to recompile when the configuration change or you can use dynamic compilation to configure container at runtime using code files.

Code for the example can be found here.



Combine Policy Injection Application Block with Unity

Part 1 – Basic of IoC unity container
Part 2 – Basic of resolving dependencies and configure objects.
Part 3 – AOP with Policy Injection Application Block
Part 4 – Custom Handler to use with Policy Injection Application Block

In previous parts I showed how to configure unity container and how to create a custom handler for policy injection application block, now it is time to speak about integration between PIAB and Unity container.

First of all you should read this thread that deal about this issue, and you can get disappointed to know that the integration is not so tight. The problem is that PIAB is now superseded by unity, it does means that you does not need to use PIAB to do AOP but you can use directly unity container.

If you look at the source of PIAB you can see something interesting, If you follow the Wrap method of PIAB you find this function

private object DoWrap(object instance, Type typeToReturn) { container.Configure<Interception>().SetDefaultInterceptorFor(typeToReturn, injector); return container.BuildUp(typeToReturn, instance); }

the variable container is a IUnityContainer, this means that the real work is done by Unity and PIAB is now just a way to access AOP functionality of Unity in different way. Let’s see how you can make this two interact. This is the Class Diagram of a TestB class


As you can see it implements the ITest interface and internally uses an ILogger object. The Logger property is defined in this way.

[Dependency] public ILogger Logger { get; set; }

Now when you resolve the ITest interface with unity container how can you make unity do AOP for the property Logger of class TestB? Remember that PIAB works calling explicitly PolicyInjection.Wrap() method on a target object, but the ILogger object that will be assigned to Logger property of TestB class gets automatically resolved by unity container. The question is "How can you make the unity container aware of policies defined for PIAB". The solution was explained in this thread.

If you configure the PIAB to intercept the interface ILogger you gets disappointed because when you resolve TestB with unity, Logger property does not contains a proxy, but the concrete class defined in the config file. This means that calls to ILogger methods are not intercepted because unity ignore configuration of the PIAB. To solve this problem you should use the following code.

1 //Gets the PIAB configuration part 2 IConfigurationSource configSource = ConfigurationSourceFactory.Create(); 3 PolicyInjectionSettings settings = (PolicyInjectionSettings)configSource.GetSection(PolicyInjectionSettings.SectionName); 4 5 // Apply PIAB settings, if any, to the container 6 if (settings != null) 7 { 8 settings.ConfigureContainer(container, configSource); 9 } 10 container.Configure<Interception>().SetInterceptorFor((typeof(ILogger)), new TransparentProxyInterceptor());

In line 2 you use the ConfigurationSourceFactory class of enterprise library to load the actual configuration, then in line 3 you gets the section that relates to PIAB. If a setting is present you can use its ConfigureContainer() method to apply PIAB configuration to the unity container. Now the container is aware of the policies defined for PIAB. This is not enough, because you need to explicitly tells unity to set interception for the ILogger interface, and you should also specify the type of interception, in this situation the TransparentProxyInterceptor().

Now unity is aware of the PIAB configuration and know that it should intercept the ILogger interface. Let’s see what is happening when you resolve the object.


As you can see the Logger property gets assigned a TransparentProxy, et voilà.

Since PIAB is using a container to do its works, it is not clear why it is still a separated block in the enterprise library. Since all the AOP functionalities are exposed by the Unity block it seem superfluous to keep the PIAB alive, because now PIAB seems to me just a different way to configure a unity container, and does not deserve a complete block on its own in Enteprise library.



Custom Handler to use with Policy Injection Application Block

Previous Posts:

Part 1 – Basic of IoC unity container
Part 2 – Basic of resolving dependencies and configure objects.
Part 3 – AOP with Policy Injection Application Block

In this fourth part I’ll examine how to build a simple custom handler that will be used with Policy Injection Application Block. The purpose of the handler is simply dumping to console the name of the called method as well all the parameters with theirs values. Here is the class.

[ConfigurationElementType(typeof(CustomCallHandlerData))] public class MyLogHandler : ICallHandler { public MyLogHandler(NameValueCollection parameters) { this.parameters = parameters; } private NameValueCollection parameters; public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // return input.CreateMethodReturn(null); Console.WriteLine("intercepted call to: {0}", input.MethodBase.Name); Console.WriteLine("Parameters:"); for (int I = 0; I < input.Arguments.Count; I++) { Console.WriteLine("{0}: {1}", input.Arguments.ParameterName(I), input.Arguments[I]); } Console.WriteLine("Call original function"); IMethodReturn retvalue = getNext()(input, getNext); return retvalue; } }

Code is really simple, the only interesting method is the Invoke() that gets called instead of the original method of the wrapped object. This method has two parameters, the first contains all the informations on the method invocation, like: name and value of all parameters; the second parameter is a delegate used to get the next handler delegate in the AOP chain. This is needed because you can add more than one handler to a single method, so you will end up with a chain of interceptors.

Now we need to configure PIAB to insert this handler wherever we need it


I want to set a matching rule for an entire type (red), this type of matching rule has only one property called matches (Green) that will accepts a list of types to intercept, in this example I ask to add handlers only to the ITest interface (blue)


I need to specify a custom handler (red) as handler type, then configure the exact type in the type property of the handler (blue) the Order property can be left to 0 (automatic). You can use the order property to manually define the order in witch the handlers will be called.

Now I can simply fire this code

ITest test1 = container.Resolve<ITest>("OtherTest"); ITest wrapped = Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjection.Wrap<ITest>(test1); Console.WriteLine(wrapped.DoAnotherThing("TEST", 6)); Console.WriteLine(wrapped.DoSomething(2));

And gets this output.

intercepted call to: DoAnotherThing Parameters: test: TEST parami: 6 Call original function Prop = VAL Names = 2 intercepted call to: DoSomething Parameters: param: 2 Call original function SUPER:DoSomething Called 1

From the output you can notice that each invocation of methods belonging to ITest, will result in a call to our custom handler.

Inside an handler you really have great control on what to do, you are not only limited to passive operation like inspecting parameters but you can actively modify the behavior of the function. Let’s show how to swallow all exceptions, and logging them to the console.

IMethodReturn retvalue = getNext()(input, getNext); if (retvalue.Exception != null) { Console.WriteLine("Exception: {0}", retvalue.Exception); retvalue.Exception = null; } return retvalue;

With this code the handler first verify if the invocation of the function have raised an exception, if yes it simply dumps the exception message to the console and clear the exception. Now if you add a throw statement in DoAnotherThing function the output will be:

intercepted call to: DoAnotherThing Parameters: test: TEST parami: 6 Call original function Exception: System.Exception: TEST at PolicyInjection.TestB.DoAnotherThing(String test, Int32 parami) in C:\Deve lop\SvnGianMaria\CodeCommon\trunk\Experiment\PolicyInjection\PolicyInjection\Tes tB.cs:line 21 intercepted call to: DoSomething Parameters: param: 2 Call original function SUPER:DoSomething Called

As you can see the execution of the program was not stopped by the exception and the exception is dumped to the console.

In PIAB there is already a handler called Exception Handling Handler that is integrated with Exception Handling Application Block, and is a good starting point in defining centralized rules to handle the exception of applications. But if you need some custom logic you can write your own.

Download code.