예제 #1
0
        public void AddError(string memberName, IErrorsCollection errorsCollection)
        {
            if (memberName == null)
            {
                throw new ArgumentNullException(nameof(memberName));
            }

            if (memberName == string.Empty)
            {
                throw new ArgumentException("Empty string", nameof(memberName));
            }

            if (errorsCollection == null)
            {
                throw new ArgumentNullException(nameof(errorsCollection));
            }

            if (errorsCollection.IsEmpty)
            {
                return;
            }

            if (!_memberErrors.ContainsKey(memberName))
            {
                _memberErrors.Add(memberName, new ErrorsCollection());
            }

            _memberErrors[memberName].Include(errorsCollection);
        }
예제 #2
0
        /// <summary>
        /// Получение линка соответствия
        /// </summary>
        /// <param name="proj_id">ID в Project</param>
        /// <param name="mappingPropertyName">Имя свойства коллекции в Mappings</param>
        /// <param name="errorsCollection">Сбор настроек, если что не так</param>
        /// <returns>Возвращает линк по ID или null</returns>
        public GuidLink GetGuidLink(Guid proj_id, string mappingPropertyName, IErrorsCollection errorsCollection)
        {
            //получение распарсенного набора линков
            var links = Mappings?.GetGuidLinksCollection(mappingPropertyName, errorsCollection);

            if (links == null)
            {
                errorsCollection.AddError($"Не удалось получить узел '{mappingPropertyName.LogValue()}' из файла настроек");
                return(null);
            }

            //ищем в настройках сопоставление
            var link = links.FirstOrDefault(c => proj_id.Equals(c.SP_ID_Guid));

            if (link == null)
            {
                errorsCollection.AddError($"Не удалось найти соответствия в узле '{mappingPropertyName.LogValue()}' по ключу '{proj_id.ToString()}' в файле настроек");
                return(null);
            }

            if (!link.IsValid)
            {
                errorsCollection.AddError($"Не удалось распознать соответствие в узле '{mappingPropertyName.LogValue()}', найденном по ключу '{proj_id.ToString()}' в файле настроек"
                                          , parameters: new ErrorParameter[] {
                    new ErrorParameter("SP_ID", link.SP_ID.ToString()),
                    new ErrorParameter("J_ID", link.J_ID.ToString())
                });
                return(null);
            }

            //возвращаем связку
            return(link);
        }
예제 #3
0
        // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
        private static void BuildListReport(ListReport listReport, string path, IErrorsCollection errorsCollection, Translator translator, int depth, IExecutionOptions executionOptions)
        {
            if (depth > executionOptions.MaxDepth)
            {
                throw new MaxDepthExceededException(executionOptions.MaxDepth);
            }

            if (errorsCollection.IsEmpty)
            {
                return;
            }

            if (errorsCollection.Errors.Any())
            {
                listReport.AddRange(errorsCollection.Errors
                                    .Select(m => string.IsNullOrWhiteSpace(path)
                        ? translator(m)
                        : $"{path}: {translator(m)}")
                                    .Distinct()
                                    .ToList()
                                    );
            }

            foreach (var memberPair in errorsCollection.Members)
            {
                var currentPath = string.IsNullOrEmpty(path) ? string.Empty : $"{path}.";

                BuildListReport(listReport, $"{currentPath}{memberPair.Key}", memberPair.Value, translator, depth + 1, executionOptions);
            }
        }
예제 #4
0
        public static IError GetSingleError(this IErrorsCollection @this)
        {
            if ([email protected]())
            {
                throw new NoSingleErrorCollectionException();
            }

            return(@this.Errors.Single());
        }
예제 #5
0
        public static void ExpectErrors(IErrorsCollection errorsCollection, IReadOnlyCollection <string> errors)
        {
            Assert.NotNull(errorsCollection.Errors);
            Assert.Equal(errors.Count(), errorsCollection.Errors.Count());

            for (var i = 0; i < errors.Count(); ++i)
            {
                Assert.Equal(errors.ElementAt(i), errorsCollection.Errors.ElementAt(i).ToFormattedMessage());
            }
        }
예제 #6
0
        public static void ExpectMembers(IErrorsCollection errorsCollection, IReadOnlyCollection <string> membersNames)
        {
            Assert.NotNull(errorsCollection.Members);
            Assert.Equal(membersNames.Count(), errorsCollection.Members.Count);

            for (var i = 0; i < membersNames.Count(); ++i)
            {
                Assert.Equal(membersNames.ElementAt(i), errorsCollection.Members.Keys.ElementAt(i));
                Assert.NotNull(errorsCollection.Members[membersNames.ElementAt(i)]);
            }
        }
예제 #7
0
        public static IValidationResult <object> MockValidationResult(IErrorsCollection errorsCollection, ExecutionContextStub executionContext = null, Translation[] translations = null)
        {
            var resultMock = new Mock <IValidationResult <object> >();

            resultMock.Setup(v => v.ErrorsCollection).Returns(errorsCollection);
            resultMock.Setup(v => v.TranslationProxy).Returns(new TranslationProxy(e => e.ToFormattedMessage(), new TranslatorsRepository(translations ?? Array.Empty <Translation>())));
            resultMock.Setup(v => v.ExecutionOptions).Returns(executionContext ?? new ExecutionContextStub {
                MaxDepth = 10, CollectionForceKey = "*", RequiredError = new Error("Required")
            });

            return(resultMock.Object);
        }
