Policy Injection with Performance Counter Handler

Apr 7, 2011 at 5:20 PM

I am trying to work through an example of using the Performance Conuter Handler with Policy Injection under Unity 2.0, but I am not getting anywhere.

I might be missing something basic as this is one of my first attempts with Policy Injection and Unity. I know that I have things working in general because I have logging working, but something is missing when I try to add the performance counter handler.

I've followed the instructions in the docs as best as possible but it seems like these docs might not be 100% accurate.

First I installed the performance counters by doing:

installutil.exe /category=PolicyInjection Microsoft.Practices.EnterpriseLibrary.PolicyInjection.dll

This is where I see the first problem with the docs. It shows that you should do:

installutil.exe /category=<category>[;<category> ...] Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.dll

But the assembly Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.dll does not exist.

The call as I run it does seem to work, because when I open PerfMon.exe, and try to add counters, I see "PolicyInjection" as a category with the counters "# calls / second" under it. If I select on one of those counters, there are no instances of the selected object (it says <No Instances>).

Thinking that maybe this doesn't matter, I attempt tp add all the counters. The Added Conuters section of the screen seems to indicate that I have added the counters, but Nothing seems to happen after I click OK. These counters don't show up in the monitoring graph.

Next I thought that maybe they won't show up until I actually use them, so I moved over to a test console app which uses policy injection. Here's my config:

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

    <alias alias="IMyInterface" type="UnityPolicyInjectionDemo.IMyInterface, UnityPolicyInjectionDemo"/>
    <alias alias="MyClass" type="UnityPolicyInjectionDemo.MyClass, UnityPolicyInjectionDemo"/>

    <namespace name="Microsoft.Practices.EnterpriseLibrary.Logging.PolicyInjection" />
    <assembly name="Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0" />
    <assembly name="Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0" />

    <container name="containerOne">
      <extension type="Interception" />

      <register type="IMyInterface" mapTo="MyClass">
        <policyInjection />
        <interceptor type="InterfaceInterceptor" />
      </register>

      <interception>
        <policy name="demoPolicy">
          <matchingRule type="NamespaceMatchingRule" name="Namespace Matching Rule">
            <constructor>
              <param name="namespaceName" value="UnityPolicyInjectionDemo" />
            </constructor>
          </matchingRule>

          <callHandler type="LogCallHandler" name="logging handler">
            <constructor>
              <!-- removed details for clarity...logging handler works fine -->
            </constructor>
          </callHandler>

          <callHandler type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.PerformanceCounterCallHandler, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0" name="perf counter handler">
            <constructor>
              <param name="category" value="PolicyInjection" />
              <param name="counterInstanceName" value="Default" />
            </constructor>
          </callHandler>
        </policy>

      </interception>

    </container>
   
  </unity>

 Note my constructor for the perforamnce counter handler. The category PolicyInjection is the same that I passed into InstallUtil. The second parameter counterInstanceName is where things get fuzzy. The documentation says it should be:

String. The name of the instance of the target performance counter. Can include the tokens {method}, {type}, {namespace}, {assembly}, and {appdomain}.

But then there really aren't any examples of exactly what this means. What is the target performance counter? If you look right below the handler constructor param descriptions, there is an example of how to add a performance counter handler:

myContainer.Configure<Interception>()
           .AddPolicy("MyPolicy")
               .AddMatchingRule<TypeMatchingRule>(new InjectionConstructor("My.Order.Object", true))
               .AddCallHandler<PerformanceCounterCallHandler>
                ("MyValidator",
                new ContainerControlledLifetimeManager());

While I am using configuration to set up my container, I was hoping that this might shed some light on what I should be doing since there aren't any examples of setting things up using config. Unfortunately it seems like this example was cut and pasted from the docs for the Validation Handler, not the Performance Conuter Handler.

I searched the forums and it doesn't seem like anyone is running into the same problems that I am, although there seems to be a little more guidance for previous version of EntLib. Unfortunately, previous versions used PIAB, and now things are rolled into Unity, so I am not sure what I am doing wrong.

I've tried several different things for counterInstanceName, but nothing seems to have an effect. I run my sample code and my log gets written to (by the logging handler) but nothing shows up in PerfMon.

Can anyone point me to better documentation, or can anyone tell me what I'm doing wrong? I am running Win7, 64bit. I ran InstallUtil as admin (actually tried admin and non admin), and nothing seems to be working.

Thanks,

Dan Griffin

 

 

 

 

 

Apr 8, 2011 at 4:10 AM
Edited Apr 8, 2011 at 9:51 AM

