Exemplo n.º 1
0
        public static void RevalidateItems(IEnumerable <IViewModel> items, ValidationScope scope)
        {
            if (scope != ValidationScope.Self)
            {
                foreach (var item in items)
                {
                    foreach (var property in item.Descriptor.Properties)
                    {
                        PerformDescendantValidations(item, property, scope);
                    }
                }
            }

            var controller = new ValidationController();

            foreach (var item in items)
            {
                foreach (var property in item.Descriptor.Properties)
                {
                    controller.RequestPropertyRevalidation(item, property);
                }
            }

            foreach (var item in items)
            {
                controller.RequestViewModelRevalidation(item);
            }

            controller.ProcessPendingValidations();
        }
        public void RevalidateDescendants(IBehaviorContext context, ValidationScope scope)
        {
            State s = GetState(context);

            switch (s.Type)
            {
            case StateType.Initial:
                bool isUnloaded = !this.IsLoadedNext(context);
                bool validateOnlyLoadedDescendants = scope == ValidationScope.SelfAndLoadedDescendants;

                if (isUnloaded && validateOnlyLoadedDescendants)
                {
                    TransitionTo(context, State.ValidateOnFirstAccess(scope));
                }
                else
                {
                    TransitionToValidated(context, scope);
                }

                break;

            case StateType.Validated:
                TransitionToValidated(context, scope);
                break;

            case StateType.ValidateOnFirstAccess:
                if (scope == ValidationScope.SelfAndAllDescendants)
                {
                    TransitionToValidated(context, ValidationScope.SelfAndAllDescendants);
                }
                break;
            }

            this.RevalidateDescendantsNext(context, scope);
        }
Exemplo n.º 3
0
 public void Revalidate(
     IVMPropertyDescriptor property,
     ValidationScope scope = ValidationScope.Self
     )
 {
     Revalidator.RevalidatePropertyValidations(_vm, property, scope);
 }
        public virtual void Outer_validation_scope_aggregates_rules_from_inner_scopes()
        {
            var plan = new ValidationPlan <string>
            {
                Validate.That <string>(s => true)
            };

            using (var scope = new ValidationScope())
            {
                using (new ValidationScope())
                {
                    plan.Execute("");
                }
                using (new ValidationScope())
                {
                    plan.Execute("");
                }
                using (new ValidationScope())
                {
                    plan.Execute("");
                }

                Assert.AreEqual(3, scope.Evaluations.Count());
            }
        }
Exemplo n.º 5
0
        public async Task <IActionResult> TriggerSyncValidation(ValidationScope scope)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.AdministerGraphs))
            {
                return(Forbid());
            }

            IValidateAndRepairResults?validateAndRepairResults = null;

            try
            {
                //todo: display page straight away : show progress (log) in page
                //todo: add name of user who triggered into logs (if not already sussable)
                _logger.LogInformation("User sync validation triggered");
                validateAndRepairResults = await _validateAndRepairGraph.ValidateGraph(scope);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "User triggered sync validation failed.");
                await _notifier.Add("Unable to validate graph sync.", exception : e);
            }
            return(View(new TriggerSyncValidationViewModel
            {
                ValidateAndRepairResults = validateAndRepairResults,
                Scope = scope
            }));
        }
        public void An_unentered_scope_does_not_receive_parameters()
        {
            var scope = new ValidationScope(false);

            42.As("some parameter");

            Assert.That(scope.FlushParameters(), Is.Null);
        }
 private void TransitionToValidated(IBehaviorContext context, ValidationScope scope)
 {
     // Note: We need to transition FIRST, because a revalidate may trigger
     // a lazy load which calls InitializeValue. The validated state ignores
     // this event to avoid revalidating twice.
     TransitionTo(context, State.Validated(scope));
     RevalidateDescendantsCore(context, scope);
 }
Exemplo n.º 8
0
        public static void Revalidate(IViewModel viewModel, ValidationScope scope)
        {
            foreach (var property in viewModel.Descriptor.Properties)
            {
                RevalidatePropertyValidations(viewModel, property, scope);
            }

            RevalidateViewModelValidations(viewModel);
        }