예제 #8
0
        public void InsertErrors(ErrorsCollection targetErrorsCollection, IErrorsCollection scopeErrorsCollection)
        {
            if (targetErrorsCollection == null)
            {
                throw new ArgumentNullException(nameof(targetErrorsCollection));
            }

            if (scopeErrorsCollection == null)
            {
                throw new ArgumentNullException(nameof(scopeErrorsCollection));
            }

            targetErrorsCollection.AddError(Name, scopeErrorsCollection);
        }
예제 #9
0
        // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
        private static IModelReport BuildModelReport(IErrorsCollection errorsCollection, Translator translator, int depth, IExecutionOptions executionOptions)
        {
            if (depth > executionOptions.MaxDepth)
            {
                throw new MaxDepthExceededException(executionOptions.MaxDepth);
            }

            if (errorsCollection.IsEmpty)
            {
                return(ModelReport.Empty);
            }

            var errorsList = new ModelReportErrorsList();

            if (errorsCollection.Errors.Any())
            {
                var errors = errorsCollection.Errors
                             .Select(e => translator(e))
                             .Distinct()
                             .ToList();

                errorsList.AddRange(errors);
            }

            if (!errorsCollection.Members.Any())
            {
                return(errorsList);
            }

            var report = errorsList.Any()
                ? new ModelReport {
                { string.Empty, errorsList }
            }
                : new ModelReport();

            foreach (var memberPair in errorsCollection.Members)
            {
                var memberReport = BuildModelReport(memberPair.Value, translator, depth + 1, executionOptions);

                if (memberReport != null)
                {
                    report.Add(memberPair.Key, memberReport);
                }
            }

            return(report);
        }
예제 #10
0
        public void Include(IErrorsCollection errorsCollection)
        {
            if (errorsCollection == null)
            {
                throw new ArgumentNullException(nameof(errorsCollection));
            }

            if (errorsCollection.IsEmpty)
            {
                return;
            }

            foreach (var member in errorsCollection.Members)
            {
                AddError(member.Key, member.Value);
            }

            foreach (var error in errorsCollection.Errors)
            {
                AddError(error);
            }
        }
예제 #11
0
        public bool TryGetErrors(TModel model, IExecutionContext executionContext, ValidationStrategy validationStrategy, int depth, out IErrorsCollection scopeErrorsCollection)
        {
            var errorsCollection = _getErrors(this, model, executionContext ?? throw new ArgumentNullException(nameof(executionContext)), validationStrategy, depth);

            if (!errorsCollection.IsEmpty && (RuleSingleError != null))
            {
                scopeErrorsCollection = ErrorsCollection.WithSingleOrNull(RuleSingleError);

                return(true);
            }

            scopeErrorsCollection = errorsCollection;

            return(!scopeErrorsCollection.IsEmpty);
        }
예제 #12
0
        private static IErrorsCollection GetOrEmpty(IErrorsCollection result)
        {
            var anyErrors = (result != null) && !result.IsEmpty;

            return(anyErrors ? result : ErrorsCollection.Empty);
        }
예제 #13
0
 public abstract bool TryGetErrors(object memberValue, IExecutionContext executionContext, ValidationStrategy validationStrategy, int depth, out IErrorsCollection errorsCollection);
예제 #14
0
        public bool TryGetErrors(TModel model, IExecutionContext executionContext, ValidationStrategy validationStrategy, int depth, out IErrorsCollection scopeErrorsCollection)
        {
            var anyErrors = Rule.TryGetErrors(model, executionContext, validationStrategy, out var errorsCollection);

            if (!errorsCollection.IsEmpty && (RuleSingleError != null))
            {
                scopeErrorsCollection = ErrorsCollection.WithSingleOrNull(RuleSingleError);

                return(true);
            }

            scopeErrorsCollection = errorsCollection;

            return(anyErrors);
        }
예제 #15
0
 public static bool ContainsSingleError(this IErrorsCollection @this)
 {
     return((@this.Errors.Count == 1) && [email protected]());
 }
예제 #16
0
 public abstract bool TryGetErrors(object model, object memberValue, IExecutionContext executionContext, ValidationStrategy validationStrategy, out IErrorsCollection result);
예제 #17
0
        internal ValidationResult(Guid validationContextId, ITranslationProxy translationProxy, IExecutionOptions executionOptions, T model = null, IErrorsCollection errorsCollection = null)
        {
            TranslationProxy = translationProxy ?? throw new ArgumentNullException(nameof(translationProxy));
            ErrorsCollection = errorsCollection ?? Errors.ErrorsCollection.Empty;
            ExecutionOptions = executionOptions ?? throw new ArgumentNullException(nameof(executionOptions));

            ValidationDate      = DateTime.UtcNow;
            ValidationContextId = validationContextId;

            Model = model;
        }