Ejemplo n.º 1
0
        public void AndTrueTrue( )
        {
            And <object>        and       = new And <object>(True <object> .Instance, True <object> .Instance);
            IViolation <object> violation = and.Check(null);

            Assert.AreEqual(NonViolation <object> .Instance, violation);
        }
Ejemplo n.º 2
0
        public void OrTrueTrue( )
        {
            Or <object>         or        = new Or <object>(True <object> .Instance, True <object> .Instance);
            IViolation <object> violation = or.Check(null);

            Assert.AreEqual(NonViolation <object> .Instance, violation);
        }
Ejemplo n.º 3
0
        public void AndFalseFalse( )
        {
            And <object>        and       = new And <object>(False <object> .Instance, False <object> .Instance);
            IViolation <object> violation = and.Check(null);

            Assert.AreNotEqual(NonViolation <object> .Instance, violation);
        }
Ejemplo n.º 4
0
        public void ImpliesTrueTrue( )
        {
            Implies <object>    implies   = new Implies <object>(True <object> .Instance, True <object> .Instance);
            IViolation <object> violation = implies.Check(null);

            Assert.AreEqual(NonViolation <object> .Instance, violation);
        }
Ejemplo n.º 5
0
        public void XorSolutions( )
        {
            IRuleChecker <IList <string> > rc = new RuleCheckerBase <IList <string> >( );

            rc.Add(
                new Xor <IList <string> >(
                    new Contains <string>("a"),
                    new Contains <string>("b")));

            IList <string> list = new CList <string>( );
            IViolation <IList <string> > violation = rc.Check(list);

            Assert.IsNotInstanceOf <NonViolation <IList <string> > >(violation);

            ISolution <IList <string> >[] solutions = violation.Solutions.ToArray( );

            Assert.AreEqual(2, solutions.Length);

            IAction <IList <string> >[] actions1 = solutions[0].Actions.ToArray( );
            IAction <IList <string> >[] actions2 = solutions[1].Actions.ToArray( );

            Assert.AreEqual(1, actions1.Length);
            Assert.AreEqual(1, actions2.Length);
            Assert.AreEqual(1, actions1.Count(a => a is Add <string>));
            Assert.AreEqual(0, actions1.Count(a => a is Remove <string>));
            Assert.AreEqual(1, actions2.Count(a => a is Add <string>));
            Assert.AreEqual(0, actions2.Count(a => a is Remove <string>));

            IAction <IList <string> >[] allActions = actions1.Union(actions2).ToArray( );

            Assert.AreEqual(1, allActions.Count(a => a is Add <string> add && add.Target == "a"));
            Assert.AreEqual(1, allActions.Count(a => a is Add <string> add && add.Target == "b"));
            Assert.AreEqual(0, allActions.Count(a => a is Remove <string> rem && rem.Target == "a"));
            Assert.AreEqual(0, allActions.Count(a => a is Remove <string> rem && rem.Target == "b"));
        }
Ejemplo n.º 6
0
        public void ImpliesViolation( )
        {
            IRuleChecker <IList <string> > rc = new RuleCheckerBase <IList <string> >( );

            rc.Add(
                new Implies <IList <string> >(
                    new Contains <string>("hello"),
                    new Contains <string>("world")));
            IList <string> list = new List <string> {
                "hello"
            };
            IViolation <IList <string> > violation = rc.Check(list);

            Assert.IsInstanceOf <Violation <IList <string> > >(violation);
            Assert.AreEqual(2, violation.Solutions.Count( ));

            ISolution <IList <string> > solRemA =
                violation.Solutions.FirstOrDefault(s => s.Actions.FirstOrDefault( ) is Remove <string>);

            Assert.NotNull(solRemA);
            Assert.AreEqual(1, solRemA.Actions.Count( ));
            Assert.AreEqual("hello", (solRemA.Actions.FirstOrDefault( ) as Remove <string>)?.Target);

            ISolution <IList <string> > solAddB =
                violation.Solutions.FirstOrDefault(s => s.Actions.FirstOrDefault( ) is Add <string>);

            Assert.NotNull(solAddB);
            Assert.AreEqual(1, solAddB.Actions.Count( ));
            Assert.AreEqual("world", (solAddB.Actions.FirstOrDefault( ) as Add <string>)?.Target);

            Assert.AreEqual(solAddB, violation.Solutions.FirstOrDefault( ));
        }
