policy injection in asp.net using enterprise library 3.0
DESCRIPTION
Terminology and Buzzwords The Policy Injection Application Block what it does, how it works Configuring Policies Using Attributes Extending the Block custom Handlers and Matching RulesTRANSCRIPT
DaveAndAl.net
Policy Injection in ASP.NET using Enterprise Library 3.0
Alex [email protected]
http://www.daveandal.net
DaveAndAl.net
Agenda
Terminology and Buzzwords
The Policy Injection Application Block
• what it does, how it works
Configuring Policies
Using Attributes
Extending the Block
• custom Handlers and Matching Rules
DaveAndAl.net
Terminology and Buzzwords
Aspect Oriented Programming (AOP) Policy Injection Remoting Proxies Intercepting Proxies Method Interception
The overall aim is better management of Crosscutting Concerns
DaveAndAl.net
Core Concerns
What are Crosscutting Concerns?
Application
Business
Object
Business
Object
Data Access Object
Application
Business
Object
Data Access Object
Validation
Logging
Exception Handling
Caching
Authorization
Crosscutting Concerns
Performance
Counters
DaveAndAl.net
What is Policy Injection? “... techniques for creating policies that
help to manage crosscutting concerns, and applying these policies across all relevant objects and applications ...”
Using the Policy Injection Block you can:• Create handlers for each crosscutting concern• Define the conditions where they will apply• Define the behavior in specific circumstances • Adjust runtime behavior through configuration• Manage runtime behavior using Group Policy
DaveAndAl.net
The Handlers Pipeline
Objects must be “interceptable” Must use factory Create or Wrap method Each handler can execute code in the pre-
and/or post-processing stages Handlers can short-circuit (abort)
execution
DaveAndAl.net
Interceptable Object Types (1)
C#:object = PolicyInjection.Create<type>(ctor_params)object = PolicyInjection.Create<type>(IConfigurationSource,
ctor_params)
object = PolicyInjection.Wrap<type>(existing_object)object = PolicyInjection.Wrap<type>(IConfigurationSource,
existing_object)
Types that inherit MarshalByRefObject:
VB.NET:object = PolicyInjection.Create(Of type)(ctor_params)object = PolicyInjection.Create(Of type)(IConfigurationSource,
params)
object = PolicyInjection.Wrap(Of type)(existing_object)object = PolicyInjection.Wrap(Of type)(IConfigurationSource,
object)
C#
Visual Basic .NET
DaveAndAl.net
Interceptable Object Types (2)
interface = PolicyInjection.Create<type, interface>(ctor_params)interface = PolicyInjection.Create<type, interface> (IConfigurationSource, ctor_params)interface = PolicyInjection.Wrap<interface>(existing_object)interface = PolicyInjection.Wrap<interface> (IConfigurationSource, existing_object)
Types that implement a known interface:C#
interface = PolicyInjection.Create(Of type, interface)(ctor_params)interface = PolicyInjection.Create(Of type, interface) _
(IConfigurationSource, ctor_params)interface = PolicyInjection.Wrap(Of interface) (existing_object)interface = PolicyInjection.Wrap(Of interface) _
(IConfigurationSource, existing_object)
Visual Basic .NET
DaveAndAl.net
Configuring Policies Enterprise Library Configuration Console Visual Studio 2005 Configuration Editor Manually (recommended for masochists
only)
Add the PIAB to your app configuration Create the required Policies
• Each policy has one or more matching rules Must all evaluate to TRUE to select a target
• Each policy has one or more handlers Processed in the order they occur in
configuration
DaveAndAl.net
Configuring Policies Demo
DaveAndAl.net
Demo Business Object Members
Member
Attributed Customer Model
Interface Customer Model
Notes
GetCustomerList() GetCustomerName(customerID)
GetCustomerNameWithWildcard
(customerID)
Uses GetCustomerName method with a wildcard.
GetCustomerDetails(customerID)
Not defined in interface.
GetCityList(minimumCount) CityCount Property. Uses
GetCityListPublic members exposed by the two business objects
DaveAndAl.net
Demo PoliciesPolicy Name Matching Rules Call Handlers
InterfaceModelPolicy Member Name = GetCustomerNameWithWildcard or GetCustomerList
Type Name = InterfaceCustomerModel
Logging Handler with Categories = "AuditFile" and "EventLog"
Caching Handler with cache duration 20 seconds
Exception Handler with Exception Policy = "CustomerModelPolicy”
AttributeModelPolicy Method Signature, Name = * and parameter = System.String
Type Name = AttributedCustomerModel
Logging Handler with Categories = "AuditFile"
CacheByTagPolicy Tag Attribute = "ApplyTenSecondCaching"
Caching Handler with cache duration 10 seconds
The policies defined in the example application
DaveAndAl.net
Using Attributes (1) Use an attribute to apply a handler, and
optionally set properties, at design-time:
[CachingCallHandler(0, 0, 30)]public DataTable GetCustomerList(){ …}
C#
<CachingCallHandler(0, 0, 30)> _Public Sub GetCustomerList() As DataTable
…End Sub
Visual Basic .NET
DaveAndAl.net
Using Attributes (2) Use Validation attributes (from the Validation
Application Block) to validate parameters:
[ValidationCallHandler][ValidationCallHandler]public String GetCustomerName( [StringLengthValidator(3,
RangeBoundaryType.Inclusive, 5,
RangeBoundaryType.Inclusive)] String customerID)
C#
<ValidationCallHandler()> _Public Function GetCustomerName( _ <StringLengthValidator(3,
RangeBoundaryType.Inclusive, _ 5,
RangeBoundaryType.Inclusive)> _ ByVal customerID As String) As String
Visual Basic .NET
DaveAndAl.net
Using Attributes (3) Prevent configuration of any policies:
[ApplyNoPolicies]public DataTable GetCustomerList()…
C#
< ApplyNoPolicies> _Public Sub GetCustomerList() As DataTable
…
Visual Basic .NET
Other handler attributes: [AuthorizationCallHandler],
[ExceptionHandlingCallHandler],
[LoggingCallHandler],
[PerformanceCounterCallHandler]
DaveAndAl.net
Using Attributes Demo
DaveAndAl.net
Factory
Proxy
Handlers
Matching Rules
Pipeline
DaveAndAl.net
Extending the PIAB
Create a new Matching Rule• implement the IMatchingRule interface
Create a new Handler• implement the ICallHandler interface
Create a new Handler Attribute• derive from HandlerAttribute or
Attribute
DaveAndAl.net
Inside a Matching Rulepublic interface IMatchingRule{ bool Matches(MethodBase member);}
// for example… the built-in Tag Attribute Matching Rule uses:public bool Matches(MethodBase member){ foreach (TagAttribute tagAttribute in
GetAllAttributes(member, true)) { if (string.Compare(tagAttribute.Tag, tagToMatch,
ignoreCase) == 0) return true; } return false;}
DaveAndAl.net
Inside a Pipeline Handlerpublic interface ICallHandler{ IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext);}
public delegate IMethodReturn InvokeHandlerDelegate(IMethodInvocation input,
GetNextHandlerDelegate getNext);
public delegate InvokeHandlerDelegate GetNextHandlerDelegate();
Handlers must implement the Invoke method
IMethodInvocation contains method invocation or property access information (including parameters)
DaveAndAl.net
Handler Process Overviewpublic class ExampleHandler : ICallHandler{ public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { // Perform any pre-processing tasks required in the custom
handler. ... // Invoke next handler that the block should execute. This
code gets the current return message that you must pass back to the caller:
IMethodReturn msg = getNext()(input, getNext); ... // Perform any post-processing tasks required in the custom
handler. // You can modify the return message if required. // Return the message to the previous handler or the client. return msg; }
DaveAndAl.net
Messages and Short-CircuitingEach handler invokes the next one, passing the invocation message along the pipeline and the return message back again
A handler can instead simply refuse to call
the next handler, and can add information
(e.g. an exception) to the return message.
Note that previous handlers still execute
DaveAndAl.net
Short-Circuiting Executionpublic IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){ GregorianCalendar cal = new GregorianCalendar(); DayOfWeek weekDay = cal.GetDayOfWeek(DateTime.Now); if (weekDay == DayOfWeek.Saturday || weekDay ==
DayOfWeek.Sunday) { // create an Exception to return and the return message. Exception ex = new Exception("Available on weekdays only"); IMethodReturn msg = input.CreateExceptionMethodReturn(ex) return msg; } else { return getNext()(input, getNext); // invoke the next handler }
DaveAndAl.net
Custom Handler Attributes[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property |
AttributeTargets.Method)]public class CachingCallHandlerAttribute : HandlerAttribute{ private TimeSpan expirationTime;
public CachingCallHandlerAttribute(int hours, int minutes, int seconds)
{ // constructor, save the parameter values expirationTime = new TimeSpan(hours, minutes, seconds); }
public override ICallHandler CreateHandler() { // create the appropriate handler instance and return it return new CachingCallHandler(expirationTime); }}
DaveAndAl.net
References Book covering Enterprise Library:
• "Effective Use of Microsoft Enterprise Library: Building Blocks for Creating Enterprise Applications and Services" (Addison-Wesley ISBN 0-321-33421-3).
All about Enterprise Library:• http://www.codeplex.com/entlib/
Code and Slides for this session:• http://www.daveandal.net/download/
Contact: [email protected]
http://www.codeplex.com