programing

.NET에서 간단한 규칙 엔진 라이브러리 찾기

nasanasas 2020. 11. 15. 11:23
반응형

.NET에서 간단한 규칙 엔진 라이브러리 찾기


좋은 .NET 라이브러리 규칙 라이브러리 (이상적으로는 오픈 소스)를 아는 사람이 있습니까? 예를 들어 (A AND B) AND (B OR C OR D)와 같이 중첩 논리 표현식을 수행 할 수있는 것이 필요합니다. 객체 속성 (예 : A.P1 및 B.P1)을 비교해야합니다. (이상적으로는 A.P1 및 B.P2의 모든 속성을 비교할 수 있습니다).

규칙을 데이터베이스에 저장해야합니다 (간단한 구성 가능한 논리가 많이 있습니다). 그리고 규칙 생성 / 관리 API가 있어야합니다. 관리 도구는 인스턴스를 검사하여 사용 가능한 속성과 존재하는 제약 조건을 결정해야합니다.

감사!


아, 한 가지 더. 규칙 엔진으로서 액션 (명령) 개념을 포함해야합니다. 표현식이 반환 될 때 실행되는 항목은 다음과 같습니다.

If (expression.Evaluation) { actions.Execute(); }

따라서 규칙은 다음과 같습니다.

class Rule
{
    Expression Exp;
    Actions[] Actions;
    Run() 
    { 
        if(Exp.Evaluate()) 
        { 
            foreach(action in Actions) 
            { 
                action.Execute(); 
            }
        } 
    }
}

동의하면 워크 플로는 아니지만 워크 플로 엔진 제품군의 무언가를 사용한다고 말할 수 있습니다. 검사 System.Workflow.Activities.Rules 네임 스페이스를 조금 - 그것은 닷넷 3에서 지원하고, .Net3.5에 내장. 당신은 당신이 언급했듯이 모든 것을 무료로 사용할 수 있습니다.

  • 조건의 경우 RuleCondition, 작업의 경우 RuleAction

  • 메타 코드를 설명하기위한 표준화 된 형식 (CodeDom-CodeExpressions)

  • TypeProviders를 통해 모든 종류의 복잡성을 플러그인 할 수 있습니다 (Linq 및 람다 등 어떤 종류의 확장 메서드를 제외하고 진실을 알리기 위해).

  • intellisense로 규칙 편집을위한 내장 편집기가 있습니다.

  • 규칙이 직렬화 가능하므로 쉽게 지속될 수 있습니다.

  • 데이터베이스 체계에 대한 규칙을 사용하려는 경우 typeprovider를 통해 구현할 수도 있습니다.

우선 : 워크 플로 외부에서 규칙 사용

추신 : 우리는 그것을 광범위하게 사용하고 있으며 그 네임 스페이스에는 당신이 상상했던 것보다 훨씬 더 많은 것이 있습니다-> 완전한 메타 알고리즘 언어

그리고 가장 중요한 것은 사용하기 쉽습니다.


여기 제가 과거에 사용한 수업이 있습니다. Javascript에서 eval ()처럼 문자열을 평가합니다.

String result = ExpressionEvaluator.EvaluateToString("(2+5) < 8");

해야 할 일은 비즈니스 객체에서 평가할 문자열을 구성하는 것뿐입니다. 그러면 모든 복잡한 중첩 논리 등을 처리 할 수 ​​있습니다.

using System;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Reflection;
using Microsoft.JScript;

namespace Common.Rule
{
  internal static class ExpressionEvaluator
  {
    #region static members
    private static object _evaluator = GetEvaluator();
    private static Type _evaluatorType;
    private const string _evaluatorSourceCode =
        @"package Evaluator
            {
               class Evaluator
               {
                  public function Eval(expr : String) : String 
                  { 
                     return eval(expr); 
                  }
               }
            }";

    #endregion

    #region static methods
    private static object GetEvaluator()
    {
      CompilerParameters parameters;
      parameters = new CompilerParameters();
      parameters.GenerateInMemory = true;

      JScriptCodeProvider jp = new JScriptCodeProvider();
      CompilerResults results = jp.CompileAssemblyFromSource(parameters, _evaluatorSourceCode);

      Assembly assembly = results.CompiledAssembly;
      _evaluatorType = assembly.GetType("Evaluator.Evaluator");

      return Activator.CreateInstance(_evaluatorType);
    }

