Ejemplo n.º 1
0
        public override IRuleSet GetRuleSet(string propertyName, string datalist)
        {
            RuleSet ruleSet = new RuleSet();

            if (IsEmpty())
            {
                return(ruleSet);
            }
            switch (propertyName)
            {
            case "FieldName":
                if (FieldName.Length == 0)
                {
                    ruleSet.Add(new IsStringEmptyRule(() => FieldName));
                }
                break;

            case "ValueToMatch":
                if (ValueToMatch.Length == 0)
                {
                    ruleSet.Add(new IsStringEmptyRule(() => ValueToMatch));
                }
                ruleSet.Add(new IsValidExpressionRule(() => ValueToMatch, datalist, "1"));
                break;
            }

            return(ruleSet);
        }
        public string Fire(Unit target)
        {
            string result = string.Empty;

            RuleSet idealHitRules = new RuleSet();
            idealHitRules.Add(new UnderMaximumIdealRangeRule(this, target));
            idealHitRules.Add(new OverMinimumIdealRangeRule(this, target));

            RuleSet regularHitRules = new RuleSet();
            regularHitRules.Add(new UnderMaximumRangeRule(this, target));
            regularHitRules.Add(new OverMinimumRangeRule(this, target));

            //Fire!
            if (idealHitRules.Validate())
            {
                result = "Ideal hit!";
            }
            else if (regularHitRules.Validate())
            {
                result = "Hit.";
            }
            else
            {
                result = regularHitRules.FailureMessages[0];
            }

            return result;
        }
Ejemplo n.º 3
0
        public override IRuleSet GetRuleSet(string propertyName, string datalist)
        {
            var ruleSet = new RuleSet();

            if (IsEmpty())
            {
                return(ruleSet);
            }

            switch (propertyName)
            {
            case "FieldName":
                ruleSet.Add(new IsStringEmptyRule(() => FieldName));
                ruleSet.Add(new IsValidExpressionRule(() => FieldName, datalist, "1"));
                break;

            case "FieldValue":
                ruleSet.Add(new IsValidExpressionRule(() => FieldValue, datalist, "1"));
                break;

            case "FieldValueAndCalculate":
                ruleSet.Add(new ComposableRule <string>(new IsValidExpressionRule(() => FieldValue, datalist, "1")).Or(new IsValidCalculateRule(() => FieldValue)));
                break;
            }
            return(ruleSet);
        }
Ejemplo n.º 4
0
        RuleSet Chomskey5_Terminals(RuleSet rs, List<char> newVars) {
            var newRs = new RuleSet();
            var translate = new Dictionary<char, char>();

            foreach (var r in rs) {
                var newVals = new List<string>(r.Value.Length);
                foreach (string ibody in r.Value) {
                    string newBody = ibody;
                    if (ibody.Length == 2) {

                        var c2Replaces = new List<char>();
                        if (Terminals.Contains(newBody[0]))
                            c2Replaces.Add(newBody[0]);
                        if (Terminals.Contains(newBody[1]))
                            c2Replaces.Add(newBody[1]);

                        foreach (var c2Replace in c2Replaces) {
                            if (translate.TryGetValue(c2Replace, out char nl)) { } else {
                                nl = Utils.NextFreeCapitalLetter(newVars.Union(Terminals).ToArray(), c2Replace.ToString().ToUpper()[0]);
                                newVars.Add(nl);
                                translate.Add(c2Replace, nl);
                            }
                            newBody = newBody.Replace(c2Replace, nl);
                        }
                    } //end if body.Length = 2
                    newVals.Add(newBody);
                } //next body
                newRs.Add(r.Key, newVals.ToArray());
            } //next r

            foreach (var la in translate)
                newRs.Add(la.Value, new string[] { la.Key.ToString() });

            return newRs;
        } //end function
        protected virtual string ValidatePath(string label, string path, Action onError, bool pathIsRequired)
        {
            if (!pathIsRequired && string.IsNullOrWhiteSpace(path))
            {
                return(string.Empty);
            }

            var errors = new List <IActionableErrorInfo>();

            RuleSet fileActivityRuleSet = new RuleSet();
            IsValidExpressionRule isValidExpressionRule = new IsValidExpressionRule(() => path, DataListSingleton.ActiveDataList.Resource.DataList);

            fileActivityRuleSet.Add(isValidExpressionRule);
            errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError));


            string pathValue;

            path.TryParseVariables(out pathValue, onError, variableValue: ValidUriSchemes[0] + "://temp");

            if (errors.Count == 0)
            {
                IsStringEmptyOrWhiteSpaceRule isStringEmptyOrWhiteSpaceRuleUserName = new IsStringEmptyOrWhiteSpaceRule(() => path)
                {
                    LabelText = label,
                    DoError   = onError
                };

                fileActivityRuleSet.Add(isStringEmptyOrWhiteSpaceRuleUserName);
                errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError));

                var pathBlankError = isStringEmptyOrWhiteSpaceRuleUserName.Check();
                if (pathBlankError != null)
                {
                    errors.Add(new ActionableErrorInfo(onError)
                    {
                        ErrorType = ErrorType.Critical, Message = label + " must have a value"
                    });
                }
                else
                {
                    Uri uriResult;
                    var isValid = Uri.TryCreate(pathValue, UriKind.Absolute, out uriResult)
                            ? ValidUriSchemes.Contains(uriResult.Scheme)
                            : File.Exists(pathValue);

                    if (!isValid)
                    {
                        errors.Add(new ActionableErrorInfo(onError)
                        {
                            ErrorType = ErrorType.Critical, Message = "Please supply a valid " + label
                        });
                    }
                }
            }

            UpdateErrors(errors);
            return(pathValue);
        }
