Monthly Archives: July 2007

Enterprise library session slides and samples

The presentation  Antonin Jelinek (webmaster of FC Bohemians and tech lead in my company) and me did in Microsoft on July 17th  (Enterprise Library a její použití v praxi) bring us a lot of fun.

I believe we did a good job in explaining real world use cases and usages in “just” 3 hours.

The slides and samples can be downloaded from Enterprise Library – Slides and Examples

The one thing I didn’t have time (and strength) to cover in the session is example of policy injection application block very simple examples. The zip file contain that example and I would just make a couple of comments here which would make understanding of those examples an easier task

Both examples cover the use case of having the page which would upon the button click retrieve current time from SessionClock helper class. Both examples would implement the PIAB caching and logging handlers.


covers the use case when our object which calls we would like to intercept inherits from MarshalByRefObj so there are no attributes decoration.

Session clock looks really simple

   1: public class SessionClock : MarshalByRefObject
   2: {
   3:     /// <summary>        
   4:     /// /// This is a method which would return current time so the presenter could        
   5:     /// /// know how much time he has more 🙂        
   6:     /// /// </summary>        
   7:     /// /// <returns>Current time</returns>        
   8:     public DateTime GetCurrentTime()
   9:     {
  10:         return DateTime.Now;
  11:     }
  12: }

Matching rule

To define matching rule: (in my example I used the Member one)


And then in property window of that Member name rule pick Matches and Add the name of method which retrieves the time GetCurrentTime (click on image to load more readable screen shoot)


With this defining of matching rules we defined that the “targets” of the policy we defines are all the types which have GetCurrentTime() method in it.


When we defined the appliance scope of policy, we have to define what that policy would contain. For this example, I pick the logging and caching handlers.

To define handlers


And to define then the handler attributes use the property window (in this example I set caching to 10 seconds)


When we set the policy scope and implementation, all we need is to create a proxy object by using factory method to wrap up our type

   1: protected void Button1_Click(object sender, EventArgs e)
   2: {
   3:     SessionClock clock = PolicyInjection.Create<SessionClock>();
   4:     CurrentTime.Text = string.Format("System  clock time: {0}", DateTime.Now);
   5:     CachedTime.Text = string.Format("Session clock time: {0}", clock.GetCurrentTime());
   6: }

And that’s it!

If we run the site and click the button we would see that the CachedTime text box would be caching output on 10 seconds and if we would check the event log we would see the method access event log entry

Timestamp: 25.7.2007 10:52:19 AM
Message: —- PIAB LOG START —
Category: General
Priority: -1
EventId: 0
Severity: Information
Title:Call Logging
Machine: NIKOLA
Application Domain: 6079b8a-1-128298341641858405
Process Id: 6832
Process Name: C:Program FilesMicrosoft Visual Studio 8Common7IDEWebDev.WebServer2.exe
Win32 Thread Id: 2812
Thread Name:
Extended Properties:

For more information, see Help and Support Center at


covers the use case of class implementing the interface and not inheriting the MarshalByRefObject, so the interception occurs on interface member implementation. This example is instead of using Matching rules using the attribute declaration approach. It also examples tagging concept.

In this example, implementation starts with interface definition (which is IMHO a great architectural and TDD practice, off course used in reasonable means)

Interface definition

   1: using System;
   2: using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
   3: using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers;
   4: using PIAB=Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers;
   6: namespace InterfaceAttributes
   7: {
   8:     public interface ISessionClock
   9:     {
  10:         /// <summary>        
  11:         /// /// This is a method which would return current time so the presenter could        
  12:         /// /// know how much time he has more 🙂        
  13:         /// /// </summary>        
  14:         /// /// <returns>Current time</returns>        
  15:         [Tag("SECURE")]
  16:         [CachingCallHandler(0, 0, 10)]
  17:         DateTime GetCurrentTime();
  18:     }
  19: }

Decorating GetCurrentTime() method interface contract with CachingCallHandlerAttribute makes the same effect like declaring it in a policy handler configuration. Second attribute is Tag(“Some_string”) which allows us to tag us desired number of type members for which we would like to have uniform policy behavior.


An example use case could be that all the methods (regardless of type, namespace etc) which are reading sensitive data (credit card etc) could be tagged with the same tag. That would allow us later to set Tag matching rule and define/alter on single place desired behavior of all those methods.

To define a tag matching rule you should do something like this:



In my example, I’ve defined a policy that all the access to members compliant with tag matching rule should be logged


That could be interpreted as:”For all the things tagged as SECURE do this logging”. Very, very powerful concept!

Factory method

The button click implementation is slightly different because now we have to inform policy injection factory method about the interface been intercepted (That is why we use Create overload with two generic parameters)

   1: protected void Button1_Click(object sender, EventArgs e)
   2: {
   3:     ISessionClock clock = PolicyInjection.Create<SessionClock, ISessionClock>();
   4:     CurrentTime.Text = string.Format("System  clock time: {0}", DateTime.Now);
   5:     CachedTime.Text = string.Format("Session clock time: {0}", clock.GetCurrentTime());
   6: }


The behavior of the application is the same. Output is cached on 10 second basis and accesses are logged in Application event log


That would be it! I hope you all enjoyed the presentation and found a lot of useful things there. 🙂


Design patterns in real world use case scenarios – Composite

Design patterns are set of best practices solutions to common problems. They are also an excellent dictionary which can enhance and speed up the communication between various team member. But they are also sometimes misused and lead to over-architected solutions.

