Register Login

 

Welcome to the Coach Factor blog. Here you will find all of our ideas on software development. Subscribe at  http://blog.nventive.net.

# Thursday, January 01, 2009

The founders of nVentive, Erik Renaud and Francois Tanguay have both been awarded a MVP award. It is an honor to be recognized by Microsoft in this way and nVentive will continue to implicate itself in the community, following it's mission to perform coaching and guidance for agile software development using .net technologies.

Thursday, January 01, 2009 11:25:06 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | Announcement
# Thursday, December 18, 2008

nVentive's Erik Renaud will be speaking at the January 28th @Lunch meeting on the subject of Dependency Inversion using Unity.

Thursday, December 18, 2008 10:55:58 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net - Microsoft PnP | Announcement
# Thursday, November 27, 2008

Part 1 and part 2 of this series were devoted to Unity, and part 3 introduced interception. Let’s examine Unity’s interception mechanism in more details.

Let’s look at the GetContainer method once again:

    1             public IUnityContainer GetContainer()

    2             {

    3                 IUnityContainer container = new UnityContainer();

    4                 container.AddNewExtension<Interception>();

    5 

    6                 //define how to intercept

    7                 container.Configure<Interception>()

    8                     .SetDefaultInterceptorFor<AccountingService>(new VirtualMethodInterceptor());

    9 

   10                 //create policy

   11                 container.Configure<Interception>()

   12                     .AddPolicy("SecurityPolicy")

   13                     .AddMatchingRule(new TypeMatchingRule(typeof(AccountingService)))

   14                     .AddCallHandler<SecurityCallHandler>();

   15 

   16                 return container;

   17             }

From this code, you can see a few concepts being introduced.

The first is the configuration of an interceptor, which defines how interception is to be made for the specified class. In this case, we are using the VirtualMethodInterceptor which creates a new class, on the fly, which derives from the AccountingService and overrides anything virtual as place holders for executing the policies (more on policies later).

The current interceptors are:

  1. VirtualMethodInterceptor, which can intercept virtual calls by deriving a a class from the intercepted class.
  2. InterfaceInterceptor, which can intercept any call on a given a interface, by creating a class that implements the specified interface and decorates the concrete type.
  3. TransparentProxyInterceptor, which can intercept anything deriving from MarshalByRefObject or an interface and reuses the .net technology for remoting. Out of the three, this is the slowest interceptor but also the one that is the most flexible.

The other part of configuring is the creation of a policy. A policy is basically something that has a name (RuleDrivenPolicy), knows how to identify things it needs to intercept (IMatchingRule) and calls handlers (ICallHandler).

Out of the box, Unity comes with many matching rules but no call handlers. If you are using Enteprise Libary’s PIAB, you will find that PIAB implements may call handlers for invoking the security, logging, exception management…

The following code will get you on your way to creating your own call handlers:

    1         public class SampleCallHandler : ICallHandler

    2         {

    3             #region ICallHandler Members

    4 

    5             public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)

    6             {

    7                 //before next CallHandler or Target Method

    8                 IMethodReturn result = getNext.Invoke().Invoke(input, getNext);

    9                 //after previous CallHandler or Target Method

   10 

   11                 return result;

   12             }

   13 

   14             public int Order

   15             {

   16                 get { return 0; }

   17                 set { }

   18             }

   19 

   20             #endregion

   21         }

Note that there is always a AttributeDrivenPolicy present in the container, which uses attributes for matching rules and call handlers. All you have to do is create attributes that derive from HandlerAttribute and off you go.

In part 2, we saw the we could also configure the container through xml configuration files. The same is true for interception and GetContainer would look like this:

    1             public IUnityContainer GetContainer()

    2             {

    3                 IUnityContainer container = new UnityContainer();

    4 

    5                 UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

    6                 section.Containers.Default.Configure(container);

    7 

    8                 return container;

    9             }

The exact same syntax as for configuring Unity, isn’t that great ! The backing XML though is another thing, here is an example:

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <configuration>

    3     <configSections>

    4         <section

    5             name="unity"

    6             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

    7     </configSections>

    8     <unity>

    9         <containers>

   10             <container>

   11                 <types>

   12                     <type type="Demo1.AccountingService,TestAssembly"/>

   13                 </types>

   14                 <extensions>

   15                     <add type="Microsoft.Practices.Unity.InterceptionExtension.Interception, Microsoft.Practices.Unity.Interception" />

   16                 </extensions>

   17                 <extensionConfig>

   18                     <add name="interception" type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationElement, Microsoft.Practices.Unity.Interception.Configuration">

   19                         <interceptors>

   20                             <interceptor

   21                                 type="transparentProxy">

   22                                 <default

   23                                     type="Demo1.AccountingService,TestAssembly"/>

   24                             </interceptor>

   25                         </interceptors>

   26                         <policies>

   27                             <policy name="SecurityPolicy">

   28                                 <matchingRules>

   29                                     <matchingRule

   30                                         name="matchingRule"

   31                                         type="AlwaysMatchingRule"/>

   32                                 </matchingRules>

   33                                 <callHandlers>

   34                                     <callHandler

   35                                         name="callHandler"

   36                                         type="SampleCallHandler"/>

   37                                 </callHandlers>

   38                             </policy>

   39                         </policies>

   40                     </add>

   41                 </extensionConfig>

   42             </container>

   43         </containers>

   44     </unity>

   45 </configuration>

