Ejemplo n.º 1
0
        public void CreateExpression_DateOutsideOfWindowAndIsMonday_ReverseExpression_BuildsExpression(int year, int month, int day, bool validates, int numberOfErrorMsg)
        {
            // Test: (DateTime d) => d.DayOfWeek == DayOfWeek.Monday & (d < floorDate | d > ceilingDate)
            var floorDate   = new DateTime(2010, 2, 1);
            var ceilingDate = new DateTime(2010, 3, 1);
            var testDate    = new DateTime(year, month, day);

            // build rules / rule nodes for "d < floorDate | d > ceilingDate" and put in a group
            var rangeRuleNode = new RuleNode(new LessThan <CalendarEvent, DateTime>(floorDate));

            rangeRuleNode.OrChild(new RuleNode(new GreaterThan <CalendarEvent, DateTime>(ceilingDate)));
            var groupNode = new GroupNode(rangeRuleNode);

            // build rule / rule node for "d.DayOfWeek == DayOfWeek.Monday
            var dateOneMondayRule = new CustomRule <CalendarEvent, DateTime>((c, d) => d.DayOfWeek == DayOfWeek.Monday);

            dateOneMondayRule.Message = "Date does not fall on a Monday.";
            var dateOneMondayRuleNode = new RuleNode(dateOneMondayRule);

            // add the rangeRuleNode as an And child of dateOneMondayRuleNode
            dateOneMondayRuleNode.AndChild(groupNode);

            var tree = new RuleTree <CalendarEvent, DateTime>(dateOneMondayRuleNode);

            Assert.That(tree.LambdaExpression, Is.Not.Null);

            var context      = BuildContextForCalendarEventStartDate(testDate);
            var notification = new ValidationNotification();
            var isValid      = tree.LambdaExpression(context, null, notification);

            Assert.That(isValid, Is.EqualTo(validates));
        }
Ejemplo n.º 2
0
        public async override Task <bool> Passes()
        {
            var result = false;

            switch (Operator)
            {
            case CommonCore.Models.Enums.ComparisonOperatorEnum.LessThan:
            case CommonCore.Models.Enums.ComparisonOperatorEnum.LessThanOrEqualTo:
            case CommonCore.Models.Enums.ComparisonOperatorEnum.GreaterThanOrEqualTo:
            case CommonCore.Models.Enums.ComparisonOperatorEnum.GreaterThan:
                throw new System.Exception(NonApplicableOperatorMessage);

            case CommonCore.Models.Enums.ComparisonOperatorEnum.EqualTo:
                result = OwnValue == ComparisonValue;
                break;

            case CommonCore.Models.Enums.ComparisonOperatorEnum.NotEqualTo:
                result = OwnValue != ComparisonValue;
                break;

            default:
                result = OwnValue == ComparisonValue;
                break;
            }

            return(result && await RuleTree.PassesAnd(Children));
        }
Ejemplo n.º 3
0
        public void ItShouldReplaceOutputValue()
        {
            var filter = new Filter <int, bool>("{0} > {1}");

            filter.SetParameters(new List <IMonthlyParameter <int> > {
                SetDictionary("0", 10), SetDictionary("1", 1)
            });
            var concept = new Concept <int>();

            concept.AddFilter(filter);
            const string text      = "({0} * {1}) + ({2} * {3})";
            var          operation = new RuleTree <int, int>(text);

            operation.SetParameters(
                new List <IMonthlyParameter <int> > {
                SetDictionary("0", 2), SetDictionary("1", 3), SetDictionary("2", 2), SetDictionary("3", 5)
            });
            concept.AddOperation(operation);
            var output = SetDictionary("output", 25);

            concept.AddOutputParameter1(output);

            concept.Run();
            Assert.AreEqual(16, concept.Output1.Value[Month.May]);
            Assert.AreEqual(16, output.Value[Month.August]);
        }
 protected void btnViewCode_Click(object sender, EventArgs e)
 {
     viewCodeElem.Text   = RuleTree.GetCondition();
     titleElem.TitleText = GetString("macros.macrorule.viewcodeheader");
     pnlViewCode.Visible = true;
     mdlDialog.Visible   = true;
     mdlDialog.Show();
 }
Ejemplo n.º 5
0
        public void ItShouldvalidateWhenRulesAndOperation()
        {
            var rule = new RuleTree <int, int> {
                I         = new Mock <Rule <int, int> >().Object, J = new Mock <IRule <int, int> >().Object,
                Operation = new Mock <IOperation>().Object
            };

            Assert.IsTrue(rule.Validate());
        }
Ejemplo n.º 6
0
        public void ItShouldNotValidateWhenNoOperations()
        {
            var rule = new RuleTree <int, int>
            {
                I = new Mock <Rule <int, int> >().Object, J = new Mock <Rule <int, int> >().Object
            };

            Assert.Throws(typeof(RuleException), () => rule.Validate());
        }