Ejemplo n.º 6
0
        public CFGrammer KleeneStern() {
            var newRules = new RuleSet();

            char newStart = Utils.NextFreeCapitalLetter(this.VarAndTerm, this.StartSymbol);

            newRules.Add(newStart, new string[] { this.StartSymbol.ToString(), "", $"{this.StartSymbol}{newStart}" });

            foreach (var r in this.Rules) {
                newRules.Add(r.Key, r.Value);
            }
            return new CFGrammer($"CFG_KleeneStern({Name})-", this.Variables.Append(newStart).ToArray(), this.Terminals, newRules, newStart);
        }
Ejemplo n.º 7
0
        public void EvaluateTest(int inputValue, bool expectedHasError, string expectedError)
        {
            var set = new RuleSet <int>();

            set.Add(new Rule <int>(@int => @int > 0, "Error 1"));
            set.Add(new Rule <int>(@int => @int <= 10, "Error 2"));
            set.Evaluate(inputValue);
            Assert.AreEqual(expectedHasError, set.HasError);
            if (expectedHasError)
            {
                Assert.That(set.Errors, Has.Exactly(1).EqualTo(expectedError));
            }
        }
Ejemplo n.º 8
0
        public void RuleSetRerunTest()
        {
            int calls = 0;
            var rule  = new Rule <int>(number => {
                calls++;
                return(number == 10);
            }, "Error");
            var set = new RuleSet <int>();

            set.Add(rule);
            set.Evaluate(10);
            Assert.False(set.HasError);
            Assert.AreEqual(1, calls);

            for (int i = 0; i < 100; i++)
            {
                set.Evaluate(15);
                Assert.False(set.HasError);
            }
            Assert.AreEqual(1, calls);

            set.Reset();
            set.Evaluate(15);
            Assert.True(set.HasError);
            Assert.AreEqual(2, calls);
        }
Ejemplo n.º 9
0
        public void TestAddAndGetEnumeratorFor()
        {
            var first  = new RuleGeneric(new[] { 1 }, Reason.JobInstall, null);
            var second = new RuleGeneric(new[] { 2 }, Reason.JobInstall, null);
            var third  = new RuleGeneric(Array.Empty <int>(), Reason.InternalAllowUpdate, null);

            var ruleSet = new RuleSet();

            ruleSet.Add(first, RuleType.Job);
            ruleSet.Add(third, RuleType.Learned);
            ruleSet.Add(second, RuleType.Job);

            Assert.AreEqual(3, ruleSet.Count);
            CollectionAssert.AreEqual(new[] { first, second }, ruleSet.GetEnumeratorFor(RuleType.Job).ToArray());
            CollectionAssert.AreEqual(new[] { third }, ruleSet.GetEnumeratorFor(RuleType.Learned).ToArray());
        }
