public void FalseScalarExpression()
        {
            Inventor tesla = new Inventor();
            tesla.Name = "Soltan Gris";

            ConditionValidator validator = new ConditionValidator(Expression.Parse("Name == 'Nikola Tesla'"), null);
            validator.Actions = new ErrorMessageAction[] {new ErrorMessageAction("Wrong name", "InventorValidator") };
            IValidationErrors errors = new ValidationErrors();
            Assert.IsFalse(validator.Validate(tesla, errors));
            Assert.IsFalse(errors.IsEmpty);
            IList<string> namedErrors = errors.GetResolvedErrors("InventorValidator", new NullMessageSource());
            Assert.AreEqual(1, namedErrors.Count);
            string error = (string) namedErrors[0];
            Assert.AreEqual("Wrong name", error);
        }
Exemplo n.º 2
0
    static int ValidateRoleAllTrainingQuality(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        ConditionValidator obj  = (ConditionValidator)LuaScriptMgr.GetNetObjectSelf(L, 1, "ConditionValidator");
        string             arg0 = LuaScriptMgr.GetLuaString(L, 2);
        bool o = obj.ValidateRoleAllTrainingQuality(arg0);

        LuaScriptMgr.Push(L, o);
        return(1);
    }
        public void TrueScalarExpression()
        {
            Inventor tesla = new Inventor();

            tesla.Name = "Nikola Tesla";

            ConditionValidator validator = new ConditionValidator(Expression.Parse("Name == 'Nikola Tesla'"), null);

            Assert.IsTrue(validator.Validate(tesla, new ValidationErrors()));
        }
Exemplo n.º 4
0
    static int ValidateBadgeSlotEquiped(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        ConditionValidator obj  = (ConditionValidator)LuaScriptMgr.GetNetObjectSelf(L, 1, "ConditionValidator");
        string             arg0 = LuaScriptMgr.GetLuaString(L, 2);
        bool o = obj.ValidateBadgeSlotEquiped(arg0);

        LuaScriptMgr.Push(L, o);
        return(1);
    }
Exemplo n.º 5
0
        public static ConditionValidator <T> MyExtension <T>(
            this ConditionValidator <T> validator, IEnumerable <T> collection)
        {
            if (collection == null || !collection.Contains(validator.Value))
            {
                validator.ThrowException(validator.ArgumentName + " should be in the supplied collection");
            }

            return(validator);
        }
Exemplo n.º 6
0
    static int ValidateGuideModuleComplete(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        ConditionValidator obj  = (ConditionValidator)LuaScriptMgr.GetNetObjectSelf(L, 1, "ConditionValidator");
        string             arg0 = LuaScriptMgr.GetLuaString(L, 2);
        bool o = obj.ValidateGuideModuleComplete(arg0);

        LuaScriptMgr.Push(L, o);
        return(1);
    }
Exemplo n.º 7
0
 public MdFluentBuilder(string template, string fileName, MarkDownType type)
 {
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((string.IsNullOrWhiteSpace(template)),
                                                                         nameof(template));
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((string.IsNullOrWhiteSpace(fileName)),
                                                                         nameof(fileName));
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((type == null),
                                                                         nameof(type));
     Template = template;
     FileName = fileName;
     Type     = type;
 }
        public void WhenValidatorIsNotEvaluatedBecauseWhenExpressionReturnsFalse()
        {
            ConditionValidator validator = new ConditionValidator();
            validator.Test = Expression.Parse("false");
            validator.When = Expression.Parse("false");
            IValidationErrors errors = new ValidationErrors();

            bool valid = validator.Validate(new object(), null, errors);

            Assert.IsTrue(valid, "Validation should succeed when condition validator is not evaluated.");
            Assert.AreEqual(0, errors.GetErrors("errors").Count);
        }
Exemplo n.º 9
0
        public void ValidateSetsDefaultVariables()
        {
            TestPage        page = new TestPage(HttpContext.Current);
            TestUserControl c1   = new TestUserControl();

            page.Controls.Add(c1);

            ConditionValidator v1 = new ConditionValidator("#page == #this.Page", null);
            ConditionValidator v2 = new ConditionValidator("#usercontrol == #this", null);

            Assert.IsTrue(c1.Validate(c1, v1, v2));
        }
