Giter Club home page Giter Club logo

enflow's Introduction

Enflow is a simple library for workflows and state/business rules. It is a potential replacement for the Unit of Work pattern popular in MVC applications, particularly where model state validation must accompany units of work.

Usage is not limited to MVC. Enflow is a Portable Class Library (PCL) and works across multiple platforms. For more information, including usage in Xamarin.Android and Xamarin.iOS, see this blog post (and update) by Stuart Lodge (@slodge). Note: Currently experiencing a problem targeting Xamarin.Android and Xamarin.iOS. Working to resolve.

Enflow is available via NuGet.

Models

Note: It is no longer necessary to mark types with the IModel<T> interface. This has been removed - Enflow is now much more versatile.

State Rules

Create rules based on any type and use the fluent API to create composite rules from atomic constituents.

public class Employee
{
    public string Name { get; set; }
    public string Department { get; set; }
    public string Salary { get; set; }
}

public class MaxSalaryRule : StateRule<Employee>
{
    public override Expression<Func<Employee, bool>>
    {
        get { return candidate => candidate.Salary < 40000; }
    }
}

public class InHrDepartmentRule : StateRule<Employee>
{
    public override Expression<Func<Employee, bool>>
    {
        get { return candidate => candidate.Department == "Human Resources"; }
    }
}

// Compose a new rule from the others and describe it.
var salaryRaiseRule = new MaxSalaryRule()
    .And(new InHrDepartmentRule())
    .Describe("Employee must be in the HR deparment and have a salary less than $40,000.");

// Candidates can then be checked against a rule to see if they satisfy it.
var isEligible = salaryRaiseRule.IsSatified(someEmployee);

// A rule can also be used to filter an IQueryable via the Predicate property.
// Depending on the actual expression, this will also work with LINQ to Entities.
var eligibleEmployees = Employees.Where(salaryRaiseRule.Predicate);

Workflows

This is our new Unit of Work. Instantiate, passing in the rule to be validated. If the rule validation fails, a StateRuleException will be thrown with the rule description as the message.

// Example incorporating a repository pattern.
public class ApplySalaryRaise : Workflow<Employee>
{
    private readonly IRepository<Employee> _repository;

    public ApplySalaryRaise(IStateRule<Employee> rule, IRepository<Employee> repository) : base(rule)
    {
        _repository = repository;
    }

    protected override Employee ExecuteWorkflow(Employee candidate)
    {
        candidate.Salary += 5000;
        _repository.Update(candidate);
        return candidate;
    }
}

// Some example candidates for our workflow.
var eligibleEmployee = new Employee
    {
        Name = "John Smith",
        Department = "Human Resources",
        Salary = 10000;
    };

var ineligibleEmployee = new Employee
    {
        Name = "Tye Tarse",
        Department = "Board of Directors",
        Salary = 1000000
    };

// Give the candidate employee a $5000 raise if they're in HR and they earn less than $40k.
var salaryRaiseWorflow = new ApplySalaryRaise(salaryRaiseRule, new EmployeeRepository());

// Input candidate will be granted the salary raise.
salaryRaiseWorflow.Execute(eligibleEmployee); 

// This will throw a StateRuleException.
salaryRaiseWorflow.Execute(ineligibleEmployee);

Flowable

Flowable is a type amplification wrapper that allows fluent, declaritive use of Enflow.

// It is possible to chain workflows using flowable.
// This would apply two pay increases as long as the salary remained under $40k.
eligibleEmployee
    .AsFlowable()
    .Flow(salaryRaiseWorflow)
    .Flow(salaryRaiseWorflow);

// State rule checks can also be applied directly to flowables.
var canThisPersonGetMore = eligibleEmployee
    .AsFlowable()
    .Flow(salaryRaiseWorflow)
    .Satisfies(salaryRaiseRule);

An IWorkflow<T> returns T from its call to Execute. IWorkflow<T, U> allows chaining together sequences of workflows that pass different types between them. This means complex workflows can be expressed as compositions of smaller ones, increasing modularity, re-use and testability.

public class Department
{
    public string Name { get; set; }
    public int EmployeeCount { get; set; }
    public string Building { get; set; }
}

// These examples have the repository/persistence code omitted for clarity.

public class MoveHrPersonToNewDepartment : Workflow<Employee, Department>
{
    public Department Destination { get; set; }

    protected override Department ExecuteWorkflow(Employee candidate)
    {
        candidate.Department = Destination.Name;
        Destination.EmployeeCount++;
        return Destination;
    }
}

public class MoveToTheNewOffice : Workflow<Department>
{
    protected override Department ExecuteWorkflow(Department candidate)
    {
        candidate.Building = "Uptown Office";
        return candidate;
    }
}

var moveToBoardWorkflow = new MoveHrPersonToNewDepartment(new InHrDepartmentRule())
    {
        // Something like this would come from the DB in a less contrived example, of course.
        Department = new Department 
            { 
                Name = "Board of Directors", 
                EmployeeCount = 5,
                Building = "Downtown Office"
            }
    };

var moveDeptOfficeWorkflow = new MoveToTheNewOffice();

var employeeLocation = eligibleEmployee
    .AsFlowable()
    .Flow(salaryRaiseWorflow)
    .Flow(moveToBoardWorkflow)
    .Flow(moveDeptOfficeWorkflow)
    .Value
    .Building; // "Uptown Office"

The Workflow Factory

Note: The workflow factory has been removed from Enflow.

License

Unless otherwise specified, all content in this repository is licensed as follows.

The MIT License (MIT)

Copyright (c) 2013 Joseph Phillips

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

enflow's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

enflow's Issues

Multiple And operator not working

Hello, I'm having problem using the following rules:

My test table is like this:
Configuration //Id is auto incremental
Id | Code | Value
1 | "a" | "value1"
2 | "b" | "value2"

I'm trying to insert this new configuration
Configuration configuration = new Configuration(){ Code = "c", Value = "not empty" };

var rules = new CodeNotEmpty().And(ValueNotEmpty()).And(CodeIsUnique());

var satisfied = rules.IsSatisfied(configuration); //it is false, but should be true

But if I do this way, it works:
var rules2 = new CodeNotEmpty().And(ValueNotEmpty());

var satisfied2 = rules2.IsSatisfied(configuration) && new CodeIsUnique().IsSatisfied(configuration); //this is true, as it should be

public class CodeNotEmpty: StateRule
{
public override Expression<Func<Configuracao, bool>> Predicate
{
get { return o => o.Code != null && o.Code.Trim() != string.Empty; }
}
}

public class ValueNotEmpty: StateRule
{
public override Expression<Func<Configuracao, bool>> Predicate
{
get { return o => o.Value != null && o.Value.Trim() != string.Empty; }
}
}

public class CodeIsUnique: StateRule
{
public override Expression<Func<Configuracao, bool>> Predicate
{
get {
Database database = new Database();
return o => !database.GetTable< Configuration >().Any(p => p.Id != o.Id && p.Code == o.Code);
}
}
}

By the way, if there is any syntax error, please ignore because I did translate the code, and it can be missing a few characters..

And thank you for this great job, I loved this library, very pratical and easy to use.

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.