    /// <summary>
    /// Executes the passed JScript Statement and returns the string representation of the result
    /// </summary>
    /// <param name="statement">A JScript statement to execute</param>
    /// <returns>The string representation of the result of evaluating the passed statement</returns>
    public static string EvaluateToString(string statement)
    {
      object o = EvaluateToObject(statement);
      return o.ToString();
    }

    /// <summary>
    /// Executes the passed JScript Statement and returns the result
    /// </summary>
    /// <param name="statement">A JScript statement to execute</param>
    /// <returns>The result of evaluating the passed statement</returns>
    public static object EvaluateToObject(string statement)
    {
      lock (_evaluator)
      {
        return _evaluatorType.InvokeMember(
                    "Eval",
                    BindingFlags.InvokeMethod,
                    null,
                    _evaluator,
                    new object[] { statement },
                    CultureInfo.CurrentCulture
                 );
      }
    }
    #endregion
  }    
}

None of the open sourced .NET rules-engine have support for storing rules in the database. The only ones that stored the rules in a database are commercial. I've created some UIs for custom rule engines that run off the database, but this can be non-trivial to implement. That's usually the main reason you won't see that feature for free.

As far as I know, none of them will meet all of your criteria, but here is a list of the ones I know of:

Simplest one is SRE
http://sourceforge.net/projects/sdsre/

One with rule management UI is NxBRE
http://www.agilepartner.net/oss/nxbre/

Drools.NET uses JBOSS rules
http://droolsdotnet.codehaus.org/

I personally haven't used any of them, because all of the projects I worked with never wanted to use something built in-house. Most business think that this is pretty easy to do, but end up wasting too much time coding and implementing it. This is one of those areas that the Not Invented Here Syndrome (NIH) rules.


Well, since logical expression are just a subset of mathematical expression, you may want to try NCalc - Mathematical Expressions Evaluator for .NET over on CodePlex.


The official MS solution for this is Windows Workflow. Although I wouldn't call it "simple", it meets all of your specifications (which would require an extensive framework to meet, anyhow).


I've used this http://www.codeproject.com/KB/recipes/Flee.aspx with success in the past. Give it a try.


Windows Workflow Foundation does give you a free forward chaining inference engine. And you can use it without the workflow part. Creating and Editing rules is ok for developers.

If you want to have non-programmers edit and maintain the rules you can try out the Rule Manager.

The Rule Manager will generate a working visual studio solution for you. That should get you started rather quickly. Just click on File \ Export and selecte the WFRules format.


You can take a look at our product as well at http://www.FlexRule.com

FlexRule is a Business Rule Engine framework with support for three engines; Procedural engine, Inference engine and RuleFlow engine. Its inference engine is a forward chaining inference that uses enhanced implementation of Rete Algorithm.


I would look at Windows Workflow. Rules engines and workflow tend to start simple and get progressively more complex. Something like Windows Workflow Foundation is not too difficult to start with and provides room for growth. Here is a post that shows it's not too difficult to get a simple workflow engine going.


Maybe check out SmartRules. Its not free, but the interface looks simple enough.

Only know about it because I've used the SmartCode codegen utility from there before.

Here is an example rule from the Website:

BUSINESS RULES IN NATURAL LANGUAGE      

Before
If (Customer.Age > 50 && Customer.Status == Status.Active) {
policy.SetDiscount(true, 10%);
}

After (with Smart Rules)
If Customer is older than 50 and
the Customer Status is Active Then
Apply 10 % of Discount

You can use a RuEn, an simple open source attribute based Rule Engine created by me:

http://ruen.codeplex.com


Try out http://rulesengine.codeplex.com/

It's a C# Open-Source rules engine that works with Expression trees.


Have a look at Logician: tutorial/overview on CodeProject

Project: page/source on SourceForge


Depending on what you are trying to do using Lambda expressions (and expression trees) can work for this concept. Essentially, you provide an expression as a string that is then compiled on the fly into a lambda expression/expression tree, which you can then execute (evaluate). It's not simple to understand at first, but once you do it's extremely powerful and fairly simple to set up.


It's not free, as you can't easily untangle it from its BizTalk parentage, but the Business Rules Engine components of BizTalk are a separate entity from the core BizTalk engine itself, and comprise a very powerful rules engine that includes a rules / policy based GUI. If there was a free version of this it would fit your requirements (buying BizTalk just for the BRE wouldn't really work commercially.)

참고URL : https://stackoverflow.com/questions/208659/looking-for-simple-rules-engine-library-in-net

반응형