Ejemplo n.º 7
0
        public async Task <RuleTree> CreateRuleTreeAsync(RulesDomain domain, RuleTreeSeed origin)
        {
            // TODO: Do all the work to help initialize the RuleTree

            var NewRuleTree = new RuleTree(origin);

            await _ruleTreeRepository.AddAsync(NewRuleTree).ConfigureAwait(false);

            return(new RuleTree(origin));
        }
Ejemplo n.º 8
0
        public void ItShouldParseExpression()
        {
            const string text = "( {0} + {1} ) * ( {2} * 1 )";

            var rule = new RuleTree <int, int>(text);

            var expression = rule.GetExpression();

            Assert.AreEqual("0", expression.Parameters[0].ToString());
            Assert.AreEqual("1", expression.Parameters[1].ToString());
            Assert.AreEqual(ExpressionType.Multiply, expression.Body.NodeType);
        }
Ejemplo n.º 9
0
        public void ItShouldGet30FromRule()
        {
            const string text = "( {0} / {1} ) + ({2} * 1)";

            var rule       = new RuleTree <int, int>(text);
            var parameters = new List <IMonthlyParameter <int> > {
                SetDictionary("0", 125), SetDictionary("1", 5), SetDictionary("2", 5)
            };

            rule.SetParameters(parameters);

            Assert.AreEqual(30, rule.GetResult().Value[Month.August]);
        }
Ejemplo n.º 10
0
        public void ItShouldGet15FromRule()
        {
            const string text = "( {0} + {1} ) * ( {2} * 1 )";

            var rule       = new RuleTree <int, int>(text);
            var parameters = new List <IMonthlyParameter <int> > {
                SetDictionary("0", 4), SetDictionary("1", 1), SetDictionary("2", 3)
            };

            rule.SetParameters(parameters);

            Assert.AreEqual(15, rule.GetResult().Value[Month.February]);
        }
Ejemplo n.º 11
0
        public void ItShouldParseComplexOperations()
        {
            const string text = "( {0} / 25 ) * 14";

            var rule       = new RuleTree <int, int>(text);
            var parameters = new List <IMonthlyParameter <int> > {
                SetDictionary("0", 250)
            };

            rule.SetParameters(parameters);

            Assert.AreEqual(140, rule.GetResult().Value[Month.February]);
        }
Ejemplo n.º 12
0
        public async Task <RuleTreeReport> ExecuteAsync(RuleTree targetRuleTree, RuleTreeRecord targetRecord)
        {
            // TODO: Do all the work to execute the RuleTree - and return a report?

            Random rnd    = new Random();
            var    Report = new RuleTreeReport(new RuleTreeSeed())
            {
                Id = rnd.Next()
            };

            // NOTE: To be determined where reports will be stored in the database, if at all
            // await _reportRepository.AddAsync(Report).ConfigureAwait(false);

            return(Report);
        }
Ejemplo n.º 13
0
        public async Task Passes_TwoStringComparsionValues_Or_PassesFalse()
        {
            RuleTree ruleTree = new RuleTree()
            {
                BaseNode = new OrRule()
                {
                    Children = new List <RuleNode>()
                    {
                        new GenericComparisonRule <string>("Joes", "Joe"),
                        new GenericComparisonRule <string>("Dog", "Dogs")
                    }
                }
            };

            Assert.False(await ruleTree.Passes());
        }
Ejemplo n.º 14
0
    protected void btnMove_Click(object sender, EventArgs e)
    {
        string[] parts = hdnParam.Value.Split(';');
        if (parts.Length == 3)
        {
            var sourcePath = parts[0];

            int plusOne = sourcePath.CompareToCSafe((string.IsNullOrEmpty(parts[1]) ? "" : parts[1] + ".") + parts[2]);
            plusOne = (plusOne < 0 ? 1 : 0);

            var targetPath = (parts[1] == pnlCondtion.ClientID) ? "" : parts[1];

            RuleTree.MoveNode(sourcePath, targetPath, ValidationHelper.GetInteger(parts[2], 0) + plusOne);

            // Clear selection
            hdnSelected.Value = ";";
        }
    }
