zoukankan      html  css  js  c++  java
  • Smart Rules a Tool for Building and Testing Business Rules(转载与CodeProject)

    Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report this article.

    Sample Image - logo.gif

    Introduction

    Typical Enterprise application include the next elements: one front end, such as Web interface, a back end database access layer, such as SQL Server and business logic services in between. While it is now common practice to use frameworks and components, commercial or not, for the front end and back end layers, there is no standard way of structuring dynamic business logic. This article tries to give a survey for replace the IF…THEN hard code statement, with a framework that gave us the same benefits of configurability, readability, and reuse that we already exist in other areas, using the Smart Rules Tools.

    Overview of Smart Rules Framework

    Smart Rules Tools is a Business Rules Management System, created by Kontac. which facilitate the separation of business rules from application code, allowing dramatic reduction in maintenance and enhancement costs for software applications. Use of Smart Rules will allow organizations to substantially reduce their development resource requirements while shortening development latency to near zero. Thus, the agility of Smart Rules will allow organizations to become more competitive in their markets while enjoying the bonus of cost reduced development

    Business Rules

    Typical business rules can be represented as simple if-then statement:
    If a driver’s age is younger than 18, then decline to rent.

    Traditionally, business rules are embedded in application code, and might appear in a VB.NET application as follows: 

       'Simple business rule	
       Public Function CheckUnderAgeRule() As Boolean
            Dim DeclineRent As Boolean = False 
            If Me.Age < 18 Then
                DeclineRent = True
            End If 
            Return DeclineRent 
        End Function
    
    
    We've all come across similar (or even more complex) business logic. While this has been the standard way of implementing business logic in traditional programming languages, there are many problems with it:
    • The code is inflexible, suppose that the rental company changes its rule to "Age Under 21", in many production environments, the developer would need to modify the application, recompile, and then redeploy the application.
    • This code is not easy for non-technical users to read and can be difficult to understand and modify.
    • How do we check that these rules are correct? It's hard enough for technical people--never mind commercial folks--to review. Do we have any methodical way of testing this business logic?.
    • If we have one product and various clients with distinct needs, how you can manage multiples source code and versions?.
    • What if other languages want to leverage the existing Age Rule in business rule logic?.
    An additional problem is that business logic tends to differ widely between applications. Our framework should be able to cope with this and still promote code reuse.

    Smart Rule Engines to the Rescue

    How are we going to solve this problem? One solution, in .NET, is write the code in text file and attach the code, in runtime, using Reflection. Other solution that is gaining traction is to use a rule engine. Rule engines are frameworks for organizing business logic that allow the developer to concentrate on things that are known to be true, rather than the low-level mechanics of making decisions.

    Kontac, allows a business analyst to change business policies expressed as rules quickly with little or no assistance from a programmer. Applications using Smart Rules, called rule enabled applications, can quickly adapt to new regulations, improvements in internal company processes, and changes in relationships with customers and suppliers.

    Starting a VB.NET Application using Smart Rules

    To get started, download the Smart Rules and create a new VB.NET project in Visual Studio .NET and make sure to add reference to SmartRules.Engine.dll and add you CareRental.exe to GAC.

    Alternatively, the code for this article includes a completed Dictionary file – if you don't want to build the business dictionary for yourself, feel free to import the completed alias (CarRentalAliases.xml, on zip file)  via the Smart Rules Deployment Wizard. There is more information about using this tool later in this paper. 

    Defining a Data Model for the Car Rental Sample

    Before working with Smart Rules you need to define a data model. A data model contains business data definitions for facts or data objects used in rules, including: .NET class fact types, XML fact types, and DataTable or Data Row types (Database fact types).

    We need three .NET components facts, incorporate .NET components into your rules as facts is an important feature that significantly increases the rules' flexibility, Rather than just working on static data, this feature allows your rules to interact with instances of your components – reading and writing properties, calling methods – to provide a programmable and dynamic element to your business rules.

    PayType component

        Public Enum PayType
            Cash
            Credit_Card
            Check_Card
        End Enum
    

    This component helps us restrict if Customer pay type is by Credit Card, Check Card or Cash. Some rules apply for each pay type.

    Customer Component

     Public Class Customer 
        Private _Name As String
        Private _Age As Integer
        Private _LicenseNo As String
        Private _PaymentType As PayType
        Private _PreAccidents As Boolean
        Private _AbleToDrive As Boolean
     
        'Properties Get for each field.
     
    End Class
    
    

    This class is the business object representing a Customer, who wants rental a car. This component provides basic information like the Pay Type for initial deposit or Age accidents, the rental company can configure the minimal age for rent a car.

    RentalInfo Component

    Public Class RentalInfo 
        Private _Reason As String
        Private _PickupDate As Date
        Private _ReturnDate As Date
        Private _CustomerName As String
        Private _CarId As Integer
        Private _RentalAmount As Decimal
        Private _DepositAmount As Decimal
        Private _ExtraCharge As Decimal
     
        'Get/Set properties
        '…………….
        Public Property Reason() As String
            Get
                Return Me._Reason
            End Get
            Set(ByVal Value As String)
                Me._Reason = Value
            End Set
        End Property
     
        Public Function DaysOfRent() As Integer
            Dim Ts As TimeSpan = Me._ReturnDate.Subtract(Me._PickupDate)
            Return Ts.Days
        End Function
    
    

    The final piece of our facts is this third .NET component. This simple component represents the Rental info functionality that our rules need to call on; in this example the logic is some very simple local code. The class has two key members used for Smart Rules Studio:

    • Public Function DaysOfRent() As Integer
      This is a read-only property that exposes the days of rent. The value of the days is selected from days between pickup date and return date.
    • Public Property Reason() As String
      If any reason for rental declined is done, the Smart Rules Engine write the reason using it method.

    Defining Database Model for the Car Rental Sample

    Because we are going to use a database for the source of vehicles, we need build the basic car table information using the next script:

    CREATE TABLE [Vehicle] (   
        [VehicleId] [int] IDENTITY (1, 1) NOT NULL,
        [RateDaily] [money] NOT NULL,
        [VehicleType] [varchar] (50) NOT NULL,
        [VehicleStatus] [int] NOT NULL,
        [MinDays] [int] NOT NULL 
    ) 
    ON [PRIMARY]
    GO
    
    INSERT INTO  [Vehicle]([RateDaily], [VehicleType], [VehicleStatus], [MinDays])
    VALUES (45, ‘Truck’, 1, 4)
    
    INSERT INTO  [Vehicle]([RateDaily], [VehicleType], [VehicleStatus], [MinDays])
    VALUES (35, ‘VAN’, 1, 2)
    
    

    Writing the Business Logic using Smart Rules Studio

    The car Rental business rules development will be done in the Smart Rules Studio. The car rental sample, customer specifies driver information and the business rules determine if a rental company service representative should decline to rent a vehicle due to driver age restrictions, and calculate net charges payable by a customer, including deposit, total rent by days, and extra charges. Now you create one rule, the Under Age rule.

    Starting Smart Rules Studio

    You access to Smart Rules Studio from Smart Rules menu, Smart Rules save the data in any compatible SQL Server database, include MSDE 2000.

     
    Click here to enlarge

    The Smart Rules Studio Interface

    Creating Dictionaries

    Names of the methods and classes used in Smart Rules can often be pretty complex, like its:

    Customer.get_Age() is less than 18 
    OR
    CarRentalDB.Vehicle.VehicleType is equal to 2
    

    To facilitate work with complex class names or methods names, Smart Rules allows business analysts to create rules using familiar names with a feature called business dictionary. If you use dictionary their rules will be look like below:

    In English:

    Customer Age is less than Min age for rent a car  or 
    The vehicle Type is equal to Truck 

    In Spanish:

    La Edad del Cliente less than Edad minima para rentar  or 
    El Tipo de Vehiculo is equal to Camioneta 

    You can develop rules without building a business dictionay, but you decrease the readability of your code, if you don't use dictionaries. As stated earlier, a dictionary maps your .NET classes, and database information to user-friendly text.

    Alternatively, the code for this article includes a completed dictionarie files – if you don't want to build the dictionary for yourself, feel free to import the completed dictionaries and rule sets via the Smart Rules Deployment Wizard. There is more information about using this tool later in this paper.

    Putting the Dictionary Together


    The Business Dictionary Pane

    To actually build our Dictionary we'll be using the Smart Rules Studio. The user interface to do this is very straightforward. Here are the basic steps:

    • Select the Dictionaries root node in the Business Dictionary Pane.
    • Right Click and Select Add New Dictionary.
    • Give the Dictionary the name Car Rental.
    • Save It.

    Specifying the Business Dictionary for Class Fact Definitions

    To specify the business Dictionary for Class Fact definitions, the VB.NET GetAge property, do the following:

    1. Right-click your Car Rental Dictionary version,  and select Add New Class Alias.
    2. Click Browse and then scroll down the list of assemblies. Select CarRental and click OK.
    3. A dialog box now prompts us for the class or member that we need to expose as a fact. Select the Customer.get_Age() method and click OK.
    4. Update the Alias Name and Display Name to Customer Age and then click OK.

    We need to repeat steps 1 to 4 for the following .NET component members RentalInfo.get_Reason() method, Alias name "Get declined reason".

    The same way you can create Dictionary for Databases, using the Add New Data Row Alias submenu from Add New Database alias, and for the age limit constant 18 using the Add Literal Alias submenu from Add Constant Alias menu.

    Finally, we need to save and lock our new alias. Right-click on your alias and select Save. Then right-click it again and select Lock.

    Creating Rule Sets

    The Smart Rules Knowledge base is the top-level container and the starting point for working with Smart Rules Studio.


    The Knowledge base Pane

    To create a Rule Set, do the following:

    • In the Knowledge Base Explorer right-click the Rule Sets folder and then click Add New Rule Sets.
    • Name the Rule Set Base CarRental.
    • Save It.

    Creating a Rule for the Car Rental Sample

    After creating a RuleSet you can create rules within the RuleSet. In this section, you create the UnderAge rule. The UnderAge rule tests the following:

    If the driver's age is younger than 18, then decline to rent.
    The following actions are associated with the UnderAge rule:

    • Set the RentalInfo.Reason the text, "Rental Declined".
    • Assert the matched driver object.

    Rule Sets are groups of rules, rules creation works differently from Dictionaries . Dictionaries use a dialog windows, Rules creation employs drag and drop and right click extensively, To define the UnderAge rule:

    • Right-click the Version 1.0 folder under the CarRental folder and then click Add New Rule.
    • Name the rule UnderAge. The center side of the screen will be populated with an IF (condition section) and a THEN (action section).
    • Right click in Condition text and select the LessThan predicate from the popup menu.
    • Drag and drop the Customer Age from Dictionary treeview to argument1
    • Drag and drop the Min age rent a Car to argument2

    Adding Actions for the Under Age Rule

    Actions are associated with pattern matches. When a rule’s "If" portion matches, the Rules Engine activates the "Then" portion and prepares to run the rule’s action. In this section, you add two actions for the UnderAge rule. The first action set the reason value to "Declined rental". The second action Assert the RentalInfo for continue processing the rules with the updated values.

    To add the actions that set the reason to declined and assert the RentalInfo to memory for a match of the UnderAge rule, do the following:

    • Drag and drop the Set declined reason Alias from Business Dictionary pane.
    • Replace the <empty string> text with the Rental Declined text, without "".
    • Right Click in Actions and select the Assert option from context menu.
    • Go to Assembly fact, in Facts pane, and select the RentaInfo root class node, drag and drop it, to the fact argument.

    Finally, we need to save and deploy our new RuleSet. Right-click on your version and select Save. Then right-click it again and select Deploy.

    Running the Car Rental Sample Using the Test Program

    In order to use the business rule engine, you must add a reference to it and instruct it which RuleSet to execute.

    When executing a RuleSet, you can specify a particular version, or provide no version ensuring that you use the latest deployed version every time.

    Dim customerFact As Customer 
    Dim rentalInfoFact As RentalInfo 
    Dim vehicleFact As TypedDataRow 
    
    'Constructors....blah blah blah... 
    
    'Get lasted deployed Rule for CarRental versions
    
    Dim engine As RuleEngine = GetRuleEngineWithKnowledgeBase("CarRental")   
    
    'Declare the short term fact for assert objects to engine 
    Dim shortTermFacts(3) As Object  
    shortTermFacts(0) = customerFact 
    shortTermFacts(1) = rentalInfoFact 
    shortTermFacts(2) = vehicleFact 
    shortTermFacts(3) = New Customer.PayType 'We need add the Paytype enum fact too 
    
      
    ' Asserting is the act of loading facts (.NET objects, XML Documents, etc.) into the memory of the executing RuleSets. 
    engine.Assert(shortTermFacts)  
    
    'Execute the Rule 
    engine.Execute() 
    
    
    

    Show the standard code to call and executing rules. for load the DataRow from database, the application needs to assert prepopulated DataTable or DataRow objects. For load a .NET class, is different, the class must be signed and loaded in the GAC.

    Test with different values and review the output, also you can modify the rules for test another scenarios.

    Smart Rules Deployment Tool

    When you work with the Smart Rules Studio, you're loading and saving rule sets and dictionaries from a specified SQL Server database. You might be wondering how you move those rules and Dictionary from that machine to a new location. The answer, as you might have guessed, is the Rules Engine Deployment Wizard.

    The code supplied with this paper contains both a Dictionaries and a Rule Sets. To make use of these files you'll need to first add the exe CarRental.exe into your GAC. Import the Dictionary file (CarRentalAliases.xml) followed by the RuleSet file (CarRentalKnowledge.xml). Finally, you need to deploy the RuleSet.

    Conclusion

    This article demonstrated a problem that most programmers have had to face: how to put some order on the complexity of business logic. We demonstrated a simple application using Smart Rules Engine as a solution and introduced the notion of rule-based programming, including how these rules are resolved at runtime.

    About SmartRules


    Smart Rules allows a business analyst to change business policies expressed as rules quickly with little or no assistance from a programmer

    Click here to view SmartRules's online profile.

  • 相关阅读:
    重定向请求
    json处理
    post请求
    get请求
    提交cookie登录
    进击的Python【第三章】:Python基础(三)
    进击的Python【第二章】:Python基础(二)
    进击的Python【第一章】:Python背景初探与Python基础(一)
    java 内存分析
    java--循环练习
  • 原文地址:https://www.cnblogs.com/zhoujg/p/544862.html
Copyright © 2011-2022 走看看