By my opinion, every pattern usage in an application has to answer one simple questions:”What exact pain this pattern solves? ”

If that question doesn’t have a clear answer, I would challenge right there the decision for pattern usage

I already blogged about Dependency injection and service locator patterns and about Model View Presenter design pattern, but I’ll be blogging again about them and about some other patterns with some “real world” problems scenarios which could clarify what kind of problems some pattern could solve. The intention of those examples are not to be “real” “real world examples” but to be still abstracted examples which could discover you use cases when you could use some pattern

So, stay tuned

Composite pattern – persistent control tree problem

To get a very detail explanation of what this pattern stands for check out the Armen’s blog – Composite where he posted very detail article about pattern illustrated with one nice example

Problem – use case

The use case of the problem we would be solving in this example is next one:

We have a web page with fie different controls. The web page is organized in a web parts style, in the sense every control encapsulates the persistence logic inside of it.

When user clicks on a Save button of the page, page just commands to controls to persist the data without the knowledge what and how is been persisted.

The controls are named ControlA, ControlB, ControlC, ControlD and ControlE.

ControlB persistence requires that controlC and controlD would be persisted successfully first

ControlA persistence requires that ControlB and ControlE would be persisted successfully first

So, there’s a tree structure


Why composite pattern?

Composite pattern in short is a pattern where some type has a member which is a collection of the same element.

So, if I would have an Interface IPersistable with a property of IPersistable collection type and bool Persist() method


If we would take a look at our problem we would see that this interface fits problem description: a bunch of controls which can be (or not) dependable on other controls. Our interface is: something which implements an IPersistable interface with a collection of something implementing the same interface.

Rule of thumb

Usage of composite pattern is usually appropriate whenever there are hierarchical tree structures where all the tree nods are of the same type.

Problem – solution example

Class Diagram of the solution



We would first implement the IPersistable interface on a BaseControl class which would also inherit from UserControl.
BaseControl would implement the IPersistable interface by defining the ICollection<IPersistable> field and expose it through the getter property named Dependencies.
BaseControl would implement the IPersistable method Persist() by defining it as virtual method which base implementation would just iterate through the Dependencies collection and call Persist() method on each collection member.

BaseControl code example:


   1: public abstract class BaseControl : UserControl, IPersistable
   2: {
   3:     private readonly ICollection<IPersistable> _dependencies 
   4:         = new List<IPersistable>();
   6:     #region IPersistable Members
   8:     /// <summary>
   9:     /// Defines list of controls which has to be persisted 
  10:     /// successfully before this control can be persisted
  11:     /// </summary>
  12:     public ICollection<IPersistable> Dependencies
  13:     {
  14:         get { return _dependencies; }
  15:     }
  17:     /// <summary>
  18:     /// Method which would implement control peristing
  19:     /// </summary>
  20:     /// <returns></returns>
  21:     public virtual bool Persist()
  22:     {
  23:         foreach (IPersistable dependecy in _dependencies)
  24:         {
  25:             if (!dependecy.Persist())
  26:             {
  27:                 // something went wrong in saving lower leafs
  28:                 return false;
  29:             }
  30:         }
  31:         return true;
  32:     }
  34:     #endregion
  36: }

Controls implementation

Every web control would inherit from BaseControl and override its base implementation of the Perist() method.

Implementation would first call the base.Persist() which would caused the BaseControl to start iterating through the dependencies and persist them. If all the dependencies would persist successfully their state base.Perist() would return true value. Then the control itself could persist itself.

The same logic is implemented in all controls

ControlA implementation example

   1: public partial class ControlA : BaseControl
   2: {
   3:     /// <summary>
   4:     /// Persisting the control level information
   5:     /// </summary>
   6:     /// <returns></returns>
   7:     public override bool Persist()
   8:     {
   9:         bool areAllChildControlsPeristedSuccessfully = base.Persist();
  10:         if (!areAllChildControlsPeristedSuccessfully)
  11:         {
  12:             Response.Write("<br />Some of the dependent controls of ControlA failed to perist");
  13:             return false;
  14:         }
  16:         // do something specific to peristsance of this
  17:         Response.Write("<br />Save completed in ControlA");
  18:         return true;
  19:     }
  20: }

Page implementation

Now when we have defined composite behaviors of controls we have only to define the dependency structures of controls and form a composite tree. That would be done on a page level by simply setting the values of Dependencies property of every control.
(This is a setter type of dependency injection which I covered in Dependency injection and service locator patterns  and I would be covering in separate article from “real world patterns” series of articles)

Page code example

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     // defining dependencies of ControlB
   4:     ControlB1.Dependencies.Add(ControlC1);
   5:     ControlB1.Dependencies.Add(ControlD1);
   7:     // defining dependencies of ControlA
   8:     ControlA1.Dependencies.Add(ControlB1);
   9:     ControlA1.Dependencies.Add(ControlE1);
  10: }

Testing the solution

We would add a button on the page and inside of that button we would initiate persistence


protected void Button1_Click(object sender, EventArgs e)

And the result:


Problem solved!

To download source code click here: Example source code


If you are neat freak like me who likes his code to be in “perfect harmony & order” you would really like to check this open source add in to Visual Studio 2005 and 2008 which allows you to by simple right click rearrange your code according to your needs. There is a possibility of customizing your own arranging rules.

This is really a project someone from Microsoft team should take a look and incorporate it as a standard IDE feature

Watch the short video showing it in action.
Regionerate web site

Technorati tags: , ,