Ejemplo n.º 15
0
        public void ItShouldAddValues()
        {
            var i = new Mock <IRule <int, int> >();
            var j = new Mock <IRule <int, int> >();

            i.Setup(x => x.GetResult()).Returns(SetDictionary("1", 1));
            j.Setup(x => x.GetResult()).Returns(SetDictionary("2", 2));
            var operation = new Mock <IOperation>();

            operation.Setup(x => x.GetOperator()).Returns(ExpressionType.Add);

            var rule = new RuleTree <int, int>
            {
                I         = i.Object,
                J         = j.Object,
                Operation = operation.Object
            };

            Assert.AreEqual(3, rule.GetResult().Value[Month.November]);
        }
    /// <summary>
    /// Adds a clause according to selected item.
    /// </summary>
    private void AddClause()
    {
        MacroRuleInfo rule = MacroRuleInfo.Provider.Get(ValidationHelper.GetInteger(lstRules.SelectedValue, 0));

        if (rule != null)
        {
            List <MacroRuleTree> selected = GetSelected();
            if (selected.Count == 1)
            {
                MacroRuleTree item = selected[0];
                if (item?.Parent != null)
                {
                    item.Parent.AddRule(rule, item.Position + 1);
                    return;
                }
            }

            // Add the rule at the root level, when no selected item
            RuleTree.AddRule(rule, RuleTree.Children.Count);
        }
    }
Ejemplo n.º 17
0
        public async override Task <bool> Passes()
        {
            bool result = false;

            if (ComparisonValue is T2 comparisonValue)
            {
                switch (Operator)
                {
                case ComparisonOperatorEnum.LessThan:
                    result = OwnValue.IsLessThan <T2>(comparisonValue);
                    break;

                case ComparisonOperatorEnum.LessThanOrEqualTo:
                    result = OwnValue.IsLessThanOrEqualTo <T2>(comparisonValue);
                    break;

                case ComparisonOperatorEnum.EqualTo:
                    result = OwnValue.IsEqualTo <T2>(comparisonValue);
                    break;

                case ComparisonOperatorEnum.GreaterThanOrEqualTo:
                    result = OwnValue.IsGreaterThanOrEqualTo <T2>(comparisonValue);
                    break;

                case ComparisonOperatorEnum.GreaterThan:
                    result = OwnValue.IsGreaterThan <T2>(comparisonValue);
                    break;

                case ComparisonOperatorEnum.NotEqualTo:
                    result = OwnValue.IsNotEqualTo <T2>(comparisonValue);
                    break;

                default:
                    result = OwnValue.IsEqualTo <T2>(comparisonValue);
                    break;
                }
            }
            return(result &&
                   await RuleTree.PassesAnd(Children));
        }
Ejemplo n.º 18
0
        public void ItShouldGetExpresionWhenvalidate()
        {
            var i = new Mock <IRule <int, int> >();
            var j = new Mock <IRule <int, int> >();

            i.Setup(x => x.GetResult()).Returns(SetDictionary("1", 1));
            j.Setup(x => x.GetResult()).Returns(SetDictionary("2", 2));
            var operation = new Mock <IOperation>();

            operation.Setup(x => x.GetOperator()).Returns(ExpressionType.Add);

            var rule = new RuleTree <int, int>
            {
                I         = i.Object,
                J         = j.Object,
                Operation = operation.Object
            };
            var expression = rule.GetExpression();

            Assert.IsNotNull(expression);
            Assert.AreEqual("0", expression.Parameters[0].ToString());
            Assert.AreEqual("1", expression.Parameters[1].ToString());
            Assert.AreEqual(ExpressionType.Add, expression.Body.NodeType);
        }
Ejemplo n.º 19
0
        public async override Task <bool> Passes()
        {
            var result = false;

            switch (Operator)
            {
            case CommonCore.Models.Enums.ComparisonOperatorEnum.LessThan:
                result = OwnValue < ComparisonValue;
                break;

            case CommonCore.Models.Enums.ComparisonOperatorEnum.LessThanOrEqualTo:
                result = OwnValue >= ComparisonValue;
                break;

            case CommonCore.Models.Enums.ComparisonOperatorEnum.EqualTo:
                result = OwnValue == ComparisonValue;
                break;

            case CommonCore.Models.Enums.ComparisonOperatorEnum.GreaterThanOrEqualTo:
                result = OwnValue >= ComparisonValue;
                break;

            case CommonCore.Models.Enums.ComparisonOperatorEnum.GreaterThan:
                result = OwnValue >= ComparisonValue;
                break;

            case CommonCore.Models.Enums.ComparisonOperatorEnum.NotEqualTo:
                result = OwnValue != ComparisonValue;
                break;

            default:
                result = OwnValue == ComparisonValue;
                break;
            }
            return(result && await RuleTree.PassesAnd(Children));
        }
 protected void btnAutoIndent_Click(object sender, EventArgs e)
 {
     MacroRuleTree.RemoveBrackets(RuleTree);
     RuleTree.AutoIndent();
 }
Ejemplo n.º 21
0
        public void ItShouldNotGetExpressionWhenNotValidate()
        {
            var rule = new RuleTree <int, int>();

            Assert.Throws(typeof(RuleException), () => rule.GetExpression());
        }