Now how’s that for XML !!!

We hope that these posts will reassure you and help you integrate Unity into your software. Unity is quite powerful and we have only touched the surface. Feel free to write to use to get more information.

Thursday, November 27, 2008 11:41:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | .net - Microsoft PnP | Architecture
# Wednesday, November 26, 2008

After presenting at Microsoft TechDays the “BlackBelt WPF DataBinding Session”, we received a very interesting question from one of the attendees:

If there are validation rules associated to a binding declared in XAML and validation fails due to invalid data, the value in the target (“onscreen value”) will not be in sync with the value in the source (your business object).

In the end, the folllowing screen shot shows what we want :

image

  1. The ErrorTemplate is active, because a validation error occured;
  2. The tooltip shows the range of valid values and the invalid value that was entered;
  3. The textbox shows the currently binded value, and not the actual invalid value that the user entered.

By default, the text box would show the invalid value, and would be out of sync with the binded object.

This is what we came up with to change that default behavior: when the validator fails, invoke the binding mechanism as to update the target (onscreen value) with the current value in the source (business object).

Here is the recipe:

  1. Implement INotifyPropertyChanged on your business object.
  2. Create the IRaiseNotifyPropertyChanged:

        1     public interface IRaiseNotifyPropertyChanged

        2     {

        3         void Raise(string PropertyName);

        4     }

  3. Implement IRaiseNotifyPropertyChanged on your business object as follows:

        1         public void Raise(string PropertyName)

        2         {

        3             if (PropertyChanged != null)

        4             {

        5                 PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));

        6             }

        7         }

  4. Add these two properties to the class that implements your validation rule (derives from ValidationRule):

        1         public string PropertyName { get; set; }

        2         public object Target { get; set; }

  5. Modify the Validate method like this:

        1             if ((age < Min) || (age > Max))

        2             {

        3                 if (Target is IRaiseNotifyPropertyChanged)

        4                 {

        5                     IRaiseNotifyPropertyChanged t = Target as IRaiseNotifyPropertyChanged;

        6                     t.Raise(PropertyName);

        7                 }

        8 

        9                 return new ValidationResult(false,

       10                   "Please enter an age in the range: " + Min + " - " + Max + ". You entered : " + value.ToString());

       11             }

       12             else

       13             {

       14                 return ValidationResult.ValidResult;

       15             }

  6. Use the validation rule like this in your XAML:
    <c:agerangerule target="{Binding}" propertyname="Age" max="130" min="21">

We hope that this will be useful in your WPF adventures !

Wednesday, November 26, 2008 10:37:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net - WPF

In part 1 and part 2, we briefly explored what was Unity. In this part, we’ll introduce the subject of interception.

In releases prior to 4.1 of Enterprise Library, interception was something provided by the “Policy Injection Application Block”. One of the big moves for 4.1 was to refactor the functionality into Unity, and modify PIAB to be a facade (easier to use interface) over Unity.

But the question remains, what is interception. Interception relates to a programming technique called AOP (Aspect Oriented Programming) and deals with things that are mostly non-functional (logging, exception handling, security, caching…). This said, you would use interception to perform security checks (for example) in a transparent way while calling a target method on a target object.

    1         public class AccountingService

    2         {

    3             public virtual void Deposit(decimal amount)

    4             { }

    5         }

    6 

    7         public class FormController

    8         {

    9             public void DoSomething()

   10             {

   11                 IUnityContainer container = GetContainer();

   12 

   13                 var accountingService = container.Resolve<AccountingService>();

   14 

   15                 accountingService.Deposit(50.0m);

   16             }

   17         }

From this example, you see that we are resolving the AccountingService class through the container, and then calling the Deposit method. Let’s see how we implemented GetContainer() to account for interception.

    1         public IUnityContainer GetContainer()

    2         {

    3             IUnityContainer container = new UnityContainer();

    4             container.AddNewExtension<Interception>();

    5 

    6             //define how to intercept

    7             container.Configure<Interception>()

    8                 .SetDefaultInterceptorFor<AccountingService>(new VirtualMethodInterceptor());

    9 

   10             //create policy

   11             container.Configure<Interception>()

   12                 .AddPolicy("SecurityPolicy")

   13                 .AddMatchingRule(new TypeMatchingRule(typeof(AccountingService)))

   14                 .AddCallHandler<SecurityCallHandler>();

   15 

   16             return container;

   17         }