Ejemplo n.º 7
0
        public void NotTrue( )
        {
            Not <object>        not       = new Not <object>(True <object> .Instance);
            IViolation <object> violation = not.Check(null);

            Assert.AreNotEqual(NonViolation <object> .Instance, violation);
        }
Ejemplo n.º 8
0
        public void OrFalseFalse( )
        {
            Or <object>         or        = new Or <object>(False <object> .Instance, False <object> .Instance);
            IViolation <object> violation = or.Check(null);

            Assert.AreNotEqual(NonViolation <object> .Instance, violation);
        }
        public string ResolvePropertyName(IViolation violation)
        {
            var propertyChain = ReflectionHelper.PropertyChainToString(violation.Property, Binder.NameDelimeter);

            if (string.IsNullOrEmpty(propertyChain))
                return null;

            return Binder.NameDelimeter + propertyChain;
        }
Ejemplo n.º 10
0
        public override IViolation <T> Check(T subject, IBehaviors context = null)
        {
            IViolation <T> violation = Target.Check(subject, context);

            return(violation == NonViolation <T> .Instance
               ? (IViolation <T>) new Violation <T>(
                       this,
                       Reduce(
                           MakeValid( ),
                           subject))
               : NonViolation <T> .Instance);
        }
Ejemplo n.º 11
0
 public class ApplicationResult <T> where T : class { //, ICloneable{
     public ApplicationResult(
         T resultSubject,
         IViolation <T> unsolveableViolation,
         ReadOnlyCollection <IAction <T> > performedActions,
         Action acceptDelegate)
     {
         ResultSubject       = (T)(resultSubject as ICloneable)?.Clone( );
         UnsolvableViolation = unsolveableViolation;
         Successful          = ResultSubject != null;
         PerformedActions    = performedActions;
         AcceptDelegate      = acceptDelegate;
     }
Ejemplo n.º 12
0
        public void Check(ICliSpecification spec)
        {
            IBehaviors context = new BehaviorsBase( );

            context.Set(new ConfigBehavior(_config));
            foreach (IRule <ICliSpecification> policy in _config.Policies)
            {
                IViolation <ICliSpecification> violation = policy.Check(spec, context);
                if (violation != NonViolation <ICliSpecification> .Instance)
                {
                    throw new CliPolicyException(policy, violation);
                }
            }
        }
Ejemplo n.º 13
0
        public void ContainsViolation( )
        {
            IRuleChecker <IList <string> > rc = new RuleCheckerBase <IList <string> >( );

            rc.Add(new Contains <string>("hello"));
            IList <string> list = new List <string>( );
            IViolation <IList <string> > violation = rc.Check(list);

            Assert.IsInstanceOf <Violation <IList <string> > >(violation);
            Assert.AreEqual(1, violation.Solutions.Count( ));
            Assert.AreEqual(1, violation.Solutions.First( ).Actions.Count( ));
            Assert.IsInstanceOf <Add <string> >(violation.Solutions.First( ).Actions.First( ));
            Assert.AreEqual("hello", (violation.Solutions.First( ).Actions.First( ) as Add <string>)?.Target);
        }
Ejemplo n.º 14
0
        public IViolation <T> Check(T subject, IBehaviors context = null)
        {
            context ??= EmptyBehaviors.Instance;
            foreach (IRule <T> rule in _rules)
            {
                IViolation <T> violation = rule.Check(subject, context);
                if (violation != NonViolation <T> .Instance)
                {
                    return(violation);
                }
            }

            return(NonViolation <T> .Instance);
        }
Ejemplo n.º 15
0
        public bool Check(T subject, out IEnumerable <IViolation <T> > violations, IBehaviors context = null)
        {
            context ??= EmptyBehaviors.Instance;
            violations = new List <IViolation <T> >( );
            foreach (IRule <T> rule in _rules)
            {
                IViolation <T> violation = rule.Check(subject, context);
                if (violation != NonViolation <T> .Instance)
                {
                    ((List <IViolation <T> >)violations).Add(violation);
                }
            }

            return(((List <IViolation <T> >)violations).Count == 0);
        }
Ejemplo n.º 16
0
		/// <summary>
		/// Adds a violation to GUI (currently, Task View)
		/// </summary>
		private static void AddViolation (IViolation v)
		{
			// TODO: replace Task View with our own GUI			
			TaskSeverity type = TaskSeverity.Warning;
			
			if ((v.Severity == Severity.Critical || v.Severity == Severity.High)
			    && (v.Confidence == Confidence.Total || v.Confidence == Confidence.High))
				type = TaskSeverity.Error;
			
			string text = v.Problem + Environment.NewLine + v.Solution;

			// TODO: handle Location
			Task task = new Task (v.Location.File, text, v.Location.Column, v.Location.Line, type, TaskPriority.Normal, MainAnalyzer.CurrentProject);
			TaskService.Errors.Add (task);				  
		}
Ejemplo n.º 17
0
      public override IViolation<ICliSpecification> Check(
            ICliSpecification subject,
            IBehaviors context = null ) {
         ConfigBehavior cb = null;
         context?.TryGet( out cb );
         ICliConfig conf = cb?.Config;

         foreach( Func<UniqueNames, ICliSpecification, ICliConfig, IViolation<ICliSpecification>> check
               in __checks ) {
            IViolation<ICliSpecification> violation = check( this, subject, conf );
            if( violation != NonViolation<ICliSpecification>.Instance )
               return violation;
         }

         return NonViolation<ICliSpecification>.Instance;
      }
Ejemplo n.º 18
0
        public override IViolation <T> Check(T subject, IBehaviors context = null)
        {
            IViolation <T> va = TargetA.Check(subject, context);
            IViolation <T> vb = TargetB.Check(subject, context);

            if (va == NonViolation <T> .Instance &&
                vb == NonViolation <T> .Instance)
            {
                return(NonViolation <T> .Instance);
            }

            return(new Violation <T>(
                       this,
                       Reduce(
                           MakeValid( ),
                           subject)));
        }
Ejemplo n.º 19
0
        private void XorN(Xor <IList <string> > rule, params string[] args)
        {
            IRuleChecker <IList <string> > rc = new RuleCheckerBase <IList <string> >( );

            rc.Add(rule);
            IList <string> list = args.Where(arg => arg != null).ToList( );
            IViolation <IList <string> > violation = rc.Check(list);

            if (args.Count(arg => arg != null) == 1)
            {
                Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);
            }
            else
            {
                Assert.IsNotInstanceOf <NonViolation <IList <string> > >(violation);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Adds a violation to GUI (currently, Task View)
        /// </summary>
        private static void AddViolation(IViolation v)
        {
            // TODO: replace Task View with our own GUI
            TaskSeverity type = TaskSeverity.Warning;

            if ((v.Severity == Severity.Critical || v.Severity == Severity.High) &&
                (v.Confidence == Confidence.Total || v.Confidence == Confidence.High))
            {
                type = TaskSeverity.Error;
            }

            string text = v.Problem + Environment.NewLine  + v.Solution;

            // TODO: handle Location
            Task task = new Task(v.Location.File, text, v.Location.Column, v.Location.Line, type, TaskPriority.Normal, MainAnalyzer.CurrentProject);

            TaskService.Errors.Add(task);
        }
Ejemplo n.º 21
0
        private long AddViolation(long checkResultId, IViolation violation)
        {
            var violationLevelId = GetViolationLevelId(violation.Level) ?? AddViolationLevel(violation.Level);
            var documentId       = GetDocumentId(violation.Document) ?? AddDocument(violation.Document);
            var seqId            = NewSequence("Violation");

            new SQLiteCommand("INSERT INTO Violation (Id, IdCheckResult, IdViolationLevel, IdDocument, ObjectName) VALUES (@Id, @IdCheckResult, @IdViolationLevel, @IdDocument, @ObjectName)", _connection)
            {
                Parameters =
                {
                    new SQLiteParameter("@Id",               seqId),
                    new SQLiteParameter("@IdCheckResult",    checkResultId),
                    new SQLiteParameter("@IdViolationLevel", violationLevelId),
                    new SQLiteParameter("@IdDocument",       documentId),
                    new SQLiteParameter("@ObjectName",       $"{violation.Object}")
                }
            }.ExecuteNonQuery();
            return(seqId);
        }
Ejemplo n.º 22
0
        public string ResolvePropertyName(IViolation violation)
        {
            var expression = violation.Property as LambdaExpression;

            var propertyName = ReflectionHelper.PropertyChainToString(violation.Property, '.');

            if (!propertyName.EndsWith(".Value"))
            {
                return(propertyName);
            }

            var memberExpression = expression.Body as MemberExpression;

            if (!memberExpression.Member.ReflectedType.IsGenericType || memberExpression.Member.ReflectedType.GetGenericTypeDefinition() != typeof(Nullable <>))
            {
                return(propertyName);
            }

            return(propertyName.Substring(0, propertyName.Length - 6));
        }
Ejemplo n.º 23
0
        public void ImpliesNoViolation( )
        {
            IRuleChecker <IList <string> > rc = new RuleCheckerBase <IList <string> >( );

            rc.Add(
                new Implies <IList <string> >(
                    new Contains <string>("hello"),
                    new Contains <string>("world")));
            IList <string> list = new List <string>( );
            IViolation <IList <string> > violation = rc.Check(list);

            Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);

            list.Add("world");
            violation = rc.Check(list);
            Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);

            list.Add("hello");
            violation = rc.Check(list);
            Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);
        }