The instance name is just any name to distinguish a specific performance counter.  For example you have defined multiple performance counter handlers in your config, you would assign each of them a different instance name so you'll be able to identify which is assigned to intercept specific method(s). 

In the performance monitor, when you click on the PolicyInjection counter it will display the name of the instance in the list of Instances of selected object when you run the application and then you will be able to add it.

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Apr 8, 2011 at 9:16 PM

So it would be expected for the instances to be "<No Instances>" in PerfMon intially and then as I continue to use the performance counter handler in my code I will see instances start to show up in PerfMon based on what ever I enter as an instance name in my Unity config?

So in the above example I should be seeing "Default" showing up in PerfMon?

 

Apr 8, 2011 at 9:24 PM

Just to follow up...If my last post is the expected behavior, then something still is not working for me. I ran my code several times and then tried to add counters, and they still showed up as having "<No Instances>"

 

Apr 11, 2011 at 3:33 AM

Yes, it should show up assuming you have correctly installed it (using installutil.exe) and created an application which uses that performance counter.  By the way, did you load the container from the configuration?  Try as well to place a breakpoint in the method you are intercepting with the performancecounterhandler and check then the Performance Monitor if the instance will appear under the PolicyInjection counte.r

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Apr 11, 2011 at 2:23 PM

Aha! Adding the breakpoint in the code being intercepted did the trick. When I did this and then went into PerfMon and added the PolicyInjection category, it showed all the expected counters.

It's strange that I would need to do this though. I don't have much experience with performance counters, but I expected to be able to run my code a few times (without breakpoints) and have the instances show up in perfmon.

This concerns me when it comes to getting this worknig on a production machine, but then I guess that I would have alot more instances getting intercepted and I might just catch them in PerfMon to get things set up correctly.

Thanks for your help!

 

Apr 24, 2011 at 6:06 PM

Hi Dan, Hi Sarah,

I have found this post and it looks similar to the problem I am facing with Policy Injection. I have followed whole the above discussion but I didn't get nothing.

My project consists of a simple console application. Unity and PI are all in the app.config.

At first run, I have got a lot of errors and I have fixed all of them. 

The first question in my mind is: how can we assure that Unity and PI are running through the app.config? By using the perfmon.exe? I have opened it up and in the Counters list I have found 'PolicyInjection'. All the instances are disabled !! Something is still missing on my installation or what?

Do I still need to write down codes on my project in addition to my configuration file knowing that I do not want to touch my code as I thought that the app.config file is totally completed. I have spent a bit of time to make following the msdn documentations.

I would really appreciate it if you could clarify my understanding by answering to my questions. And I would be so glad if you could describe the main steps which leads to a working PI.

Many thanks for reading my post :)

Edra..

Apr 25, 2011 at 6:50 AM

Please find the source:

////*******************Main****************////////////

using System;
using System.Configuration;
using System.Collections;
using System.Configuration.Install;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Installers;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Raouf.Unity.Test
{
    public class Class1
    {
        
        static void Main(string[] args)   
        {
            //InstallCounters();
            IUnityContainer container = new UnityContainer();
            var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Containers["containerTest"].Configure(container);

            IMyInterface myInterface = container.Resolve("IMyInterface");

            myInterface.MethodToImplement();
        }
        //public static void InstallCounters()
        //{
        //    var installer = new PerformanceCountersInstaller(new SystemConfigurationSource());
        //    IDictionary state = new System.Collections.Hashtable();
        //    installer.Context = new InstallContext();
        //    installer.Context.Parameters.Add("Category", "PolicyInjection");
        //    installer.Install(state);
        //    installer.Commit(state);
        //    Console.WriteLine("Performance counters have been successfully installed.");
        //    Console.ReadLine();
        //} 
    }
} 
////*************IMyInterface.cs*******************//////
namespace Raouf.Unity.Test
{
    interface IMyInterface
    {
        void MethodToImplement();
    } 
}

///*****************InterfaceImplementer.cs********************////

using System;

namespace Raouf.Unity.Test
{
class InterfaceImplementer : IMyInterface
{
    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

}

///******************App.Config******************////////////

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
   </configSections>
  
   <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension,                       
                      Microsoft.Practices.Unity.Interception.Configuration" />
    <!--Conuter Handler with Policy Injection under Unity 2.0-->
    <namespace name="Raouf.Unity.Test"/>
    <alias alias="IMyInterface" type="Raouf.Unity.Test.IMyInterface, Raouf.Unity.Test"/>
    <alias alias="InterfaceImplementer" type="Raouf.Unity.Test.InterfaceImplementer, Raouf.Unity.Test"/>