Ejemplo n.º 10
0
        public void RuleRepositoryExtension_Compile_CancellationRequested()
        {
            using (var cancellationSource = new CancellationTokenSource())
            {
                // Arrange
                var ruleCompiler = new RuleCompiler();

                var rule1 = CreateRuleDefinitionMock();
                var rule2 = CreateRuleDefinitionMock();
                rule2.Setup(r => r.LeftHandSide).Returns(() =>
                {
                    cancellationSource.Cancel();
                    return(new AndElement(Enumerable.Empty <RuleElement>()));
                });

                var rule3 = CreateRuleDefinitionMock();
                var rules = new RuleSet("R1");
                rules.Add(new[] { rule1.Object, rule2.Object, rule3.Object });

                var ruleRepository = new RuleRepository();
                ruleRepository.Add(rules);

                // Act
                ruleRepository.Compile(cancellationSource.Token);

                // Assert
                rule1.Verify(r => r.LeftHandSide, Times.AtLeastOnce);
                rule2.Verify(r => r.LeftHandSide, Times.AtLeastOnce);
                rule3.Verify(r => r.LeftHandSide, Times.Never);
            }
        }
        private IRuleSet GetRuleSet(string propertyName)
        {
            var ruleSet = new RuleSet();

            switch (propertyName)
            {
            case "RabbitMQSource":
                ruleSet.Add(new IsNullRule(() => SelectedRabbitMQSource));
                break;

            case "QueueName":
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => QueueName));
                break;
            }
            return(ruleSet);
        }
Ejemplo n.º 12
0
        public void TestRuleById()
        {
            var first  = new RuleGeneric(new[] { 1 }, Reason.JobInstall, null);
            var second = new RuleGeneric(new[] { 2 }, Reason.JobInstall, null);
            var third  = new RuleGeneric(Array.Empty <int>(), Reason.InternalAllowUpdate, null);

            var ruleSet = new RuleSet();

            ruleSet.Add(first, RuleType.Job);
            ruleSet.Add(third, RuleType.Learned);
            ruleSet.Add(second, RuleType.Job);

            Assert.AreEqual(first, ruleSet.GetRuleById(0));
            Assert.AreEqual(third, ruleSet.GetRuleById(1));
            Assert.AreEqual(second, ruleSet.GetRuleById(2));
        }
Ejemplo n.º 13
0
        public void TestAddIgnoresDuplicates()
        {
            var first  = new RuleGeneric(new[] { 1 }, Reason.JobInstall, null);
            var second = new RuleGeneric(new[] { 1 }, Reason.JobInstall, null);
            var third  = new RuleGeneric(new[] { 1 }, Reason.JobInstall, null);

            var ruleSet = new RuleSet();

            ruleSet.Add(first, RuleType.Job);
            Assert.IsFalse(ruleSet.Add(second, RuleType.Job));
            Assert.IsFalse(ruleSet.Add(third, RuleType.Job));

            Assert.AreEqual(1, ruleSet.Count);
            CollectionAssert.AreEqual(new[] { first }, ruleSet.GetEnumeratorFor(RuleType.Job).ToArray());
            CollectionAssert.AreEqual(Array.Empty <Rule>(), ruleSet.GetEnumeratorFor(RuleType.Learned).ToArray());
        }