Exemplo n.º 9
0
        protected override void RevalidateDescendantsCore(IBehaviorContext context, ValidationScope scope)
        {
            var childVM = this.GetValueNext <TValue>(context);

            if (childVM != null)
            {
                Revalidator.Revalidate(childVM, scope);
            }
        }
Exemplo n.º 10
0
        public void ValidationScope_Failures_does_not_report_internal_failures()
        {
            var scope = new ValidationScope();

            scope.AddEvaluation(new FailedEvaluation {
                IsInternal = true
            });

            Assert.AreEqual(0, scope.Failures.Count());
        }
Exemplo n.º 11
0
        public void ValidationScope_raises_events_as_evaluations_are_performed()
        {
            var wasCalled = false;

            using (var scope = new ValidationScope())
            {
                scope.RuleEvaluated += (sender, e) => { wasCalled = true; };
                new ValidationRule <string>(s => true).Execute("");
            }

            Assert.That(wasCalled);
        }
Exemplo n.º 12
0
            protected override void RevalidateDescendantsCore(IBehaviorContext context, ValidationScope scope)
            {
                Log.Append(RevalidateCore);

                // Simulate a validator that triggers lazy loading.
                if (!this.IsLoadedNext(context))
                {
                    InitializeValue(context);
                }

                LastValidationScope = scope;
            }
Exemplo n.º 13
0
        public static void RevalidatePropertyValidations(
            IViewModel viewModel,
            IVMPropertyDescriptor property,
            ValidationScope scope
            )
        {
            PerformDescendantValidations(viewModel, property, scope);

            var controller = new ValidationController();

            controller.RequestPropertyRevalidation(viewModel, property);
            controller.ProcessPendingValidations();
        }
Exemplo n.º 14
0
        public static void RevalidateDescendantsNext(
            this Behavior behavior,
            IBehaviorContext context,
            ValidationScope scope
            )
        {
            IDescendantValidationBehavior next;

            if (behavior.TryGetBehavior(out next))
            {
                next.RevalidateDescendants(context, scope);
            }
        }