From this example, you cann see that we are asking Unity to intercept AccountService types using the VirutalMethodInterceptor, and to define a policy, that will be applied to types of type AccountingService who will invoke the SecurityCallHandler. The SecurityCallHandler is defined as such:

    1         public class SecurityCallHandler : ICallHandler

    2         {

    3             #region ICallHandler Members

    4 

    5             public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)

    6             {

    7                 throw new InvalidOperationException("You can't do that.");

    8                 //return getNext.Invoke().Invoke(input, getNext);

    9             }

   10 

   11             public int Order

   12             {

   13                 get { return 0; }

   14                 set { }

   15             }

   16 

   17             #endregion

   18         }

The call handler is what performs you non-functional code. This is where you would put your logging, validation, security, caching code, which would transparently wrap the object being intercepted.

More on the possibilities in part 4.

Wednesday, November 26, 2008 6:17:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | .net - Microsoft PnP | Architecture
# Tuesday, November 25, 2008

In part 1, we explored that basic functionality that Unity has to offer. In this post, we’ll explore a few more things in order to make Unity truly usable.

Back to dependency injection, we saw in part 1 that Unity will call the constructor with valid arguments. This is called constructor injection. There are two other types of injections, namely property and method that are resolved at creation time. Here are the examples.

Property injection:

    1         public interface IDatabaseContext { }

    2 

    3         public class DatabaseContext : IDatabaseContext { }

    4 

    5         public class AccountingService

    6         {

    7             [Dependency]

    8             public IDatabaseContext DBContext { get; set; }

    9         }

And method injection:

    1         public interface IDatabaseContext { }

    2 

    3         public class DatabaseContext : IDatabaseContext { }

    4 

    5         public class AccountingService

    6         {

    7             public IDatabaseContext DBContext { get; set; }

    8 

    9             [InjectionMethod]

   10            public void SetDatabaseContext(IDatabaseContext dbContext)

   11             {

   12                 this.DBContext = DBContext;

   13             }

   14         }

Of course, since a class can have more than one constructors, sometimes we need to help Unity by explicitly saying which one to use. Here is an example:

    1 

    2         public interface IDatabaseContext { }

    3 

    4         public class DatabaseContext : IDatabaseContext { }

    5 

    6         public class AccountingService

    7         {

    8             public IDatabaseContext DBContext { get; set; }

    9 

   10             public AccountingService()

   11             { }

   12 

   13             [InjectionConstructor]

   14             public AccountingService(IDatabaseContext dbContext)

   15             {

   16                 this.DBContext = dbContext;

   17             }

   18         }

Now for the other point that we’d like to cover: configuration. Unity’s approach to configuration is quite different that the one employed in Enterprise Library. API support is included in Unity’s core library and support for externalizing the configuration to XML configuration files is provided by the “Microsoft.Practices.Unity.Configuration.dll” assembly (and let’s not forget the “System.Configuration.dll” assembly). The technique used simply reuses the configuration API, which opens the door to home grown configuration plugins (i.e. from a database).

These are the things that you can configure in Unity:

  1. How to perform dependency injection (without the usage of attributes);
  2. The mapping of interfaces to their concrete classes;
  3. “Named resolves”, or the ability to ask the container to resolve something which is explicitly named;
  4. Lifetime managers, or how to control the lifetime of objects created by the container (The singleton pattern could be implemented by configuring the container with ContainerControlledLifetimeManager);
  5. Support for resolving arrays;
  6. And more…

Here is an example on how to consume external configuration:

    1             public IUnityContainer GetContainer()

    2             {

    3                 IUnityContainer container = new UnityContainer();

    4 

    5                 UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

    6                 section.Containers.Default.Configure(container);

    7 

    8                 return container;

    9             }

Of course, this will assume that a configuration section named “unity” exists in your application configuration file, that should look like this:

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <configuration>

    3     <configSections>

    4         <section

    5             name="unity"

    6             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

    7     </configSections>

    8 

    9     <unity>

   10         <containers>

   11             <container>

   12                 <types>

   13                     <type

   14                         type="Demo1.IDatabaseContext,TestAssembly"

   15                         mapTo="Demo1.DatabaseContext,TestAssembly"/>

   16                 </types>

   17             </container>

   18         </containers>

   19     </unity>

   20 </configuration>

These posts are not meant to explore every single feature present in Unity, but rather to get your started on the core concepts. Unity ships with plenty of documentation that will allow you to grasp what else can be done.

Coming up, part 3, which will introduce the subject of interception.

Tuesday, November 25, 2008 5:49:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | .net - Microsoft PnP | Architecture
Search
Archive
<January 2009>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567
Statistics
Total Posts: 47
This Year: 0
This Month: 0
This Week: 0
Comments: 2
Sign In