Ejemplo n.º 14
0
        public void HasRulesTest()
        {
            var set = new RuleSet <int>();

            Assert.False(set.HasRules);
            set.Add(new Rule <int>(@int => @int == 10, "Error"));
            Assert.True(set.HasRules);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Length <= 2, introduce new Var for all |body|>2
        /// </summary>
        RuleSet Chomskey4_Length(RuleSet rs, List<char> newVars) {
            var newRs = new RuleSet();
            var translate = new Dictionary<string, char>();

            foreach (var r in rs) {
                var newVals = new List<string>(r.Value.Length);
                foreach (string orgbody in r.Value) {
                    string newbody = orgbody;

                    // translate every new word, with all existing translations
                    foreach (var t in translate) {
                        var oldbody = newbody;
                        if (newbody.Length > 2)
                            // FIX: replace should start right
                            newbody = newbody.Replace(t.Key, t.Value.ToString());
                        else
                            break;

                        // body gets to small, Var only
                        if (newbody.Length == 1 && newVars.Contains(newbody[0]))
                            newbody = oldbody;
                    }


                    while (newbody.Length > 2) {
                        var replacePart = newbody.Substring(newbody.Length - 2, 2);

                        if (!translate.TryGetValue(replacePart, out char nL)) {
                            nL = Utils.NextFreeCapitalLetter(newVars.Union(Terminals).ToArray(), 'X');
                            newVars.Add(nL);
                            translate.Add(replacePart, nL);
                        }
                        // FIX: replace should start right
                        newbody = newbody.Replace(replacePart, nL.ToString());
                    }
                    newVals.Add(newbody);
                }
                newRs.Add(r.Key, newVals.ToArray());
            }

            foreach (var la in translate)
                newRs.Add(la.Value, new string[] { la.Key });

            return newRs;
        }
Ejemplo n.º 16
0
        public void ReturnOnlyRuleIfMatchFound()
        {
            var ruleSet = new RuleSet();

            ruleSet.Add(new SingleDieRule(1, 100));
            var result = ruleSet.BestRule(new int[] { 1, 2, 3 });

            Assert.IsInstanceOf <SingleDieRule>(result);
        }
Ejemplo n.º 17
0
        public void RuleSet_AddRule_Null_ExceptionThrown()
        {
            //------------Setup for test--------------------------
            var ruleSet = new RuleSet();

            //------------Execute Test---------------------------
            ruleSet.Add(null);
            //------------Assert Results-------------------------
        }
Ejemplo n.º 18
0
        private static IRuleSet GetRuleSet(RuleSets propertyName, RedisDesignerDTO redisDesignerDTO)
        {
            var ruleSet = new RuleSet();

            switch (propertyName)
            {
            case RuleSets.RedisSource:
                ruleSet.Add(new IsNullRule(() => redisDesignerDTO.RedisSource));
                break;

            case RuleSets.Key:
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => redisDesignerDTO.Key));
                break;

            default:
                break;
            }
            return(ruleSet);
        }
Ejemplo n.º 19
0
        protected virtual string ValidatePath(string label, string path, Action onError, bool pathIsRequired)
        {
            if (!pathIsRequired && string.IsNullOrWhiteSpace(path))
            {
                return(string.Empty);
            }

            var errors = new List <IActionableErrorInfo>();

            RuleSet fileActivityRuleSet = new RuleSet();
            IsValidExpressionRule isValidExpressionRule = new IsValidExpressionRule(() => path, DataListSingleton.ActiveDataList.Resource.DataList);

            fileActivityRuleSet.Add(isValidExpressionRule);
            errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError));


            string pathValue;

            path.TryParseVariables(out pathValue, onError, variableValue: ValidUriSchemes[0] + "://temp");

            if (errors.Count == 0)
            {
                IsStringEmptyOrWhiteSpaceRule isStringEmptyOrWhiteSpaceRuleUserName = new IsStringEmptyOrWhiteSpaceRule(() => path)
                {
                    LabelText = label,
                    DoError   = onError
                };

                IsValidFileNameRule isValidFileNameRule = new IsValidFileNameRule(() => path)
                {
                    LabelText = label,
                    DoError   = onError
                };

                fileActivityRuleSet.Add(isStringEmptyOrWhiteSpaceRuleUserName);
                fileActivityRuleSet.Add(isValidExpressionRule);

                errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError));
            }

            UpdateErrors(errors);
            return(pathValue);
        }
Ejemplo n.º 20
0
        public override IRuleSet GetRuleSet(string propertyName, string datalist)
        {
            RuleSet ruleSet = new RuleSet();

            if (String.IsNullOrEmpty(SourceName))
            {
                return(ruleSet);
            }
            if (propertyName == "SourceName")
            {
                ruleSet.Add(new IsValidJsonCreateMappingSourceExpression(() => SourceName));
            }
            if (propertyName == "DestinationName")
            {
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => DestinationName));
                ruleSet.Add(new ShouldNotBeVariableRule(() => DestinationName));
            }
            return(ruleSet);
        }
