-
Notifications
You must be signed in to change notification settings - Fork 3
Example
Navid Mehralizadeh edited this page Sep 29, 2019
·
3 revisions
using RuleEngineCore.Annotaion;
using RuleEngineCore.RuleEngine;
using RuleEngineCore.RuleEngine.Exceptions;
using System;
namespace RuleEngine.Example
{
public class RuleEngineExample
{
public void run()
{
var facts = new Facts();
facts.Put("Birthdate", new DateTime(1988, 11, 23));
facts.Put("Gender", true);
facts.Put("NationalId", "1234567890");
try
{
Rule MyRule = new Rule(new IdentificationRule());
MyRule.Execute(facts);
}
catch (RuleException ruleException)
{
Console.WriteLine(ruleException.Message);
var inner = ruleException.InnerException;
while (inner != null)
{
Console.WriteLine(inner.Message);
inner = inner.InnerException;
}
}
}
}
[Rule(NextRule = typeof(AccountRule))]
public class IdentificationRule
{
[Action]
public void UpdateUserInfo()
{
// Call a service or business to update something or do anything that you must to do
Console.WriteLine("AccountRule Is passed too.");
}
[Condition("Birthdate,Gender", "If you are boy Your age must be more than 18 years old else more than 20 years old.")]
public bool CheckAgeByGender(DateTime BirthDate, bool Gender)
{
return Gender ? CalcualteAge(BirthDate) > 18 : CalcualteAge(BirthDate) > 20;
}
private int CalcualteAge(DateTime BirthDate)
{
var today = DateTime.Today;
var age = today.Year - BirthDate.Year;
if (BirthDate.Date > today.AddYears(-age)) age--;
return age;
}
[Condition("NationalId", "Your NationalId is not valid.")]
public bool NationalIdIsValid(string NationalId)
{
return NationalId.Length == 10;
}
}
[Rule]
public class AccountRule
{
[Action]
public void UpgradeAccount()
{
Console.WriteLine("AccountRule Is passed too.");
}
[Condition("AccountNo", "Your Account is not valid")]
public bool IsAccountValid(int accountNo)
{
var accountInfo = GetAccountInfo(accountNo);
return accountInfo.FullName.Length > 0;
}
private AccountInfo GetAccountInfo(int accountNo)
{
//Get From database or service or anywhere that you store your data
return new AccountInfo()
{
AccountNo = accountNo,
FirstName = "Navid",
LastName = "Mehralizadeh",
};
}
}
public class AccountInfo
{
public int AccountNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
}
}