Exemplo n.º 15
0
        public void An_unentered_scope_still_passes_evaluationsd_to_parent_scope()
        {
            var rule = Validate.That <bool>(f => false).WithErrorMessage("oops");
            ValidationReport report;

            using (var parent = new ValidationScope())
            {
                var child = new ValidationScope(false);
                rule.Check(false, child);
                report = ValidationReport.FromScope(parent);
            }

            Assert.That(report.Failures.Count(f => f.Message == "oops"), Is.EqualTo(1));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Converts a concrete evaluation scope into a abstract validation scope.
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static IValidationScope ToValidationScope(this IEvaluationScope @this)
        {
            if (@this == null)
            {
                return(null);
            }
            var result = new ValidationScope(@this.TypeSystem, @this.Parent.ToValidationScope());

            foreach (var elem in @this)
            {
                result.DefineVariable(elem.Name, elem.Value?.GetType() ?? typeof(object));
            }
            return(result);
        }
Exemplo n.º 17
0
        private async Task <DateTime> GetValidateFromTime(ValidationScope validationScope)
        {
            if (validationScope == ValidationScope.AllItems)
            {
                return(SqlDateTime.MinValue.Value);
            }

            var auditSyncLog = await _session
                               .Query <AuditSyncLog>()
                               .ToAsyncEnumerable()
                               .LastOrDefaultAsync();

            return(auditSyncLog?.LastSynced ?? SqlDateTime.MinValue.Value);
        }
Exemplo n.º 18
0
 private static void PerformDescendantValidations(
     IViewModel target,
     IVMPropertyDescriptor property,
     ValidationScope scope
     )
 {
     if (scope != ValidationScope.Self)
     {
         property.Behaviors.RevalidateDescendantsNext(
             target.GetContext(),
             scope
             );
     }
 }
Exemplo n.º 19
0
        public void When_adding_parameters_to_disposed_scope_they_are_not_added_to_the_parent()
        {
            var rule = Validate.That <bool>(f => false).WithErrorMessage("oops");
            ValidationReport report;

            using (var parent = new ValidationScope())
            {
                var child = new ValidationScope(false);
                child.Dispose();
                rule.Check(false, child);
                report = ValidationReport.FromScope(parent);
            }

            Assert.That(report.Failures.Count(f => f.Message == "oops"), Is.EqualTo(0));
        }
        public async Task Validate()
        {
            Validation = new ValidationScope()
            {
                IsValid = false
            };

            ValidationResult commandValidation = ValidateCommand();

            if (Entity.IsOriginAccountEqualsDestinationAccount())
            {
                Validation.Message = "Operação inválida";
            }
            else
            {
                if (commandValidation.IsValid)
                {
                    Response databaseValidation = await ValidateInPersistenceLayer();

                    if (databaseValidation.Status)
                    {
                        Entity.From = await _accountRepository.Find(Entity.From.BankBranch, Entity.From.BankAccount);

                        Entity.To = await _accountRepository.Find(Entity.To.BankBranch, Entity.To.BankAccount);

                        ValidationResult domainValidation = ValidateInDomain();

                        if (domainValidation.IsValid)
                        {
                            Validation.IsValid = true;
                        }
                        else
                        {
                            Validation.Message = domainValidation.Errors.First().ErrorMessage;
                        }
                    }
                    else
                    {
                        Validation.Message = databaseValidation.Message;
                    }
                }
                else
                {
                    Validation.Message = commandValidation.Errors.First().ErrorMessage;
                }
            }
        }
Exemplo n.º 21
0
        public void Rule_successes_in_inner_scopes_are_reported_to_all_outer_scopes()
        {
            using (var outerScope = new ValidationScope())
            {
                using (var middleScope = new ValidationScope())
                {
                    using (var innerScope = new ValidationScope())
                    {
                        Validate.That <string>(s => true).Execute("");

                        Assert.That(outerScope.Successes.Count(), Is.EqualTo(1));
                        Assert.That(middleScope.Successes.Count(), Is.EqualTo(1));
                        Assert.That(innerScope.Successes.Count(), Is.EqualTo(1));
                    }
                }
            }
        }
Exemplo n.º 22
0
        public void ValidationScope_raises_events_as_evaluations_are_added_to_child_scopes_on_other_threads()
        {
            int evaluationCount = 0;
            var plan            = new ValidationPlan <IEnumerable <string> >();

            // parallelize
            plan.AddRule(
                ss => ss.Parallel(Validate.That <string>(s => false).Check));

            using (var scope = new ValidationScope())
            {
                scope.RuleEvaluated += (o, e) => Interlocked.Increment(ref evaluationCount);
                plan.Execute(Enumerable.Range(1, 30).Select(i => i.ToString()));
            }

            Assert.AreEqual(31, evaluationCount);
        }
Exemplo n.º 23
0
        public async Task <IValidateAndRepairResults> ValidateGraph(
            ValidationScope validationScope,
            params string[] graphReplicaSetNames)
        {
            if (!await _serialValidation.WaitAsync(TimeSpan.Zero))
            {
                return(ValidationAlreadyInProgressResult.Instance);
            }

            try
            {
                return(await ValidateGraphImpl(validationScope, graphReplicaSetNames));
            }
            finally
            {
                _serialValidation.Release();
            }
        }
Exemplo n.º 24
0
        public IChoSurrogateValidator CreateValidator(Attribute attribute, ValidationScope validationScope, ValidatorSource validatorSource)
        {
            if (attribute == null)
            {
                return(null);
            }

            if (attribute is ChoValidatorAttribute)
            {
                object validator = ((ChoValidatorAttribute)attribute).ValidatorInstance;

                ChoGuard.NotNull(validator, "Validator");

                if (validator is ChoValidator)
                {
                    return(new ChoSurrogateValidator(validator as ChoValidator));
                }
                else if (validator is ConfigurationValidatorBase)
                {
                    return(new ChoConfigurationValidatorBaseSurrogateValidator(validator as ConfigurationValidatorBase));
                }
                else
                {
                    throw new ChoValidationException(String.Format("Validator of type '{0}' is not supported by this manager.", validator.GetType().FullName));
                }
            }
            else if (attribute is ValidationAttribute)
            {
                return(new ChoValidationAttributeSurrogateValidator(attribute as ValidationAttribute));
            }
            else if (attribute is ConfigurationValidatorAttribute)
            {
                return(new ChoConfigurationValidatorAttributeSurrogateValidator(attribute as ConfigurationValidatorAttribute));
            }

            throw new ChoValidationException(String.Format("Invalid validation attribute '{0}' passed and not supported by this manager.", attribute.GetType().FullName));
        }
Exemplo n.º 25
0
        public void ValidationScopes_are_not_shared_across_threads()
        {
            IDictionary <string, object> scope1Params = null;
            IDictionary <string, object> scope2Params = null;
            var barrier = new Barrier(2);

            var task1 = Task.Factory.StartNew(() =>
            {
                using (var scope = new ValidationScope())
                {
                    scope.AddParameter("one", 1);
                    barrier.SignalAndWait();
                    scope1Params = scope.FlushParameters();
                    barrier.SignalAndWait();
                }
            });
            var task2 = Task.Factory.StartNew(() =>
            {
                using (var scope = new ValidationScope())
                {
                    scope.AddParameter("two", 2);
                    barrier.SignalAndWait();
                    scope2Params = scope.FlushParameters();
                    barrier.SignalAndWait();
                }
            });

            task1.Wait();
            task2.Wait();

            Assert.That(scope1Params != scope2Params);
            Assert.That(scope1Params.Count(), Is.EqualTo(1));
            Assert.That(scope2Params.Count(), Is.EqualTo(1));
            Assert.That(scope1Params["one"], Is.EqualTo(1));
            Assert.That(scope2Params["two"], Is.EqualTo(2));
        }
Exemplo n.º 26
0
        // TODO
        //public static void Refresh<TDescriptor>(
        //   this IViewModel<TDescriptor> viewModel,
        //   Action<IPathDefinitionBuilder<TDescriptor>> refreshSelector,
        //   bool executeRefreshDependencies = false
        //) where TDescriptor : IVMDescriptor {
        //   if (viewModel == null) {
        //      throw new ArgumentNullException("viewModel");
        //   }

        //   if (refreshSelector == null) {
        //      throw new ArgumentNullException("propertySelector");
        //   }
        //}

        public static void Revalidate(this IViewModel viewModel, ValidationScope scope = ValidationScope.Self)
        {
            viewModel.Kernel.Revalidate(scope);
        }
Exemplo n.º 27
0
        private async Task <IValidateAndRepairResults> ValidateGraphImpl(
            ValidationScope validationScope,
            params string[] graphReplicaSetNames)
        {
            IEnumerable <ContentTypeDefinition> syncableContentTypeDefinitions = _contentDefinitionManager
                                                                                 .ListTypeDefinitions()
                                                                                 .Where(x => x.Parts.Any(p => p.Name == nameof(GraphSyncPart)));

            DateTime timestamp = DateTime.UtcNow;

            IEnumerable <string> graphReplicaSetNamesToValidate = graphReplicaSetNames.Any()
                ? graphReplicaSetNames
                : _graphClusterLowLevel.GraphReplicaSetNames;

            DateTime validateFrom = await GetValidateFromTime(validationScope);

            var results = new ValidateAndRepairResults(validateFrom);

            //todo: we could optimise to only get content items from the oc database once for each replica set,
            // rather than for each instance
            foreach (string graphReplicaSetName in graphReplicaSetNamesToValidate)
            {
                IGraphReplicaSetLowLevel graphReplicaSetLowLevel = _graphClusterLowLevel.GetGraphReplicaSetLowLevel(graphReplicaSetName);
                IContentItemVersion      contentItemVersion      = _contentItemVersionFactory.Get(graphReplicaSetName);

                foreach (IGraph graph in graphReplicaSetLowLevel.GraphInstances)
                {
                    ValidateAndRepairResult result = results.AddNewValidateAndRepairResult(
                        graphReplicaSetName,
                        graph.Instance,
                        graph.Endpoint.Name,
                        graph.GraphName,
                        graph.DefaultGraph);

                    // make current graph available for when parts/fields call back into ValidateContentItem
                    // seems a little messy, and will make concurrent validation a pita,
                    // but stops part/field syncers needing low level graph access
                    _currentGraph = graph;

                    foreach (ContentTypeDefinition contentTypeDefinition in syncableContentTypeDefinitions)
                    {
                        List <ValidationFailure> syncFailures = await ValidateContentItemsOfContentType(
                            contentItemVersion,
                            contentTypeDefinition,
                            validateFrom,
                            result,
                            validationScope);

                        if (syncFailures.Any())
                        {
                            await AttemptRepair(syncFailures, contentTypeDefinition, contentItemVersion, result);
                        }
                    }
                }
            }

            if (results.AnyRepairFailures)
            {
                return(results);
            }

            _logger.LogInformation("Woohoo: graph passed validation or was successfully repaired at {Time}.",
                                   timestamp.ToString("O"));

            _session.Save(new AuditSyncLog(timestamp));
            await _session.CommitAsync();

            return(results);
        }
Exemplo n.º 28
0
        private async Task <List <ValidationFailure> > ValidateContentItemsOfContentType(
            IContentItemVersion contentItemVersion,
            ContentTypeDefinition contentTypeDefinition,
            DateTime lastSynced,
            ValidateAndRepairResult result,
            ValidationScope scope)
        {
            List <ValidationFailure> syncFailures = new List <ValidationFailure>();

            (bool?latest, bool?published) = contentItemVersion.ContentItemIndexFilterTerms;

            //todo: do we want to batch up content items of type?
            IEnumerable <ContentItem> contentTypeContentItems = await _contentItemsService
                                                                .Get(contentTypeDefinition.Name, lastSynced, latest : latest, published : published);

            IEnumerable <ContentItem> deletedContentTypeContentItems = await _contentItemsService
                                                                       .GetDeleted(contentTypeDefinition.Name, lastSynced);

            if (!contentTypeContentItems.Any() && !deletedContentTypeContentItems.Any())
            {
                _logger.LogDebug("No {ContentType} content items found that require validation.", contentTypeDefinition.Name);
                return(syncFailures);
            }

            foreach (ContentItem contentItem in contentTypeContentItems)
            {
                (bool validated, string?validationFailureReason) =
                    await ValidateContentItem(contentItem, contentTypeDefinition, contentItemVersion);

                if (validated)
                {
                    _logger.LogInformation("Sync validation passed for {ContentType} {ContentItemId} in {CurrentGraph}.",
                                           contentItem.ContentType,
                                           contentItem.ContentItemId,
                                           GraphDescription(_currentGraph !));
                    result.Validated.Add(new ValidatedContentItem(contentItem));
                }
                else
                {
                    string message = $"Sync validation failed in {{CurrentGraph}}.{Environment.NewLine}{{ValidationFailureReason}}.";
                    _logger.LogWarning(message, GraphDescription(_currentGraph !), validationFailureReason);
                    ValidationFailure validationFailure = new ValidationFailure(contentItem, validationFailureReason !);
                    syncFailures.Add(validationFailure);
                    result.ValidationFailures.Add(validationFailure);
                }
            }

            if (scope == ValidationScope.ModifiedSinceLastValidation)
            {
                foreach (ContentItem contentItem in deletedContentTypeContentItems)
                {
                    (bool validated, string?validationFailureReason) =
                        await ValidateDeletedContentItem(contentItem, contentTypeDefinition, contentItemVersion);

                    if (validated)
                    {
                        _logger.LogInformation(
                            "Sync validation passed for deleted {ContentType} {ContentItemId} in {CurrentGraph}.",
                            contentItem.ContentType,
                            contentItem.ContentItemId,
                            GraphDescription(_currentGraph !));
                        result.Validated.Add(new ValidatedContentItem(contentItem, ValidateType.Delete));
                    }
                    else
                    {
                        string message =
                            $"Sync validation failed in {{CurrentGraph}}.{Environment.NewLine}{{validationFailureReason}}.";
                        _logger.LogWarning(message, GraphDescription(_currentGraph !), validationFailureReason);
                        ValidationFailure validationFailure = new ValidationFailure(contentItem,
                                                                                    validationFailureReason !, ValidateType.Delete);
                        syncFailures.Add(validationFailure);
                        result.ValidationFailures.Add(validationFailure);
                    }
                }
            }

            return(syncFailures);
        }
Exemplo n.º 29
0
 public void RevalidateDescendants(IBehaviorContext context, ValidationScope scope)
 {
     Log.Append(RevalidateNext);
 }
Exemplo n.º 30
0
 public void Revalidate(ValidationScope scope)
 {
     Revalidator.Revalidate(_vm, scope);
 }