Microsoft Enterprise Library 5.0 series (9) Policy Injection Application Block

Source: Internet
Author: User

The Proxy Object is located to the Real Object through the Handler chain, and the Policy is injected into the Proxy Object and the Real Object. Entire Process

 

My personal opinion on the use of Policy Injection Application Block is:

The user first creates a proxy and uses this proxy to indirectly manipulate the entity. when calling the object method or member attribute, it can transparently trigger a series of set Handler (such as diary record and identity verification ), you only need to modify the corresponding configuration file to quickly change the Handler chain. (because it is personal opinion, maybe not very accurate, the official explanation in this http://msdn.microsoft.com/en-us/library/ff647463.aspx)

Authorization:

 

 

Currently, PIAB's predefined Handler includes Validation Handler, Logging Handler, Exception Handling Handler, Authorization Handler, and Caching Handler. These Handler correspond almost exactly to other Application blocks in the Enterprise Library. In fact, permission authentication, logs, exception handling, and caching are the most important concerns of AOP technology. The Application Block before February 2007 CTP actually has the prototype of AOP. Then, due to its lack of "cross-cutting" and "injection", it cannot achieve the reuse purpose required by AOP. Policy Injection Application Block makes up for such shortcomings. It is the same as before. Let's talk about it using an instance. Because this module has many functions and a large program, I have packaged it for you to download and study at the end of the article.

Next we will analyze the Policy Injection Application Block:

First, analyze the requirements:

1. Create a financial manager

2. Three roles are provided:

A) Teller: Allows deposit, withdrawal, and account checking.

B) Assistant: allows calling the account checking method

C) Janitor: Has No permissions for testing.

3. Create several users and assign them to these three roles. the user does not need to determine the role of the current user in the Code for calling the method, that is, the judgment process is transparent.

4. The call method information and error information are automatically written into the log, and the log writing process is transparent.

Let's talk about the traditional programming method first. Assume that a user, Charlie, belongs to the Janitor role. When he presses the account check button in the program, he should be prompted not to allow it, and write the error into the log, the program may be as follows:

Private void button#click (object sender, EventArgs e)
{
// Perform role verification first
If (Charlie. role! = Assistant | Charlie. role! = Teller)
{
// If the conditions are not met, an error is reported and logs are written.
MessageBox. Show ("authentication failed ");
Log. Write ("authentication failed ");
}
Else
{
// Obtain the balance
Double balance = GetCurrentBalance ();
MessageBox. Show (balance. ToString ());
}
}

It should be noted that only the red part of the Code actually implements the business logic, and the blue part is the identification and error handling, when more and more similar business operations occur in your program, you will find that you need to copy a lot of code here. This shows that your program needs to be restructured, if you need to verify another role or change the log processing scheme, you need to re-update the Code with the same business logic in the entire program, this is obviously not allowed. so the Policy Injection Application Block is ready for use now!

Look at the code style after the Policy Injection Application Block is used:

