Enterprise Library 3.0 Policy Injection Applicatoin Block

3,688 views

Published on

From the P&P website

Published in: Business, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,688
On SlideShare
0
From Embeds
0
Number of Embeds
39
Actions
Shares
0
Downloads
105
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • MGB 2003 © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
  • Enterprise Library 3.0 Policy Injection Applicatoin Block

    1. 1. Introducing the Policy Injection Application Block
    2. 2. Agenda <ul><li>Enterprise Library 3.0 Introduction </li></ul><ul><li>Policy Injection Motivation and Goals </li></ul><ul><li>Policy Injection Application Block Architecture </li></ul><ul><li>Call Handlers and Matching Rules </li></ul><ul><li>Extending the PIAB </li></ul><ul><li>Summary </li></ul>
    3. 3. Enterprise Library 3.0: New Features At a Glance <ul><li>New application blocks </li></ul><ul><ul><li>Validation Application Block </li></ul></ul><ul><ul><li>Policy Injection Application Block </li></ul></ul><ul><li>Improvements to existing application blocks </li></ul><ul><ul><li>Data Access Application Block </li></ul></ul><ul><ul><li>Logging Application Block </li></ul></ul><ul><li>.NET Framework 3.0 integration </li></ul><ul><ul><li>Logging, Exception Handling and Validation Application Blocks </li></ul></ul><ul><li>Configuration improvements </li></ul><ul><ul><li>Visual Studio-integrated configuration tool </li></ul></ul><ul><ul><li>Environmental Overrides </li></ul></ul><ul><ul><li>Manageable Configuration Source </li></ul></ul><ul><li>Automation </li></ul><ul><ul><li>Application Block Software Factory </li></ul></ul><ul><ul><li>Strong Naming Guidance Package </li></ul></ul>
    4. 4. Enterprise Library 3.0 Application Blocks Caching Security Data Access Logging Exception Handling Config Helpers & Design Instrumen- tation Object Builder Cryptography Core Policy Injection Validation
    5. 5. Agenda <ul><li>Enterprise Library 3.0 Introduction </li></ul><ul><li>Policy Injection Motivations and Goals </li></ul><ul><li>Policy Injection Application Block Architecture </li></ul><ul><li>Matching Rules and Call Handlers </li></ul><ul><li>Extending the PIAB </li></ul><ul><li>Summary </li></ul>
    6. 6. Context <ul><li>Applications include a mix of business logic and cross cutting concerns </li></ul><ul><li>Cross cutting concerns include security, state management and operational </li></ul><ul><ul><li>Authorization, logging, caching, transaction management, etc. </li></ul></ul><ul><li>Both types of logic are necessary, but each have unique characteristics </li></ul><ul><ul><li>Business logic is highly contextual and often not reusable </li></ul></ul><ul><ul><li>Cross cutting concerns are often applied consistently across layers and applications </li></ul></ul>
    7. 7. Mixing Business and Cross-Cutting Concerns <ul><li>Traditionally, business logic and cross-cutting concerns are mixed together in code </li></ul><ul><ul><li>Even if a shared component or application block is used, it is still generally called from code </li></ul></ul><ul><li>This can lead to </li></ul><ul><ul><li>Code that is hard to read and maintain </li></ul></ul><ul><ul><li>Duplicated code </li></ul></ul><ul><ul><li>Inconsistent behavior </li></ul></ul>
    8. 8. Sample Method Customer GetCustomerById(int id) { if (id < 0) throw new ArgumentException(&quot;Invalid Customer Id&quot;); Customer customer = HttpContext.Current.Cache.Get(id.ToString()) as Customer; if (customer != null) return customer; try { Database db = DatabaseFactory.CreateDatabase(&quot;CRM&quot;); using (IDataReader reader = db.ExecuteReader(&quot;spGetCustomerById&quot;, id)) { if (reader.Read()) { customer = new Customer(id, reader.GetString(0), reader.GetString(1)); HttpContext.Current.Cache.Add(id.ToString(), customer, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); return customer; } } return null; } catch (Exception ex) { if (ExceptionPolicy.HandleException(ex, &quot;Data Policy&quot;)) throw; return null; } }
    9. 9. Policy Injection Application Block Goals <ul><li>Separate cross-cutting concerns from business logic </li></ul><ul><ul><li>Use interception and injection to apply policies at runtime </li></ul></ul><ul><li>Allow policies to be defined declaratively, using configuration or attributes </li></ul><ul><ul><li>At a coarse- or fine-grained level </li></ul></ul><ul><li>Make it easy to integrate Enterprise Library application blocks into policies </li></ul><ul><ul><li>Validation, Logging, Authorization, Exception Handling, Caching, Performance Counters </li></ul></ul><ul><li>Design for loose-coupling and extensibility </li></ul>
    10. 10. Sample Method with Policy Injection [ValidationCallHandler] [CachingCallHandler(0, 1, 0)] [Tag(&quot;Data Access&quot;)] Customer GetCustomerById( [RangeValidator(0, RangeBoundaryType.Inclusive, 0, RangeBoundaryType.Ignore)] int id) { Database db = DatabaseFactory.CreateDatabase(&quot;CRM&quot;); using (IDataReader reader = db.ExecuteReader(&quot;spGetCustomerById&quot;, id)) { if (reader.Read()) { return new Customer(id, reader.GetString(0), reader.GetString(1)); } } }
    11. 11. Agenda <ul><li>Enterprise Library 3.0 Introduction </li></ul><ul><li>Policy Injection Motivation and Goals </li></ul><ul><li>Policy Injection Application Block Architecture </li></ul><ul><li>Call Handlers and Matching Rules </li></ul><ul><li>Extending the PIAB </li></ul><ul><li>Summary </li></ul>
    12. 12. Policy Injection Application Block Basics <ul><li>Policy Injection Application Block provides a factory for creating or wrapping policy-enabled objects </li></ul><ul><li>If policies are defined in attributes or configuration, a proxy is returned in lieu of the real object </li></ul><ul><li>When calling policy-enabled members, a handler pipeline is executed before and after the real member is called </li></ul><ul><li>Each handler can access the data going in and out of the call </li></ul>
    13. 13. Policy Injection Application Block Basics <ul><li>Normally, each handler will implement a cross-cutting concern before passing control to the next handler (or the target) </li></ul><ul><li>A handler may also choose to abort the pipeline if deemed appropriate </li></ul>
    14. 14. Policies <ul><li>The definition of which handlers should execute for which objects and methods is called a policy </li></ul><ul><li>There are two types of polices: </li></ul><ul><ul><li>Configuration-based policies </li></ul></ul><ul><ul><li>Attribute-based policies </li></ul></ul>
    15. 15. Configuration-based Policies <ul><li>A configuration-based policy consists of </li></ul><ul><ul><li>A set of matching rules </li></ul></ul><ul><ul><li>A pipeline of handlers </li></ul></ul><ul><li>Matching rules are predicates that specify which members the policy should apply to </li></ul><ul><ul><li>For example, everything in the GlobalBank.BusinessLogic namespace, or all members returning a BankAccount </li></ul></ul><ul><ul><li>Multiple matching rules are ANDed together </li></ul></ul><ul><li>The handler pipeline specifies the ordered list of handlers that will execute if the matching rules pass </li></ul><ul><li>More than one policy may apply to any given member </li></ul><ul><ul><li>They will be applied in the order specified in configuration </li></ul></ul>
    16. 16. Attribute-based Policies <ul><li>An attribute-based policy consists of a set of call handlers applied directly to objects and members using custom attributes </li></ul><ul><ul><li>Matching rules are not used </li></ul></ul><ul><li>Attributes are discovered first on types, then on members, and applied in order of discovery </li></ul><ul><ul><li>Order of discovery of multiple attributes applied on the same element cannot be guaranteed </li></ul></ul><ul><li>Attribute-based policies are always applied before configuration-based policies </li></ul>[CachingCallHandler(0, 1, 0)] [LogCallHandler(LogBeforeCall = true, LogAfterCall = false, BeforeMessage = &quot;About to call the method&quot;)] public int DoSomething(string input) { /// }
    17. 17. Disabling Policies <ul><li>Both configuration- and attribute-based policies can be disabled for a given type or member </li></ul><ul><li>Use the [ApplyNoPolicies] attribute to prevent policies being applied </li></ul><ul><li>Useful for methods that are performance critical, need no cross-cutting concerns or implement concerns differently </li></ul>
    18. 18. Interception and Injection <ul><li>In order for policies to execute when a method is called: </li></ul><ul><ul><li>Configuration- or attribute-based policies must apply to the member </li></ul></ul><ul><ul><li>The instance must be created or wrapped using the PolicyInjection factory </li></ul></ul><ul><ul><li>The target object must be interceptable </li></ul></ul><ul><ul><ul><li>Requirements depend on the chosen injection mechanism </li></ul></ul></ul><ul><ul><li>Method must be called via the proxy returned from the PolicyInjection.Create/Wrap methods, not directly on the object </li></ul></ul>
    19. 19. Creating or wrapping objects <ul><li>Objects must be created or wrapped with the PolicyInjection class for policies to apply </li></ul><ul><li>Even if no policies apply now, you may want to create objects this way to allow policies to be added in the future </li></ul><ul><ul><li>Performance impact is very low if no policies apply </li></ul></ul>MyClass1 object1 = PolicyInjection.Create<MyClass>(); MyClass2 object2 = PolicyInjection.Create<MyClass>(param1, param2); IMyInterface object3 = PolicyInjection.Create<MyClass3, IMyInterface>(); MyClass1 object4 = new MyClass(); MyClass1 object4proxy = PolicyInjection.Wrap<MyClass1>(object4); IMyInterface object5 = new MyClass3(); IMyInterface object5proxy = PolicyInjection.Wrap<IMyInterface>(object5);
    20. 20. Interception Requirements <ul><li>The requirements for intercepting objects and members depends on the chosen injection strategy </li></ul><ul><li>The PIAB ships with a Remoting Proxy injection strategy </li></ul><ul><ul><li>Can be replaced by alternative methods </li></ul></ul><ul><li>The Remoting Proxy Injection requires: </li></ul><ul><ul><li>The class derive from MarshalByRefObject , or </li></ul></ul><ul><ul><li>The class implement any interface, with intercepted calls made through that interface </li></ul></ul>
    21. 21. Calling Policy Injected Members <ul><li>Calling policy injected members is no different to calling any other member </li></ul><ul><ul><li>The caller can’t even tell if policies exist or not </li></ul></ul><ul><li>Policies do not alter the method signature </li></ul><ul><ul><li>Although they may alter the behavior </li></ul></ul><ul><li>Caller just calls a method and gets a return result or exception </li></ul><ul><ul><li>Caller doesn’t know if result came from the method or a handler </li></ul></ul>BankAccount account = PolicyInjection.Create<BankAccount>(accountId); try { account.Withdraw(amount); } catch (Exception ex) { // do something }
    22. 22. Agenda <ul><li>Enterprise Library 3.0 Introduction </li></ul><ul><li>Policy Injection Motivations and Goals </li></ul><ul><li>Policy Injection Application Block Architecture </li></ul><ul><li>Call Handlers and Matching Rules </li></ul><ul><li>Extending the PIAB </li></ul><ul><li>Summary </li></ul>
    23. 23. Supplied Handlers <ul><li>PIAB ships with six handlers </li></ul><ul><ul><li>Validation Handler </li></ul></ul><ul><ul><li>Logging Handler </li></ul></ul><ul><ul><li>Authorization Handler </li></ul></ul><ul><ul><li>Exception Handling Handler </li></ul></ul><ul><ul><li>Caching Handler </li></ul></ul><ul><ul><li>Performance Counter Handler </li></ul></ul><ul><li>Most are shims over other Enterprise Library application blocks </li></ul>
    24. 24. Validation Handler <ul><li>Validates parameters to a method, using the Validation Application Block </li></ul><ul><li>Validation rules can be defined </li></ul><ul><ul><li>As rule sets defined on parameter types, using either attributes or configuration </li></ul></ul><ul><ul><li>By applying validation attributes directly on the method parameters </li></ul></ul><ul><li>If validation fails, an ArgumentValidationException is thrown, and the method is not called </li></ul><ul><ul><li>Exception contains the ValidationResults from the validation call </li></ul></ul>
    25. 25. Logging Handler <ul><li>Writes a log entry before and/or after the method is called, using the Logging Application Block </li></ul><ul><li>Uses a TraceLogEntry which contains additional properties related to the method call </li></ul><ul><li>Handler may be configured to log additional data, including: </li></ul><ul><ul><li>Call Stack </li></ul></ul><ul><ul><li>Parameter Values </li></ul></ul><ul><ul><li>Return Value or Exception </li></ul></ul><ul><ul><li>Call execution time </li></ul></ul><ul><li>Log Categories are configurable and may include tokens such as {method} and {type} </li></ul>
    26. 26. Authorization Handler <ul><li>Uses a Security Application Block Authorization Provider to determine if the current user is authorized to perform an operation </li></ul><ul><li>Current user is determined from the thread principal </li></ul><ul><li>Handler is configured with </li></ul><ul><ul><li>The name of the Authorization Provider instance to use </li></ul></ul><ul><ul><li>The name of the Operation, which can include tokens such as {type} and {method} </li></ul></ul><ul><li>If authorization fails, an UnauthorizedAccessException is thrown, and the method is not called </li></ul>
    27. 27. Exception Handling Handler <ul><li>Executes after a method is called </li></ul><ul><li>Processes any exceptions thrown by the method using the Exception Handling Application Block </li></ul><ul><li>Handler is configured with the name of the Exception Policy to use </li></ul><ul><li>After processing, the handler will throw either the original or the new exception back to the caller, based on the exception policy definition </li></ul><ul><li>Exceptions may only be swallowed for void methods </li></ul>
    28. 28. Caching Handler <ul><li>Uses the S ystem.Web.Cache to cache method return values, keyed off the method signature and input parameters </li></ul><ul><ul><li>Keys are generated using GetHashCode </li></ul></ul><ul><li>Handler is configured with a TimeSpan indicating how long return values should be cached </li></ul><ul><li>Before the method is called, the handler checks if a value is in the cache for the set of inputs </li></ul><ul><ul><li>If so, the cached return value is returned, instead of calling the method. </li></ul></ul><ul><ul><li>If not, the method is called and the return value is cached for future use </li></ul></ul>
    29. 29. Performance Counter Handler <ul><li>Increments a number of performance counters that provide useful metrics around use and performance </li></ul><ul><li>Handler can be configured to specify which counters and instances to use </li></ul><ul><li>Available counters include </li></ul><ul><ul><li>Total number of times the method is called </li></ul></ul><ul><ul><li>Rate of calls (per second) </li></ul></ul><ul><ul><li>Average call duration </li></ul></ul><ul><ul><li>Number of exceptions thrown </li></ul></ul><ul><ul><li>Rate of exceptions thrown (per second) </li></ul></ul>
    30. 30. Supplied Matching Rules <ul><li>PIAB includes a number of matching rules that test members against static metadata: </li></ul><ul><ul><li>Assembly Matching Rule </li></ul></ul><ul><ul><li>Custom Attribute Matching Rule </li></ul></ul><ul><ul><li>Member Name Matching Rule </li></ul></ul><ul><ul><li>Method Signature Matching Rule </li></ul></ul><ul><ul><li>Namespace Matching Rule </li></ul></ul><ul><ul><li>Parameter Type Matching Rule </li></ul></ul><ul><ul><li>Property Matching Rule </li></ul></ul><ul><ul><li>Return Type Matching Rule </li></ul></ul><ul><ul><li>Tag Attribute Matching Rule </li></ul></ul><ul><ul><li>Type Matching Rule </li></ul></ul>
    31. 31. Effective Policy Viewer <ul><li>While the PIAB offers many benefits, separating business code from cross cutting concerns can also create confusion </li></ul><ul><ul><li>Complete behavior cannot be determined only by looking at code </li></ul></ul><ul><li>To take away the mystery, p&p provides the Effective Policy Viewer </li></ul><ul><li>This application shows which policies and handlers (configuration and attribute-based) will apply to which members in which order </li></ul><ul><li>Tool can be downloaded from http://codeplex.com/entlib </li></ul>
    32. 32. Agenda <ul><li>Enterprise Library 3.0 Introduction </li></ul><ul><li>Policy Injection Goals </li></ul><ul><li>Policy Injection Application Block Architecture </li></ul><ul><li>Call Handlers and Matching Rules </li></ul><ul><li>Extending the PIAB </li></ul><ul><li>Summary </li></ul>
    33. 33. Extensibility points <ul><li>The Policy Injection Application Block is designed to be extended </li></ul><ul><li>Defined extensibility points are: </li></ul><ul><ul><li>Matching Rules </li></ul></ul><ul><ul><li>Handlers </li></ul></ul><ul><ul><li>Injectors </li></ul></ul><ul><li>Other changes are possible by modifying source code </li></ul>
    34. 34. Building Custom Matching Rules <ul><li>Build a new class implementing IMatchingRule </li></ul><ul><li>Create necessary constructors and fields for configurable properties </li></ul><ul><li>Implement Matches </li></ul><ul><ul><li>bool Matches(MethodBase member) </li></ul></ul><ul><li>Build a runtime configuration class, if you want strongly-typed configuration, or use CustomMatchingRuleData </li></ul><ul><li>Add the ConfigurationElementType attribute to the class, pointing to the runtime configuration class </li></ul>
    35. 35. Building Custom Handlers <ul><li>Build a new class implementing ICallHandler </li></ul><ul><li>Create necessary constructors and fields for configurable properties </li></ul><ul><li>Implement Invoke </li></ul><ul><ul><li>IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) </li></ul></ul><ul><ul><li>Perform any pre-processing </li></ul></ul><ul><ul><li>Call the next handler using getNext().Invoke(input, getNext); </li></ul></ul><ul><ul><li>Perform any post-processing </li></ul></ul><ul><ul><li>Return the desired return value or exception </li></ul></ul><ul><li>Build a runtime configuration class, if you want strongly-typed configuration, or use CustomCallHandlerData </li></ul><ul><li>Add the ConfigurationElementType attribute to the class, pointing to the runtime configuration class </li></ul>
    36. 36. Agenda <ul><li>Enterprise Library 3.0 Introduction </li></ul><ul><li>Policy Injection Motivations and Goals </li></ul><ul><li>Policy Injection Application Block Architecture </li></ul><ul><li>Call Handlers and Matching Rules </li></ul><ul><li>Extending the PIAB </li></ul><ul><li>Summary </li></ul>
    37. 37. Summary <ul><li>The Policy Injection Application Block is about separating business logic from cross cutting concerns </li></ul><ul><li>Cross cutting concerns are applied using policies, comprising of matching rules and a handler pipeline </li></ul><ul><li>Each handler can perform logic before or after a method call </li></ul><ul><li>Policy-enabled objects are created with a factory that returns a proxy wired up to the handler pipeline </li></ul><ul><li>Used wisely, this application block can improve clarity, maintainability and consistency of applications </li></ul>
    38. 38. Resources <ul><li>Download Enterprise Library and related resources from: </li></ul><ul><ul><li>http://msdn.microsoft.com/practices </li></ul></ul><ul><li>Join the Enterprise Library Community at: </li></ul><ul><ul><li>http://codeplex.com/entlib </li></ul></ul><ul><li>Share community extensions at: </li></ul><ul><ul><li>http://codeplex.com/entlibcontrib </li></ul></ul><ul><li>Read blogs from the Enterprise Library team at: </li></ul><ul><ul><li>http://msdn.microsoft.com/practices/Comm/EntLibBlogs </li></ul></ul>

    ×