Ejemplo n.º 22
0
        public async Task PassesAnd_TwoStringComparsionValues_True()
        {
            var result = await RuleTree.PassesAnd(RuleTreeMockData.AndRuleTwoStringComparisonRules_BothMatch.BaseNode.Children);

            Assert.True(result);
        }
Ejemplo n.º 23
0
        public async Task PassesAnd_NoChildren_True()
        {
            var result = await RuleTree.PassesAnd <IRuleNode>(RuleTreeMockData.AndRuleNoChildren.Children);

            Assert.True(result);
        }
Ejemplo n.º 24
0
        public void ItShouldNotValidateWhenNoRules()
        {
            var rule = new RuleTree <int, int>();

            Assert.Throws(typeof(RuleException), () => rule.Validate());
        }
Ejemplo n.º 25
0
        public async Task PassesLimitNotAllPass_Theory(int matches, int nonMatches, int limit, bool expected)
        {
            var result = await RuleTree.PassesLimitNotAllPass(RuleTreeMockData.TwoStringComparisons_BothMatch, 1);

            Assert.False(result);
        }
Ejemplo n.º 26
0
        public async Task PassesOr_NoChildren_False()
        {
            var result = await RuleTree.PassesOr <IRuleNode>(RuleTreeMockData.AndRuleNoChildren.Children);

            Assert.False(result);
        }
 /// <summary>
 /// Returns the condition of the whole rule.
 /// </summary>
 public string GetCondition()
 {
     return(RuleTree.GetCondition());
 }
 /// <summary>
 /// Returns the XML of the designer.
 /// </summary>
 public string GetXML()
 {
     return(RuleTree.GetXML());
 }
Ejemplo n.º 29
0
        public bool SetupWorld()
        {
            const string rules = "Data\\rules.json";
            string       path  = Path.Combine(Directory.GetCurrentDirectory(), rules);

            List <AreaRuleInfo> areaRules = null;

            //maybe move this to file utils
            try
            {
                using (StreamReader sr = File.OpenText(path))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    areaRules = (List <AreaRuleInfo>)serializer.Deserialize(sr, typeof(List <AreaRuleInfo>));
                }
            }
            catch (Exception ex)
            {
                Logger.GetLogger.Log("Tried to deserialise rules.json, Error: {1}", ex.Message);
                return(false);
            }

            foreach (AreaRuleInfo info in areaRules)
            {
                Area area = new Area(info.areaName);

                //adding area locations to the area and world lists
                foreach (var l in info.locations)
                {
                    string[] locationInfo = l.Split(':');

                    if (locationInfo.Length == 2)
                    {
                        //this will get changed when more than just shop locations matter
                        LocationType locationType = LocationType.Default;
                        if (locationInfo[0].Contains("Shop"))
                        {
                            locationType = LocationType.Shop;
                        }

                        Location location = new Location(locationInfo[0], area, locationType);
                        location.ruleTree = RuleTree.ParseAndBuildRules(locationInfo[1]);
                        area.locations.Add(location);

                        if (!locations.ContainsKey(location.name))
                        {
                            locations.Add(location.name, location);
                        }
                        else
                        {
                            Logger.GetLogger.Log("Location already exists {0} in area {1}.", location.name, area.name);
                            return(false);
                        }
                    }
                    else
                    {
                        Logger.GetLogger.Log("Area {0} contains an invlaid location string: {1}", area.name, l);
                        return(false);
                    }
                }
                //adding area exits to the area and world lists
                foreach (var e in info.exits)
                {
                    string[] exitInfo = e.Split(':');

                    if (exitInfo.Length == 2)
                    {
                        Connection exit = new Connection(exitInfo[0], area);
                        exit.ruleTree = RuleTree.ParseAndBuildRules(exitInfo[1]);
                        area.exits.Add(exit);
                    }
                    else
                    {
                        Logger.GetLogger.Log("Area {0} contains an invlaid exit string: {1}", area.name, e);
                        return(false);
                    }
                }

                if (!areas.ContainsKey(area.name))
                {
                    areas.Add(area.name, area);
                }
                else
                {
                    Logger.GetLogger.Log("Area already exists {0}.", area.name);
                    return(false);
                }
            }

            //Add entrances to areas so that when we try to see if wee can reach an area when can check its entraces rules
            foreach (var area in areas)
            {
                foreach (var exit in area.Value.exits)
                {
                    Area connectingArea;
                    if (areas.TryGetValue(exit.connectingAreaName, out connectingArea))
                    {
                        exit.connectingArea = connectingArea;
                        connectingArea.entrances.Add(exit);
                    }
                    else
                    {
                        Logger.GetLogger.Log("Tried to add entrances to an area that doesn't exist {0}, from exit {1}", exit.connectingAreaName, exit.name);
                        return(false);
                    }
                }
            }

            return(true);
        }