Huang Cong: Microsoft Enterprise Library 5.0 series tutorial (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:

Privatevoid 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:

Code

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
{
Publicclass bankaccount: financialbyrefobject
{
Privatedecimal balance;
/// <Summary>
/// Obtain the current balance
/// </Summary>
Publicdecimal getcurrentbalance ()
{
Return balance;
}

/// <Summary>
/// Deposit
/// </Summary>
/// <Param name = "depositamount"> deposit amount </param>
[Validationcallhandler]
Publicvoid 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]
Publicvoid 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)
{
Thrownew 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:

Log Text Formatting

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.