Ejemplo n.º 24
0
        public void Or( )
        {
            IRuleChecker <IList <string> > rc = new RuleCheckerBase <IList <string> >( );

            rc.Add(new Or <IList <string> >(new Contains <string>("hello"), new Contains <string>("world")));
            IList <string> list = new List <string>( );

            IViolation <IList <string> > violation = rc.Check(list);

            Assert.IsInstanceOf <Violation <IList <string> > >(violation);
            Assert.AreEqual(2, violation.Solutions.Count( ));
            ISolution <IList <string> > solAddA = violation.Solutions
                                                  .FirstOrDefault(
                s => s.Actions.FirstOrDefault( ) is Add <string> &&
                (s.Actions.FirstOrDefault( ) as Add <string>)?.Target == "hello");

            Assert.IsNotNull(solAddA);
            Assert.AreEqual(1, solAddA.Actions.Count( ));
            ISolution <IList <string> > solAddB = violation.Solutions
                                                  .FirstOrDefault(
                s => s.Actions.FirstOrDefault( ) is Add <string> &&
                (s.Actions.FirstOrDefault( ) as Add <string>)?.Target == "world");

            Assert.IsNotNull(solAddB);
            Assert.AreEqual(1, solAddB.Actions.Count( ));

            list.Add("hello");
            violation = rc.Check(list);
            Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);

            list.Remove("hello");
            list.Add("world");
            violation = rc.Check(list);
            Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);

            list.Add("hello");
            violation = rc.Check(list);
            Assert.IsInstanceOf <NonViolation <IList <string> > >(violation);
        }