Privatevoid button#click (object sender, EventArgs e)
{
Try
{
Double balance = GetCurrentBalance ();
MessageBox. Show (balance. ToString ());
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}

How? Simple, the program only has Code related to the business logic, and there are no other redundant non-business logic Code. However, the implementation function is the same as the previous code! Do you want to know how to implement it? Please refer to the following tutorial. (I will package the source code in the tutorial for you to download. Please find the download link at the end of the article)

1. first, we need a BankAccount class to provide the attributes and methods required for financial management. We add a balance private attribute to this class to indicate the balance. the Deposit, Withdraw, and GetCurrentBalance methods are also provided to implement Deposit, withdrawal, and balance query functions. the code for this class is as follows:

Using System;
Using System. Collections. Generic;
Using System. Text;
Using Microsoft. Practices. EnterpriseLibrary. PolicyInjection;
Using Microsoft. Practices. EnterpriseLibrary. PolicyInjection. CallHandlers;
Using Microsoft. Practices. EnterpriseLibrary. Validation. PolicyInjection;
Using Microsoft. Practices. EnterpriseLibrary. Validation. Validators;

Namespace test
{
Public class BankAccount: financialbyrefobject
{
Private decimal balance;
/// <Summary>
/// Obtain the current balance
/// </Summary>
Public decimal GetCurrentBalance ()
{
Return balance;
}

/// <Summary>
/// Deposit
/// </Summary>
/// <Param name = "depositAmount"> deposit amount </param>
[ValidationCallHandler]
Public void Deposit ([RangeValidator (typeof (Decimal), "0.0", RangeBoundaryType. Exclusive, "0.0", RangeBoundaryType. Ignore, MessageTemplate = "Deposit amount must be greater than zero")
Decimal depositAmount)
{
Balance + = depositAmount;
}

/// <Summary>
/// Withdrawal
/// </Summary>
/// <Param name = "withdrawAmount"> withdrawal amount </param>
[ValidationCallHandler]
Public void Withdraw ([RangeValidator (typeof (Decimal), "0.0", RangeBoundaryType. exclusive, "1000.0", RangeBoundaryType. passive, MessageTemplate = "the withdrawal amount must be between 0 and 1000. ")]
Decimal withdrawAmount)
{
If (withdrawAmount> balance)
{
Throw new ArithmeticException ();
}
Balance-= withdrawAmount;
}
}
}

2. RunEntLibConfig.exe, SelectBlocksMenu, clickAdd Policy Injection Settings.ClickPlus button-AddPolicy, SetNameModify attributeMyPoliy:

3. On the IES panelRight-click-Add Matching Rules-Add Member Name Matching Rule, Click the createdMemberName Matching RulePanelMember NamesAdd the member method name (Deposit, Withdraw, GetCurrentBalance) in the BankAccount class to the plus icon on the right of the project, indicating that these methods must be matched in our MyPoliy decision, if it is called by the program or an error occurs, the corresponding processing will be performed.

4. As a result, we need to add a certain error handling mechanism, right-click the Policies panel-Add Handlers-Add Logging Call HandlerAnd set it as the log recording method in text. The details of the log module are not described here. You can refer to my previous article. now, we have completed the member method call and error exception handling mechanism. the log Text Formatting settings are as follows:

Timestamp:{timestamp}
Message:{message}
Category:{category}
Type:{property(TypeName)}
Method:{property(MethodName)}
Parameters:{dictionary({key} : {value})}
ReturnValue: {property(ReturnValue)}
Exception:{property(Exception)}
CallTime: {property(CallTime)}
Priority:{priority}
EventId:{eventid}
Severity:{severity}
Title:{title}
Machine:{machine}
ApplicationDomain: {appDomain}
ProcessId: {processId}
ProcessName: {processName}
Win32Thread Id: {win32ThreadId}
Thread Name: {threadName}

5. well, let's look at the requirements. We also need to create three roles and some users. here we will explain the Application module in EL by the way, because it has very simple functions, so we will not provide a specific tutorial. Here we will use it to configure roles and users. selectBlocksMenu, clickAdd Application Settings.Click the plus sign in the upper-right corner of the Setting panel to add some users, which are

Key: User: Alice Value: Teller

Key: User: Bob Value: Assistant

Key: User: Charlie Value: Janitor

In the Key Value, "User:" indicates that the User is added, followed by the User name, and "Value" indicates the role that the User belongs, in the program, we can write a function to get the user name and role from this module (here the user name and role are generally stored in the database or XML file, I would like to take this opportunity to explain the Application module here. You can use other solutions ):

6. now that you have users and roles, You need to configure the verification module. this requires the Security Module we mentioned earlier. The detailed introduction of this module has been written in my previous articles. I will not talk about it here, but only about the application.

SelectBlocksMenu, clickAdd Security Settings. Click in the upper-right corner of the Authorization Providers panelPlus button-Add Authorization Providers-Add AuthorizationRule Provider.

7. Right-click the Authorization Rule Provider panel-AddAuthorization RulesTo add a verification rule. Here we set the verification rule in 3 to assign the deposit, withdrawal, and Audit Permissions in the BankAccount class to the three roles just created. The settings are as follows:

Name: Deposit Rule Expression: R: Teller

Name: Withdraw Rule Expression: R: Teller

Name: GetCurrentBalance RuleExpression: R: Teller or r: Assistant

8. after the verification rule module is set, we need to associate it with our Poliy module. Because it is identity authentication, the matching scope should be in the entire Namespace, so let's go back to the Poliy module, clickPlus button-Add Policy, SetNameModify attributeAuthorizeAnd then on the Authorize panelRight-click-Add Matching Rules-Add Namespace Matching RuleAnd add a matching object,NameSetTest (make sure that the Namespace name you want to match is the same):

9. On the Authorizes panelRight-click-Add Handlers-Add Authorization Call HandlerShows the property settings:

10. now, we have bound the validation rule module to the Poliy module. Now we can run the program to verify the verification. The program has been packaged before downloading. I just want to show you the demo effect, for details, see the source code:

Then, click View log and you will find that all previous operations have been recorded:

Well, the PolicyInjection Application Block module will talk about this. You can leave a message for me if you have any good ideas ~

Download source code:

Click here \ (^ )/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.