Ejemplo n.º 21
0
        public void RuleSet_AddRule_Rule_AddsToRuleList()
        {
            //------------Setup for test--------------------------
            var ruleSet = new RuleSet();

            //------------Execute Test---------------------------
            ruleSet.Add(new TestRule("Value"));
            //------------Assert Results-------------------------
            Assert.AreEqual(1, ruleSet.Rules.Count);
        }
Ejemplo n.º 22
0
        public void TestCount()
        {
            var first = new RuleGeneric(new[] { 1 }, Reason.JobInstall, null);

            var ruleSet = new RuleSet();

            ruleSet.Add(first, RuleType.Job);

            Assert.AreEqual(1, ruleSet.Count);
        }
Ejemplo n.º 23
0
        private IRuleSet GetRuleSet(string propertyName)
        {
            var ruleSet = new RuleSet();

            switch (propertyName)
            {
            case "DisplayText":
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => DisplayText));
                break;

            case "TrueArmText":
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => TrueArmText));
                break;

            case "FalseArmText":
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => FalseArmText));
                break;
            }
            return(ruleSet);
        }
Ejemplo n.º 24
0
        IRuleSet GetRuleSet(string propertyName)
        {
            var ruleSet = new RuleSet();

            switch (propertyName)
            {
            case "SourceString":
                if (!string.IsNullOrEmpty(SourceString) && !string.IsNullOrWhiteSpace(SourceString))
                {
                    var inputExprRule = new IsValidExpressionRule(() => SourceString, GetDatalistString(), "1");
                    ruleSet.Add(inputExprRule);
                }
                else
                {
                    ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => SourceString));
                }
                break;
            }
            return(ruleSet);
        }
        IRuleSet GetRuleSet(string propertyName)
        {
            var ruleSet = new RuleSet();

            switch (propertyName)
            {
            case "SourceString":
                ruleSet.Add(new IsStringEmptyOrWhiteSpaceRule(() => SourceString));

                if (!string.IsNullOrEmpty(SourceString) && !DataListUtil.IsEvaluated(SourceString))
                {
                    ruleSet.Add(new IsValidXmlRule(() => SourceString));
                }

                var outputExprRule = new IsValidExpressionRule(() => SourceString, GetDatalistString(), "1");
                ruleSet.Add(outputExprRule);

                break;
            }
            return(ruleSet);
        }
