Giter Club home page Giter Club logo

logicengine's Introduction

LogicEngine Status

Get help on Codementor

LogicEngine

LogicEngine is designed to run arbitrary rules or bits of logic against a given model. It's written in C# .NET 4.6.2 and supports:

  • .NET 4.0
  • .NET 4.5
  • .NET 4.6+

This project is born out of a DRY (don't repeat yourself) mentality. In other words, I was using the same code on several projects.

How to use

The source code has a working example (ExampleEngine) which shows how easy the logic engine is to use. The steps to use LogicEngine are as follows:

  1. Create your business model
public class ExampleModel
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int AddResult { get; set; }
    public int SubtractResult { get; set; }
    public int MultiplicaionResult { get; set; }
    public float DivisionResult { get; set; }
}
  1. Create rules which implement IRule<T>
public class AddRule : IRule<ExampleModel> 
{
    public IEngineResult Execute(ExampleModel model)
    {
        EngineResult result = new EngineResult() { Name = GetType().ToString() };
        model.AddResult = model.Value1 + model.Value2;
        return result;
    }
}
  1. Add the rules to the rule collection
  2. Create the engine with the collection
  3. Execute the engine with your business model
Engine<ExampleModel> engine = new Engine<ExampleModel>(
    new RuleCollection<ExampleModel>()
    {
        new AddRule(), 
        new DivisionRule(), 
        new MultiplicationRule(), 
        new SubtractRule()
    }) {RunBumperRules = true};
var retval = engine.Execute(model);

The engine has the following interface:

public interface IEngine<T> 
	where T: class 
{
    IList<IEngineResult> Execute(T model);
    bool RunBumperRules { get; set; }
    TimeSpan RunElapsed { get; }
}

RunBumperRulles will insert PreRun and PostRun rules as the first and last rules. These are used to determine RunElapsed timespan.

The engine returns a list of IEngineResult:

public interface IEngineResult
{
    string Name { get; set; }
    bool HasError { get; }
    string Error { get; set; }
    string Message { get; set; }
    DateTime TimeStart { get; }
    DateTime TimeEnd { get; }
    TimeSpan Elapsed { get; }
    IEngineResult End(); // You should never need to call this.
}

Each IEngineResult will return the Elapsed TimeSpan. It's your reponsiblity to set Name, Error, and Message.

API

The only real requirement is to implement the IRule interface:

public interface IRule<T> where T : class
{
    IEngineResult Execute(T model);
}

In the ExampleEngine, the AddRule class looks like this:

public class AddRule : IRule<ExampleModel> 
{
    public IEngineResult Execute(ExampleModel model)
    {
        EngineResult result = new EngineResult() { Name = GetType().ToString() };
        model.AddResult = model.Value1 + model.Value2;
        return result;
    }
}

The EngineResult class can be implemented, or you can use your own. The Engine returns a list of EngineResults. You can add any information you'd like.

Once the rules are created, you only need to create an engine with them and execute the rules against the model.

public IList<IEngineResult> Run(ExampleModel model)
{
    Engine<ExampleModel> engine = new Engine<ExampleModel>(
        new RuleCollection<ExampleModel>()
        {
            new AddRule(), 
            new DivisionRule(), 
            new MultiplicationRule(), 
            new SubtractRule()
        }) {RunBumperRules = true};
    var retval = engine.Execute(model);
    return retval;
}

Bumper Rules

The engine has some "bumper rules". They're rules that run before/after all your rules. They will give you run start/stop times.

new Engine<SomeModel>(someListOfRules) {RunBumperRules = true;}

Results Formatter

The engine has support for formatting the list of IEngineResults. There are two provided formatters:

  1. NoopFormatter This formatter does nothing. It's the default formatter if you don't provide one.
  2. CsvFormatter This formatter returns a CSV list of the results. NOTE: The first row will the total elapsed run time.
public Engine(IRuleCollection<T> rules, IResultsFormatter resultFormatter = null)

The only requirement to implement your own formatter is to implement the IResultsFormatter interface as seen in the CsvResultsFormatter:

public interface IResultsFormatter
{
	void OutputResults(IList<IEngineResult> results, TimeSpan totalTime);
}

public class CsvResultsFormatter : ICsvResultsFormatter
{
	public string Output { get; private set; }
	public void OutputResults(IList<IEngineResult> results, TimeSpan runElapsed)
	{
		var format = "{0},{1},{2},{3},{4},{5},{6}\r\n";
		StringBuilder sb = new StringBuilder();
		sb.AppendLine("Run Elapsed Total Time: " + runElapsed);
		sb.AppendFormat(format, "RuleName", "Start", "Stop", "Elapsed", "HasError","Message" ,"ErrorMessage");
		foreach (var result in results)
		{
			sb.AppendFormat(format, result.Name, result.TimeStart,result.TimeEnd, result.Elapsed, result.HasError, result.Message,result.Error);
		}
		this.Output = sb.ToString();
	}
}

Dependency Injection Support

You can use dependency injection to add your rules. Simply add them to the RulesCollection.

UnityContainer container = new UnityContainer();
container.RegisterType<IEngine<string>,Engine<string>>();
container.RegisterType<IResultsFormatter, NoopFormatter>();
IRuleCollection<string> coll = new RuleCollection<string>();
container.RegisterInstance(coll);
var engine = container.Resolve<IEngine<string>>();
Assert.IsNotNull(engine);

Feature Requests

Feature Requests

logicengine's People

Contributors

wbsimms avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.