Exemplo n.º 10
0
 public void Build(string template)
 {
     ConditionValidator.ThrowSystemExceptionIfNotValid <OperationCanceledException>(Types == null,
                                                                                    $"Should be run 'Load' method");
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((string.IsNullOrWhiteSpace(template)),
                                                                         nameof(template));
     _content = new List <IMdStringEditor>();
     foreach (var type in Types)
     {
         var mb = new MdFluentBuilder(template, type.Name, type);
         _content.Add(mb.Build());
     }
 }
Exemplo n.º 11
0
        public void WhenValidatorIsNotEvaluatedBecauseWhenExpressionReturnsFalse()
        {
            ConditionValidator validator = new ConditionValidator();

            validator.Test = Expression.Parse("false");
            validator.When = Expression.Parse("false");
            IValidationErrors errors = new ValidationErrors();

            bool valid = validator.Validate(new object(), null, errors);

            Assert.IsTrue(valid, "Validation should succeed when condition validator is not evaluated.");
            Assert.AreEqual(0, errors.GetErrors("errors").Count);
        }
Exemplo n.º 12
0
 public List <MarkDownType> UpdateComments(List <MarkDownType> types, XmlVsComment[] comments)
 {
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((types == null), nameof(types));
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((comments == null), nameof(comments));
     foreach (var markDownType in types)
     {
         markDownType.Summary = comments.FirstOrDefault(s => s.FullMemberName == markDownType.FullMemberName)
                                ?.Summary;
         markDownType.Properties.FillSummary(comments);
         markDownType.Fields.FillSummary(comments);
         markDownType.Methods.FillSummary(comments);
     }
     return(types);
 }
Exemplo n.º 13
0
        /// <summary>
        /// Get from repository https://github.com/neuecc/MarkdownGenerator/blob/master/VSDocParser.cs
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        private XmlVsComment[] ParseXmlComment(XDocument document)
        {
            ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((document == null), nameof(document));

            return(document.Descendants("member")
                   .Select(x =>
            {
                var match = Regex.Match(x.Attribute("name").Value, @"(.):(.+)\.([^.()]+)?(\(.+\)|$)");
                if (!match.Groups[1].Success)
                {
                    return null;
                }

                var memberType = (MemberType)match.Groups[1].Value[0];
                if (memberType == MemberType.None)
                {
                    return null;
                }

                var summary = ((string)x.Element("summary")) ?? "";
                if (summary != "")
                {
                    summary = string.Join("  ", summary.Split(new[] { "\r", "\n", "\t" }, StringSplitOptions.RemoveEmptyEntries).Select(y => y.Trim()));
                }

                var returns = ((string)x.Element("returns")) ?? "";
                var remarks = ((string)x.Element("remarks")) ?? "";
                var parameters = x.Elements("param")
                                 .Select(e => Tuple.Create(e.Attribute("name").Value, e))
                                 .Distinct(new ItemEqualityComparer <string, XElement>())
                                 .ToDictionary(e => e.Item1, e => e.Item2.Value);

                var className = (memberType == MemberType.Type)
                        ? match.Groups[2].Value + "." + match.Groups[3].Value
                        : match.Groups[2].Value;

                return new XmlVsComment
                {
                    MemberType = memberType,
                    ClassName = className,
                    MemberName = match.Groups[3].Value,
                    Summary = summary.Trim(),
                    Remarks = remarks.Trim(),
                    Parameters = parameters,
                    Returns = returns.Trim()
                };
            })
                   .Where(x => x != null)
                   .ToArray());
        }
Exemplo n.º 14
0
        public void Load(string dllPath, string dllXmlPath)
        {
            ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((string.IsNullOrWhiteSpace(dllPath)),
                                                                                nameof(dllPath));
            ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((string.IsNullOrWhiteSpace(dllXmlPath)),
                                                                                nameof(dllXmlPath));

            _content = new List <IMdStringEditor>();

            var assembly = Assembly.LoadFile(dllPath);
            var types    = _markDownGenerator.GetTypes(assembly);
            var comments = _xmlVsParser.GetComments(dllXmlPath);

            Types = _markDownGenerator.UpdateComments(types, comments);
        }