Ejemplo n.º 26
0
        public void RuleSet_Validate_WithNullRule_ReturnsValueOfCheck()
        {
            //------------Setup for test--------------------------
            var ruleSet = new RuleSet();

            ruleSet.Add(new TestRule("value", null));
            //------------Execute Test---------------------------
            var validateRules = ruleSet.ValidateRules();

            //------------Assert Results-------------------------
            Assert.AreEqual(0, validateRules.Count);
        }
        public IRuleSet GetRuleSet(string propertyName, string datalist)
        {
            var ruleSet = new RuleSet();

            switch (propertyName)
            {
            case "InputColumn":
                ruleSet.Add(new IsValidExpressionRule(() => datalist, GetDatalistString(), "1"));
                break;
            }
            return(ruleSet);
        }
        public void RuleSetFailure()
        {
            //Assemble
            RuleSet rules = new RuleSet();
            rules.Add(new StringMatchRule() { string1 = "Two", string2 = "Hats" });

            //Act
            bool success = rules.Validate();

            //Assert
            Assert.IsFalse(success, "No match should exist");
            Assert.IsNotEmpty(rules.FailureMessages, "There should not be any FailureMessages");
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Chomskey Transformation 1, Remove all StartSymbols on right side
        /// </summary>
        /// <param name="rs">Old RuleSet</param>
        /// <param name="newVars">Reference to new Variables</param>
        /// <returns>CNF Step 1</returns>
        RuleSet Chomskey1_StartSymbol(RuleSet rs, List<char> newVars) {
            var newRS = new RuleSet();

            char? newStartSymbol = null;

            // check all rules for startbody
            foreach (var r in rs)
                foreach (string body in r.Value) {
                    if (body.Contains(StartSymbol)) {
                        //get new Symbol, ONCE
                        if (!newStartSymbol.HasValue) {
                            newStartSymbol = Utils.NextFreeCapitalLetter(newVars.Union(Terminals).ToArray(), StartSymbol);
                            newVars.Add(newStartSymbol.Value);
                            break;
                        }
                    }
                }

            // no symbol found, return old and exit
            if (!newStartSymbol.HasValue)
                return rs;

            // first add new startsymbole
            newRS.Add(StartSymbol, new string[] { newStartSymbol.Value.ToString() });


            // iterate rules and replace S->S'
            foreach (var r in rs) {
                char newrKey = r.Key != StartSymbol ? r.Key : newStartSymbol.Value;
                var valList = new List<string>(r.Value.Length);

                foreach (string body in r.Value)
                    valList.Add(body.Replace(StartSymbol, newStartSymbol.Value));

                newRS.Add(newrKey, valList.ToArray());
            }

            return newRS;
        }
        public void RuleSetSuccess()
        {
            //Assemble
            RuleSet rules = new RuleSet();
            rules.Add(new StringMatchRule(){ string1 = "One", string2 = "One" });

            //Act
            bool success = rules.Validate();

            //Assert
            Assert.IsTrue(success, "Strings did not match");
            Assert.IsEmpty(rules.FailureMessages, "There should not be any FailureMessages");
        }
Ejemplo n.º 31
0
        protected virtual string ValidateArchivePassword(string password, string label, Action onError, bool contentIsRequired = true)
        {
            var     errors = new List <IActionableErrorInfo>();
            RuleSet fileActivityRuleSet = new RuleSet();

            IsValidExpressionRule isValidExpressionRule = new IsValidExpressionRule(() => password, DataListSingleton.ActiveDataList.Resource.DataList);

            fileActivityRuleSet.Add(isValidExpressionRule);
            errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError));

            UpdateErrors(errors);
            return(password);
        }
Ejemplo n.º 32
0
        public static CFGrammer GenerateRandom(bool removeUnused = true) {
            var rnd = Uni.Utils.RND;
            const byte MAX_CHAR = 10;
            const byte MAX_VAR = 5;
            const byte MAX_RUL = 5;
            const byte MAX_WLEN = 5;
            const byte MAX_BODY = 5;

            var rs = new RuleSet();
            var Vars = new char[rnd.Next(1, MAX_VAR)];
            for (int i = 0; i < Vars.Length; i++)
                Vars[i] = (char)(rnd.Next((int)'A', (int)'Z'));

            var Terms = new char[rnd.Next(1, MAX_CHAR)];
            for (int i = 0; i < Terms.Length; i++)
                Terms[i] = (char)(rnd.Next((int)'a', (int)'z'));

            Vars = Vars.Distinct().OrderBy(s => s).ToArray();
            Terms = Terms.Distinct().OrderBy(s => s).ToArray();

            int rulesCount = rnd.Next(1, MAX_RUL);

            for (int i = 0; i < Math.Min(rulesCount, Vars.Length); i++) {
                char rKey = Vars[rnd.Next(0, Vars.Length)];
                var Vals = new string[rnd.Next(1, MAX_BODY)];
                for (int j = 0; j < Vals.Length; j++) {
                    string w = "";
                    var wLen = rnd.Next(0, MAX_WLEN);
                    for (int k = 0; k < wLen; k++) {
                        if (rnd.NextDouble() > 0.7)
                            w = w.Insert(k, Terms.RndElement().ToString());
                        else
                            w = w.Insert(k, Vars.RndElement().ToString());
                    }
                    Vals[j] = w;
                }

                if (!rs.ContainsKey(rKey))
                    rs.Add(rKey, Vals.Distinct().OrderBy(s => s).ToArray());
                else
                    rs[rKey] = Enumerable.Concat(rs[rKey], Vals).Distinct().OrderBy(s => s).ToArray();
            }

            var headVars = (from r in rs select r.Key).Distinct().ToArray();

            var varList = new List<char>(Vars);
            if (removeUnused)
                rs = rs.RemoveUnusedSymbols(varList, Terms);

            return new CFGrammer("CFG_Random", varList.ToArray(), Terms, rs, headVars.RndElement());
        }