Ejemplo n.º 25
0
        private void AssertAndViolation(IViolation <IList <string> > violation, IList <string> subject)
        {
            Assert.IsInstanceOf <Violation <IList <string> > >(violation);
            Assert.AreEqual(1, violation.Solutions.Count( ));
            Assert.AreEqual(2 - subject.Count, violation.Solutions.First( ).Actions.Count( ));
            if (subject.Contains("world"))
            {
                Add <string> addA =
                    violation.Solutions.First( )
                    .Actions.FirstOrDefault(a => a is Add <string> && ((Add <string>)a).Target == "hello") as
                    Add <string>;
                Assert.NotNull(addA);
            }

            if (subject.Contains("hello"))
            {
                Add <string> addB =
                    violation.Solutions.First( )
                    .Actions.FirstOrDefault(a => a is Add <string> && ((Add <string>)a).Target == "world") as
                    Add <string>;
                Assert.NotNull(addB);
            }
        }
Ejemplo n.º 26
0
        public override IViolation <T> Check(T subject, IBehaviors context = null)
        {
            int nonViolationCount = 0;

            foreach (IRule <T> target in _targets)
            {
                IViolation <T> violation = target.Check(subject, context);
                if (violation == NonViolation <T> .Instance)
                {
                    nonViolationCount++;
                }
            }

            if (nonViolationCount == 1)
            {
                return(NonViolation <T> .Instance);
            }

            return(new Violation <T>(
                       this,
                       Reduce(
                           MakeValid( ),
                           subject)));
        }