    <assembly name="Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0" />

    <container name="containerTest">
      <extension type="Interception" />

      <register type="IMyInterface" mapTo="InterfaceImplementer">
        <interceptor type="InterfaceInterceptor" />
        <policyInjection />
      </register>

      <interception>

        <policy name="policyTest">

          <matchingRule type="NamespaceMatchingRule" name="Namespace Matching Rule">
            <constructor>
              <param name="namespaceName" value="Raouf.Unity.Test" />
            </constructor>
          </matchingRule>

          <callHandler type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.PerformanceCounterCallHandler,
                       Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0" name="perf counter handler">
            <constructor>
              <param name="category" value="PolicyInjection" />
              <!--<param name="counterInstanceName" value="Raouf" />-->
              <param name="instanceName" value="Raouf" />
              <param name="useTotalCounter" value="true" />
              <param name="incrementNumberOfCalls" value="true" />
              <param name="incrementCallsPerSecond" value="true" />
              <param name="incrementAverageCallDuration" value="true" />
              <param name="incrementTotalExceptions" value="true" />
              <param name="incrementExceptionsPerSecond" value="true" />
              <!--<param name="handlerOrder" value="true" />-->
            </constructor>
          </callHandler>

        </policy>

      </interception>

    </container>

  </unity>
</configuration>

 

 
Apr 25, 2011 at 7:44 AM

Hi,

I guess you need to add Performance Counter Handler to a policy using the Unity interception mechanism as shown in the example above:

myContainer.Configure<Interception>()
           .AddPolicy("MyPolicy")
               .AddMatchingRule<TypeMatchingRule>(new InjectionConstructor("My.Order.Object", true))
               .AddCallHandler<PerformanceCounterCallHandler>
                ("MyValidator",
                new ContainerControlledLifetimeManager());

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Apr 25, 2011 at 9:20 AM

Hi Noel,

Thank your for your response.

I think I have added this code in my App.config as:

<container name="containerTest">
      <extension type="Interception" />

      <register type="IMyInterface" mapTo="InterfaceImplementer">
        <interceptor type="InterfaceInterceptor" />
        <policyInjection />
      </register>

      <interception>

        <policy name="policyTest">

          <matchingRule type="NamespaceMatchingRule" name="Namespace Matching Rule">
            <constructor>
              <param name="namespaceName" value="Raouf.Unity.Test" />
            </constructor>
          </matchingRule>

          <callHandler type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.PerformanceCounterCallHandler,
                       Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0" name="perf counter handler">
            <constructor>
              <param name="category" value="PolicyInjection" />
              <!--<param name="counterInstanceName" value="Raouf" />-->
              <param name="instanceName" value="Raouf" />
              <param name="useTotalCounter" value="true" />
              <param name="incrementNumberOfCalls" value="true" />
              <param name="incrementCallsPerSecond" value="true" />
              <param name="incrementAverageCallDuration" value="true" />
              <param name="incrementTotalExceptions" value="true" />
              <param name="incrementExceptionsPerSecond" value="true" />
              <!--<param name="handlerOrder" value="true" />-->
            </constructor>
          </callHandler>

        </policy>

      </interception>

    </container>

Apr 25, 2011 at 4:15 PM

Hi Edra,

I haven't tested your exact code, but it looks very similar to my working code. The part that made the difference for me was to run the code in the debugger and put a breakpoint in MethodToImplement(). When you hit that breakpoint, go over to perfmon (start up a new instance) and add counters from the PolicyInjection category. Since there are some "live" instances of these counters, you should see something under the instances combobox.

I think that the trick is that you have to catch the instances while they are running in order to track them in perfmon. In a production system when you have many MethodToImplement() flying all over the place, perfmon should be able to see them and add counters to them.

I hope this helps!

Dan

Apr 25, 2011 at 6:50 PM

Hi Dan,

I have tried with the breakpoint but it seems that there is something still missing in my code perhaps.

Could you please let me know how can I get the results output of the performance? I have tried with Logging Call Handler, my code is compiling and running without errors but I didn't get any result or a generated *.log file in which I should find some statistics.

Hope you do have an idea in how to get these statistics :)

Apr 25, 2011 at 7:47 PM

I'm not sure if this is your problem or not, but I think that you need to add the entlib extension. In your main program add,

container.AddNewExtension<EnterpriseLibraryCoreExtension>();

where EnterpriseLibraryCoreExtension is in entlib.commmon assembly