Exemplo n.º 15
0
 public void Build()
 {
     ConditionValidator.ThrowSystemExceptionIfNotValid <OperationCanceledException>(Types == null,
                                                                                    $"Should be run 'Load' method");
     _content = new List <IMdStringEditor>();
     foreach (var type in Types)
     {
         var mb = new MdStringEditor(type.Name);
         MdStringBuilder.CreateHeader(mb, type);
         MdStringBuilder.BuildTable(mb, type, "Properties", type.Properties);
         MdStringBuilder.BuildTable(mb, type, "Fields", type.Fields);
         MdStringBuilder.BuildTable(mb, type, "Methods", type.Methods);
         _content.Add(mb);
     }
 }
Exemplo n.º 16
0
        public void IsFileNullOrEmpty_Should_Return_True()
        {
            // Arrange
            var viewModel = new Dictionary <string, dynamic>
            {
                { "test-fileupload", null }
            };

            var condition1 = new Condition {
                ComparisonValue = "true", QuestionId = "test", ConditionType = ECondition.IsFileUploadNullOrEmpty
            };
            var conditionValidator = new ConditionValidator();

            // Act & Assert
            Assert.True(conditionValidator.IsValid(condition1, viewModel));
        }
Exemplo n.º 17
0
        public void EnsuresTest03()
        {
            ConditionValidator <int> ensuresValidator = Condition.Ensures(3);

            const string ValidCondition         = "valid condition";
            const string ValidAdditionalMessage = "valid additional message";
            const ConstraintViolationType InvalidConstraintViolationType = (ConstraintViolationType)666;

            const string AssertMessage = "EnsuresValidator.ThrowException should throw an " +
                                         "ArgumentException when an invalid ConstraintViolationType is supplied.";

            Action action = () => ensuresValidator.ThrowException(ValidCondition, ValidAdditionalMessage,
                                                                  InvalidConstraintViolationType);

            action.Should().Throw <PostconditionException>(AssertMessage).Which.Message.Should().Contain(ValidCondition, "The exception message does not contain the condition.");
        }
Exemplo n.º 18
0
        /// <summary>
        /// Get description attribute value
        /// </summary>
        /// <param name="enumerationValue"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static string ToDescription <T>(this T enumerationValue)
            where T : struct
        {
            var type = enumerationValue.GetType();

            ConditionValidator.ThrowExceptionIfNotValid <ArgumentException>((!type.IsEnum),
                                                                            $"EnumerationValue must be of Enum type {enumerationValue}");
            var memberInfo = type.GetMember(enumerationValue.ToString());

            if (memberInfo.Length <= 0)
            {
                return(enumerationValue.ToString());
            }
            var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            return(attrs.Length > 0 ? ((DescriptionAttribute)attrs[0]).Description : enumerationValue.ToString());
        }
Exemplo n.º 19
0
    static int _CreateConditionValidator(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 0)
        {
            ConditionValidator obj = new ConditionValidator();
            LuaScriptMgr.PushObject(L, obj);
            return(1);
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: ConditionValidator.New");
        }

        return(0);
    }
Exemplo n.º 20
0
        public void Is_Before_Should_Return_True()
        {
            // Arrange
            var futureDate = DateTime.Today.AddDays(4);
            var viewModel  = new Dictionary <string, dynamic>
            {
                { "test-day", futureDate.Day.ToString() },
                { "test-month", futureDate.Month.ToString() },
                { "test-year", futureDate.Year.ToString() }
            };

            var condition1 = new Condition {
                IsBefore = 10, Unit = EDateUnit.Day, ComparisonDate = "Today", QuestionId = "test", ConditionType = ECondition.IsBefore
            };
            var conditionValidator = new ConditionValidator();

            // Act & Assert
            Assert.True(conditionValidator.IsValid(condition1, viewModel));
        }
Exemplo n.º 21
0
        public void FalseScalarExpression()
        {
            Inventor tesla = new Inventor();

            tesla.Name = "Soltan Gris";

            ConditionValidator validator = new ConditionValidator(Expression.Parse("Name == 'Nikola Tesla'"), null);

            validator.Actions = new ErrorMessageAction[] { new ErrorMessageAction("Wrong name", "InventorValidator") };
            IValidationErrors errors = new ValidationErrors();

            Assert.IsFalse(validator.Validate(tesla, errors));
            Assert.IsFalse(errors.IsEmpty);
            IList <string> namedErrors = errors.GetResolvedErrors("InventorValidator", new NullMessageSource());

            Assert.AreEqual(1, namedErrors.Count);
            string error = (string)namedErrors[0];

            Assert.AreEqual("Wrong name", error);
        }