Ejemplo n.º 33
0
        public void ActivityDTO_Validate_Executed_SetErrorsProperty()
        {
            //------------Setup for test--------------------------
            var activityDTO = new ActivityDTO {
                FieldName = null
            };
            var ruleSet = new RuleSet();

            ruleSet.Add(new IsNullRule(() => activityDTO.FieldName));
            //------------Execute Test---------------------------
            activityDTO.Validate("FieldName", ruleSet);
            //------------Assert Results-------------------------
            Assert.AreEqual(1, activityDTO.Errors.Count);
        }
Ejemplo n.º 34
0
        public void LoadRuleSet(Action<IEnumerable<RuleSet>, Exception> onComplete)
        {
            var list = new List<RuleSet>();

            var ruleSet = new RuleSet() { Name = "Default" };

            ruleSet.Add(new FileStructureRule()
            {
                IsEnabled = true,
                Name = "Check File Structure",
                Description = "Check file structure with template. ",
                Template = "default.txt"
            });
            ruleSet.Add(new OutputPathRule()
            {
                IsEnabled = true,
                Path = "./output/$(Configuration)/",
                Name = "Check Build Output Path",
                Description = "Check output path for all project files (*.csproj). "
            });

            ruleSet.Add(new CodeAnalysisRule()
            {
                IsEnabled = true,
                Name = "Run Code Analysis",
                Description = "Run code analysis with InspectCode. "
            });

            list.Add(ruleSet);

            if (onComplete != null)
            {
                onComplete.Invoke(list, null);
            }
            //throw new NotImplementedException();
        }
        public void PassMaxIdealRangeTest()
        {
            //Assemble
            Unit unit1 = new Unit() { MaximumIdealRange = 10, XCoordinate = 0, YCoordinate = 0 };
            Unit unit2 = new Unit() { MaximumIdealRange = 10, XCoordinate = 0, YCoordinate = 5 };

            RuleSet rules = new RuleSet();
            rules.Add(new UnderMaximumIdealRangeRule(unit1, unit2));

            //Act
            bool success = rules.Validate();

            //Assert
            Assert.IsTrue(success, "Unit should be inside of max ideal range");
        }
        public void FailMaxRangeTest()
        {
            //Assemble
            Unit unit1 = new Unit() { MaximumRange = 10, XCoordinate = 0, YCoordinate = 0 };
            Unit unit2 = new Unit() { MaximumRange = 10, XCoordinate = 0, YCoordinate = 500 };

            RuleSet rules = new RuleSet();
            rules.Add(new UnderMaximumRangeRule(unit1, unit2));

            //Act
            bool success = rules.Validate();

            //Assert
            Assert.IsFalse(success, "Unit should be outside of max range");
        }
        public void FailMinIdealRangeTest()
        {
            //Assemble
            Unit unit1 = new Unit() { MinimumIdealRange = 10, XCoordinate = 0, YCoordinate = 0 };
            Unit unit2 = new Unit() { MinimumIdealRange = 10, XCoordinate = 0, YCoordinate = 5 };

            RuleSet rules = new RuleSet();
            rules.Add(new OverMinimumIdealRangeRule(unit1, unit2));

            //Act
            bool success = rules.Validate();

            //Assert
            Assert.IsFalse(success, "Unit should be inside of min ideal range");
        }