Ejemplo n.º 27
0
 public ConsoleViolation(ViolationLevel level, IViolation violation)
 {
     this.Level     = level;
     this.Violation = violation;
 }
		public string ResolvePropertyName(IViolation violation)
		{
			return System.Web.Mvc.ExpressionHelper.GetExpressionText(violation.Property as LambdaExpression);
		}
 public string ResolvePropertyName(IViolation violation)
 {
     return(System.Web.Mvc.ExpressionHelper.GetExpressionText(violation.Property as LambdaExpression));
 }
		internal ValidationException(IViolation violation)
		{
			this.Report = new ValidationReport(new[] {violation});
		}
Ejemplo n.º 31
0
 public CliPolicyException(IRule <ICliSpecification> policy, IViolation <ICliSpecification> violation)
     : base($"{policy.Description}: {violation.Description}")
 {
     Policy    = policy;
     Violation = violation;
 }
Ejemplo n.º 32
0
 public ValidationException(IViolation violation)
 {
     this.Report = new ValidationReport(new[] { violation });
 }
Ejemplo n.º 33
0
        private void ApplyInternal(
            T subject,
            IList <IAction <T> > appliedActions,
            Action <ApplicationResult <T> > onResult,
            Action acceptDelegate,
            PropertyObject <bool> cancellationToken,
            Func <IViolation <T>, ISolution <T> > onViolation)
        {
            IViolation <T> violation = Check(subject, _context);

            if (violation == NonViolation <T> .Instance)
            {
                onResult(
                    new ApplicationResult <T>(
                        subject,
                        null,
                        new ReadOnlyCollection <IAction <T> >(appliedActions),
                        acceptDelegate));
            }
            else
            {
                if (onViolation == null)
                {
                    foreach (ISolution <T> solution in violation.Solutions)
                    {
                        if (cancellationToken.Value)
                        {
                            return;
                        }

                        if (solution.Actions.Any(
                                a => (_interactive || !a.IsInteractive) && appliedActions.Any(a.Contradicts)))
                        {
                            continue;
                        }

                        // TODO: proper clone handling (https://github.com/jsc86/jsc.commons/issues/10)
                        T subjectClone = (T)(subject as ICloneable)?.Clone( );
                        List <IAction <T> > appliedActionsClone = new List <IAction <T> >(appliedActions);
                        foreach (IAction <T> action in solution.Actions.Where(a => _interactive || !a.IsInteractive))
                        {
                            action.Apply(subjectClone, _context);
                            appliedActionsClone.Add(action);
                        }

                        ApplyInternal(
                            subjectClone,
                            appliedActionsClone,
                            onResult,
                            acceptDelegate,
                            cancellationToken,
                            null);
                    }
                }
                else
                {
                    ISolution <T> solution = onViolation(violation);
                    if (solution == null)
                    {
                        cancellationToken.Value = true;
                        onResult(
                            new ApplicationResult <T>(
                                subject,
                                violation,
                                new ReadOnlyCollection <IAction <T> >(appliedActions),
                                () => { }));
                    }
                    else
                    {
                        // TODO: proper clone handling (https://github.com/jsc86/jsc.commons/issues/10)
                        T subjectClone = (T)(subject as ICloneable)?.Clone( );
                        List <IAction <T> > appliedActionsClone = new List <IAction <T> >(appliedActions);
                        foreach (IAction <T> action in solution.Actions)
                        {
                            action.Apply(subjectClone, _context);
                            appliedActionsClone.Add(action);
                        }

                        ApplyInternal(
                            subjectClone,
                            appliedActionsClone,
                            onResult,
                            acceptDelegate,
                            cancellationToken,
                            onViolation);
                    }
                }
            }
        } // ApplyInternal