Exemplo n.º 22
0
        public void CheckBox_Contains_Should_Return_True_False()
        {
            // Arrange
            var viewModel = new Dictionary <string, dynamic>
            {
                { "test", "pear,guava" },
                { "test2", "apple,mango" }
            };

            var condition1 = new Condition {
                CheckboxContains = "pear", QuestionId = "test", ConditionType = ECondition.Contains
            };
            var condition2 = new Condition {
                CheckboxContains = "plum", QuestionId = "test2", ConditionType = ECondition.Contains
            };
            var conditionValidator = new ConditionValidator();

            // Act & Assert
            Assert.True(conditionValidator.IsValid(condition1, viewModel));
            Assert.False(conditionValidator.IsValid(condition2, viewModel));
        }
Exemplo n.º 23
0
        public void Is_Null_Or_Empty_Should_Return_True_False()
        {
            // Arrange
            var viewModel = new Dictionary <string, dynamic>
            {
                { "test", "" },
                { "test2", "apple" }
            };

            var condition1 = new Condition {
                IsNullOrEmpty = true, QuestionId = "test", ConditionType = ECondition.IsNullOrEmpty
            };
            var condition2 = new Condition {
                IsNullOrEmpty = false, QuestionId = "test2", ConditionType = ECondition.IsNullOrEmpty
            };
            var conditionValidator = new ConditionValidator();

            // Act & Assert
            Assert.True(conditionValidator.IsValid(condition1, viewModel));
            Assert.True(conditionValidator.IsValid(condition2, viewModel));
        }
Exemplo n.º 24
0
        public void Equal_To_Should_Return_True_False()
        {
            // Arrange
            var viewModel = new Dictionary <string, dynamic>
            {
                { "test", "pear" },
                { "test2", "apple" }
            };

            var condition1 = new Condition {
                EqualTo = "pear", QuestionId = "test", ConditionType = ECondition.EqualTo
            };
            var condition2 = new Condition {
                EqualTo = "plum", QuestionId = "test2", ConditionType = ECondition.EqualTo
            };
            var conditionValidator = new ConditionValidator();

            // Act & Assert
            Assert.True(conditionValidator.IsValid(condition1, viewModel));
            Assert.False(conditionValidator.IsValid(condition2, viewModel));
        }
Exemplo n.º 25
0
        public Behaviour GetNextPage(Dictionary <string, dynamic> viewModel)
        {
            var conditionValidator = new ConditionValidator();

            if (Behaviours.Count == 1)
            {
                return(Behaviours.FirstOrDefault());
            }

            foreach (var behaviour in Behaviours.OrderByDescending(_ => _.Conditions.Count))
            {
                var isConditionTrue = false;

                foreach (var condition in behaviour.Conditions)
                {
                    isConditionTrue = conditionValidator.IsValid(condition, viewModel);

                    if (!isConditionTrue)
                    {
                        break;
                    }
                }

                if (isConditionTrue || !behaviour.Conditions.Any())
                {
                    return(behaviour);
                }
            }

            var conditionValuesForDebug = Behaviours.OrderByDescending(_ => _.Conditions.Count)
                                          .Where(_ => _.Conditions != null)
                                          .SelectMany(_ => _.Conditions)
                                          .Where(_ => !string.IsNullOrEmpty(_.QuestionId))
                                          .Select(_ => _.QuestionId)
                                          .Distinct()
                                          .Select(_ => $"QuestionId: {_} with answer {(viewModel.ContainsKey(_) ? viewModel[_] : "'null'")}")
                                          .Aggregate((curr, acc) => $"{acc} {curr}");

            throw new ApplicationException($"Page::GetNextPage, There was a problem whilst processing behaviors for page '{PageSlug}', Behaviour Answers and conditions: {conditionValuesForDebug}");
        }
        public void RequiresTest03()
        {
            ConditionValidator <int> requiresValidator = Condition.Requires(3);

            const string ValidCondition         = "valid condition";
            const string ValidAdditionalMessage = "valid additional message";
            const ConstraintViolationType InvalidConstraintViolationType = (ConstraintViolationType)666;

            const string AssertMessage = "RequiresValidator.ThrowException should throw an " +
                                         "ArgumentException when an invalid ConstraintViolationType is supplied.";

            try
            {
                requiresValidator.ThrowException(ValidCondition, ValidAdditionalMessage, InvalidConstraintViolationType);

                Assert.True(false, AssertMessage);
            }
            catch (Exception ex)
            {
                ex.GetType().ShouldBe(typeof(ArgumentException));
                ex.Message.ShouldContain(ValidCondition, "The exception message does not contain the condition.");
            }
        }