Ejemplo n.º 38
0
        public static void TestEngine()
        {
            TagReplacementWatchers watchers;
              DataLookupTag dlt;
              Rule rule;
              RuleSet rules = new RuleSet();

              rule = new Rule("root");
              rule.Priority = 2; rule.MinPriority = 1;
              rule.Output = new Content();
              rule.Output.Add("Hello. ");
              rule.Output.Add(new Tag("cats"));
              rule.Expression = Expression.Parse("value? 2 >=");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("cats");
              rule.Output = new Content();
              dlt = new DataLookupTag("value");
              dlt.AddWatcher(new CardinalFilter());
              rule.Output.Add(dlt);
              rule.Output.Add(" (");
              rule.Output.Add(new DataLookupTag("value"));
              rule.Output.Add(") cat");
              dlt = new DataLookupTag("value");
              dlt.AddWatcher(new PluraliseFilter());
              rule.Output.Add(dlt);
              rule.Output.Add(" in a bag, here is the ");
              dlt = new DataLookupTag("value");
              dlt.AddWatcher(new OrdinalFilter());
              rule.Output.Add(dlt);
              rule.Output.Add(" (");
              dlt = new DataLookupTag("value");
              dlt.AddWatcher(new OrdinalSuffixFilter());
              rule.Output.Add(dlt);
              rule.Output.Add(")");
              rule.AddWatcher(new SentenceFilter());
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("root");
              rule.Frequency = 2;
              rule.Output = new Content();
              rule.Output.Add("Hi ");
              watchers = new TagReplacementWatchers();
              watchers.Add(new AsClause("name"));
              rule.Output.Add(new Tag("nickname", watchers));
              rule.Output.Add("! Do you mind if I call you '");
              rule.Output.Add(new DataLookupTag("name"));
              rule.Output.Add("'?");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("nickname");
              rule.Output = new Content();
              rule.Output.Add("mate");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("nickname");
              rule.Output = new Content();
              rule.Output.Add("buddy");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("nickname");
              rule.Output = new Content();
              rule.Output.Add("dude");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("nickname");
              rule.Output = new Content();
              rule.Output.Add("man");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              rule = new Rule("nickname");
              rule.Output = new Content();
              rule.Output.Add("friendo");
              rules.Add(rule);
              Console.WriteLine(rule.ToString());

              Engine engine = new Engine(rules);
              Namespace data = new Namespace();
              data.Set("value", 2);
              string result = engine.Run("root", data);

              Console.WriteLine("........................................................................");
              Console.WriteLine(result);
              Console.WriteLine("........................................................................");
              Console.WriteLine("Final data:");
              Console.WriteLine(data.ToString("  "));
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Program entry point.
        /// </summary>
        /// <example>
        /// -r "f:\_E_\SolutionTool" -t default.xml -b "./output/$(Configuration)/" -i "f:\_E_\jb-cl\inspectcode.exe" -l slntool.log
        /// </example>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Debug.Listeners.Add(new ConsoleTraceListener());

            var options = new Options();
            var parser = new Parser();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            Console.WriteLine("Begin checking " + options.Repository);

            var pathOfRepository = Path.GetFullPath(options.Repository);
            var pathOfTemplate = Path.GetFullPath(options.Template);

            if (!Directory.Exists(pathOfRepository))
            {
                Console.WriteLine("Repository directory does not exist: [" + options.Repository + "]");
            }
            if (!File.Exists(pathOfTemplate))
            {
                Console.WriteLine("Template File does not exist: [" + options.Repository + "]");
            }
            else
            {
                var di = new DirectoryInfo(pathOfRepository);
                var fi = new DirectoryInfo(pathOfTemplate);
                var project = new Project { Name = di.Name, Path = pathOfRepository, CreateTime = DateTime.Now, };
                var ruleSet = new RuleSet
                {
                    new FileStructureRule
                    {
                        Name = "File Structure Rule",
                        IsEnabled = true,
                        Template = fi.Name,
                    },
                    new OutputPathRule
                    {
                        Name = "Output Path Rule",
                        IsEnabled = true,
                        Path = options.OutputBuildPath,
                    },
                };

                if (!string.IsNullOrWhiteSpace(options.InspectCodeExePath))
                {
                    ruleSet.Add(new CodeAnalysisRule
                    {
                        Name = "Code Analysis Rule",
                        IsEnabled = true,
                        Path = options.InspectCodeExePath,
                    });
                }

                var ruleRunner = new RuleRunner();

                project.RuleSet = ruleSet;
                ruleRunner.RunProject(project, (report,log) =>
                {
                    if (report != null)
                    {
                        Console.WriteLine(report.GetText());
                    }

                    if (!string.IsNullOrWhiteSpace(options.LogFile))
                    {
                        var logFile = Path.GetFullPath(options.LogFile);

                        using (var sw = File.AppendText(logFile))
                        {
                            sw.Write(report.GetText());
                        }
                    }
                });
            }

            Console.WriteLine("Checking is done. ");

            Console.ReadKey();
        }