Exemplo n.º 27
0
        public async Task <BattleUnitsListViewModel> Handle(GetBattleUnitsQuery request, CancellationToken cancellationToken)
        {
            var dbHero        = this.Context.Heroes.FromSqlRaw($"GetBattleHero {request.HeroId}").AsEnumerable().First();
            var hero          = this.Mapper.Map <BattleUnitViewModel>(dbHero);
            var fightingClass = await this.Context.FightingClasses.FindAsync(dbHero.FightingClassId);

            var dbSpells           = this.Context.Spells.Where(s => s.FightingClassId == dbHero.FightingClassId).AsNoTracking();
            var conditionValidator = new ConditionValidator();

            foreach (var spell in dbSpells)
            {
                conditionValidator.Process(spell, dbHero, request.Enemy, null, null, true);
                var mappedSpell = this.Mapper.Map <SpellMinViewModel>(spell);
                mappedSpell.ClassType = fightingClass.Type;

                hero.Spells.Add(mappedSpell);
            }

            return(new BattleUnitsListViewModel
            {
                Hero = hero,
                Enemy = this.Mapper.Map <BattleUnitViewModel>(request.Enemy),
            });
        }
Exemplo n.º 28
0
        public void StraightFalse()
        {
            ConditionValidator validator = new ConditionValidator("false", null);

            Assert.IsFalse(validator.Validate(null, new ValidationErrors()));
        }
Exemplo n.º 29
0
 public void StraightFalse()
 {
     ConditionValidator validator = new ConditionValidator("false", null);
     Assert.IsFalse(validator.Validate(null, new ValidationErrors()));
 }
 public void ConditionValidator_Should_ReturnArgumentOutOfRangeException()
 {
     //act
     Assert.Throws(typeof(ArgumentOutOfRangeException),
                   () => ConditionValidator.ThrowExceptionIfNotValid <ArgumentOutOfRangeException>((true), "name"));
 }
Exemplo n.º 31
0
 public void ConditionValidatorTest()
 {
     var conditionValidator = new ConditionValidator();
     var condition = new Condition();
     ValidationResults result = conditionValidator.Validate(condition);
 }
 public void ConditionValidator_WhenFalseCondition_Should_ReturnArgumentOutOfRangeException_With_Message()
 {
     //act
     ConditionValidator.ThrowExceptionIfNotValid <ArgumentOutOfRangeException>((false), "name", "string");
 }
 public void ConditionValidator_Should_ReturnArgumentNullException_With_Message()
 {
     //act
     Assert.Throws(typeof(ArgumentNullException),
                   () => ConditionValidator.ThrowExceptionIfNotValid <ArgumentNullException>((true), "name", "string"));
 }
Exemplo n.º 34
0
 public void StraightTrue()
 {
     ConditionValidator validator = new ConditionValidator();
     validator.Test = Expression.Parse("true");
     Assert.IsTrue(validator.Validate(null, new ValidationErrors()));
 }
Exemplo n.º 35
0
 public StubConditionValidator(ConditionValidator <T> baseValidator)
     : base(baseValidator.ArgumentName, baseValidator.Value)
 {
 }
Exemplo n.º 36
-1
        public void TrueScalarExpression()
        {
            Inventor tesla = new Inventor();
            tesla.Name = "Nikola Tesla";

            ConditionValidator validator = new ConditionValidator(Expression.Parse("Name == 'Nikola Tesla'"), null);
            Assert.IsTrue(validator.Validate(tesla, new ValidationErrors()));
        }