/// <summary>
        /// Проверяет указанную в параметре <paramref name="obj"/> коллекцию,
        /// последовательно применяя к каждому её элементу валидатор <see cref="ObjectValidator"/>.
        /// </summary>
        /// 
        /// <remarks>
        /// При валидации производится замена ключей ошибок, добавляя к ним префикс "[&lt;индекс&gt;].",
        /// аналогичный префиксу, добавляемого ASP.NET MVC для элементов форм при рендеринге списка вложенных объектов.
        /// 
        /// Если проверяемый объект равен <c>null</c>, то валидация завершается успешно. Используйте <see cref="RequiredValidator"/>,
        /// если хотите проверить, имеет ли объект значение.
        /// </remarks>
        /// 
        /// <param name="obj">Проверяемая коллекция.</param>
        /// <param name="context">Валидационный контекст.</param>
        /// 
        /// <exception cref="InvalidOperationException">Указанный <paramref name="obj"/> задан, но не является коллекцией.</exception>
        public void Validate(IValidationContext context, object obj)
        {
            if (obj == null) { return; }

            var enumerable = obj as IEnumerable<object>;

            if (enumerable == null)
            {
                throw new InvalidOperationException(
                    String.Format(Resources.Strings.CollectionValidatorInvalidObject, GetType(), obj.GetType()));
            }

            var index = 0;
            foreach (var o in enumerable)
            {
                // Если исходный ключ был пустым, то просто добавляем индекс.
                using (context.ModifyKeys("^$", string.Format("[{0}]", index)))
                // Если исходным ключ не был пустым, то добавляем индекс с точкой.
                using (context.ModifyKeys("^(.+)$", string.Format("[{0}].$1", index)))
                {
                    _objectValidator.Validate(context, o);
                }

                index++;
            }
        }
Beispiel #2
0
 /// <summary>
 /// Called when the object is validating the fields.
 /// </summary>
 /// <param name="validationContext">The validation context.</param>
 protected override void OnValidatingFields(IValidationContext validationContext)
 {
     if (string.IsNullOrWhiteSpace(Name))
     {
         validationContext.AddFieldValidationResult(new FieldValidationResult(NameProperty,ValidationResultType.Error, "Name cannot be empty."));
     }
 }
        /// <summary>
        /// Проверяет длину строки, либо массива, указанного в параметре <paramref name="value"/>
        /// сравнивая её с минимальной длиной, указанной в свойстве <see cref="Length"/>.
        /// </summary>
        /// 
        /// <remarks>
        /// Если длина объекта миньше, чем указанное число, то в валидационный
        /// контекст добавляется сообщение об ошибке, указанное в свойстве <see cref="Message"/>.
        /// 
        /// Если значение проверяемого объекта равно <c>null</c>, то валидация всегда 
        /// проходит успешно. Используйте <see cref="RequiredValidator"/>,
        /// если хотите проверить, имеет ли объект значение.
        /// 
        /// В качестве ключей для ошибок выступает пустая строка.
        /// </remarks>
        /// 
        /// <param name="value">Проверяемый объект.</param>
        /// <param name="context">Валидационный контекст.</param>
        /// 
        /// <exception cref="InvalidOperationException"><see cref="Length"/> имеет отрицательное значение.</exception>
        /// <exception cref="InvalidOperationException">
        ///   <paramref name="value"/> задан, но не является строкой или массивом.
        /// </exception>
        public void Validate(IValidationContext context, object value)
        {
            if (Length < 0)
            {
                throw new InvalidOperationException(
                    String.Format(Resources.Strings.LengthValidatorNegativeLength, GetType().Name, Length));
            }

            if (value == null) { return; }

            var str = value as string;
            var arr = value as Array;
            int num = str != null ? str.Length : arr != null ? arr.Length : -1;

            if (num == -1)
            {
                throw new InvalidOperationException(
                    String.Format(Resources.Strings.LengthValidatorInvalidObject, GetType().Name, value.GetType().Name));
            }

            if (num < Length)
            {
                context.AddError(String.Format(Message ?? Resources.Strings.MinLengthValidatorMessage, Length));
            }
        }
        public string Validate(IValidationContext context)
        {
            if (context.Value == null)
                return null;

            var value = context.Value.ToString();
            return Validate(value, this.Multiple, this.Internal, this.Mobile, this.AllowInternational, this.AllowExtension);
        }
 /// <summary>
 /// Вызывает метод <see cref="IValidatable.Validate"/>, если
 /// <paramref name="obj"/> реализует интерфейс <see cref="IValidatable"/>.
 /// </summary>
 /// 
 /// <remarks>
 /// Если значени указанного объекта равено <c>null</c>, либо не реализует 
 /// нужный интерфейс, валидация всегда проходит успешно. 
 /// Используйте <see cref="RequiredValidator"/>,  если хотите проверить, 
 /// имеет ли объект значение.
 /// </remarks>
 /// 
 /// <param name="obj">Проверяемый объект.</param>
 /// <param name="context">Валидационный контекст.</param>
 public void Validate(IValidationContext context, object obj)
 {
     var validatable = obj as IValidatable;
     if (validatable != null)
     {
         validatable.Validate(context);
     }
 }
 private static void RegisterValidateableProperties(ProjectViewModel project, IValidationContext ValidationContext)
 {
     if (ValidationContext == null) return;
     ValidationContext.RegisterValidateableElement(project.BlockDetails.AssemblyDate);
     ValidationContext.RegisterValidateableElement(project.BlockDetails.SerialNumber);
     foreach (ValidateableFirmwareSetComponentViewModel component in project.FirmwareSetConstructor.Components)
         ValidationContext.RegisterValidateableElement(component);
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="origContext"></param>
        public BaseContext(IValidationContext origContext)
        {
            if ((origContext is AutomatedContext) || (origContext is ConfigurableContext))
                throw new ArgumentException("origContext cannot be an AutomatedContext or ConfigurableContext.");

            // Store the original context
            originalContext = origContext;

            Init();
        }
        protected override async Task OnLoadingFailedAsync(string location, Exception exception, IValidationContext validationContext)
        {
            await base.OnLoadingFailedAsync(location, exception, validationContext);
            if (ProjectManager.ActiveProject == null)
            {
                return;
            }

            var lastActiveProject = _projectActivationHistoryService.GetLastActiveProject();
            await ProjectManager.SetActiveProjectAsync(lastActiveProject).ConfigureAwait(false);
        }
        public string Validate(IValidationContext context)
        {
            if (context.Value == null)
                return null;

            var value = context.Value.ToString();

            if (!EmailPattern.IsMatch(value))
                return Web.Texts.Validation.Email;

            return null;
        }
        public ProjectViewModel GetViewModel(int CellKindId, int CellModificationId, IValidationContext ValidationContext)
        {
            var project = new ProjectViewModel(CellKindId, CellModificationId,
                                               new BlockDetailsViewModel(),
                                               _firmwareSetConstructorViewModelProvider.GetViewModel(CellKindId, CellModificationId),
                                               _eventAggregator,
                                               _burningStatus);

            RegisterValidateableProperties(project, ValidationContext);

            return project;
        }
        /// <summary>
        /// Проверяет заданный <paramref name="obj"/> на корректность,
        /// используя делегат, заданный в свойстве <see cref="Delegate"/>.
        /// </summary>
        /// 
        /// <remarks>
        /// Если валидация завершилась неудачей, то в валидационный
        /// контекст добавляется ошибка с сообщением, указанным в свойстве 
        /// <see cref="Message"/>.
        /// 
        /// В качестве ключей для ошибок выступает пустая строка.
        /// </remarks>
        /// 
        /// <param name="obj">Проверяемый объект.</param>
        /// <param name="context">Валидационный контекст.</param>
        /// <exception cref="InvalidOperationException">Свойство <see cref="Delegate"/> не задано.</exception>
        public void Validate(IValidationContext context, object obj)
        {
            if (Delegate == null)
            {
                throw new InvalidOperationException("Delegate can not be null");
            }

            if (!Delegate(obj))
            {
                context.AddError(Message);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ValidationSummary"/> class and filters all the validations on the specified tag.
        /// </summary>
        /// <param name="validationContext">The validation context to base the summary on.</param>
        /// <param name="tag">The tag.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="validationContext"/> is <c>null</c>.</exception>
        public ValidationSummary(IValidationContext validationContext, object tag)
        {
            Argument.IsNotNull("validationContext", validationContext);

            _fieldWarnings = validationContext.GetFieldWarnings(tag);
            _fieldErrors = validationContext.GetFieldErrors(tag);
            _businessRuleWarnings = validationContext.GetBusinessRuleWarnings(tag);
            _businessRuleErrors = validationContext.GetBusinessRuleErrors(tag);

            LastModified = validationContext.LastModified;
            LastModifiedTicks = validationContext.LastModifiedTicks;
        }
Beispiel #13
0
 private async Task ProcessValidationErrors(IValidationContext context)
 {
     await Task.Run(() =>
     {
         if (!context.IsValid)
         {
             foreach (string error in context.ErrorMessages)
             {
                 ModelState.AddModelError("url", error);
             }
         }
     });
 }
        /// <summary>
        /// Проверяет строковое представление указанного объекта на
        /// соответствие с указанным в свойстве <see cref="Pattern"/> 
        /// регулярным выражением, которое должно соответствовать всей строке.
        /// </summary>
        /// 
        /// <remarks>
        /// Если строковое представление удовлетворяет <c>String.IsNullOrEmpty</c>,
        /// то валидация всегда проходит успешно. Используйте <see cref="RequiredValidator"/>,
        /// если хотите проверить, имеет ли объект значение.
        /// 
        /// В качестве ключей для ошибок выступает пустая строка.</remarks>
        /// 
        /// <param name="obj">Проверяемый объект.</param>
        /// <param name="context">Валидационный контекст.</param>
        public void Validate(IValidationContext context, object obj)
        {
            var input = Convert.ToString(obj, CultureInfo.CurrentCulture);

            if (string.IsNullOrEmpty(input)) { return; }

            var match = Regex.Match(input, Pattern);

            if (!match.Success || match.Index != 0 || match.Length != input.Length)
            {
                context.AddError(String.Format(Message ?? Resources.Strings.RegularExpressionMessage, Pattern));
            }
        }
        private static string FormatMessage(IValidationContext context)
        {
            var sb = new StringBuilder();
            sb.AppendLine("One or more validation errors occured:");
            foreach (var key in context.Keys)
            {
                sb.AppendLine(String.Format(
                    "Key {0}: {1}", 
                    !String.IsNullOrEmpty(key) ? "\"" + key + "\"" : "<empty>", 
                    String.Join(", ", context[key].Select(x => "\"" + x + "\""))));
            }

            return sb.ToString();
        }
Beispiel #16
0
        /// <summary>
        /// Synchronizes the current with the specified context. This means that the current contains will become the same as the
        /// specified context.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        /// <param name="additionalValidationContext">The additional validation context.</param>
        /// <param name="onlyAddValidation">if set to <c>true</c>, validation is only added, not removed. This is great to build up summaries.</param>
        /// <returns>The list of changes.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException">The <paramref name="validationContext" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="validationContext" /> is <c>null</c>.</exception>
        public static List<ValidationContextChange> SynchronizeWithContext(this ValidationContext validationContext, IValidationContext additionalValidationContext, bool onlyAddValidation = false)
        {
            Argument.IsNotNull("validationContext", validationContext);
            Argument.IsNotNull("additionalValidationContext", additionalValidationContext);

            var changes = ValidationContextHelper.GetChanges(validationContext, additionalValidationContext);

            foreach (var change in changes)
            {
                var validationResultAsField = change.ValidationResult as IFieldValidationResult;
                var validationResultAsBusinessRule = change.ValidationResult as IBusinessRuleValidationResult;

                switch (change.ChangeType)
                {
                    case ValidationContextChangeType.Added:
                        if (validationResultAsField != null)
                        {
                            validationContext.AddFieldValidationResult(validationResultAsField);
                        }
                        else if (validationResultAsBusinessRule != null)
                        {
                            validationContext.AddBusinessRuleValidationResult(validationResultAsBusinessRule);
                        }
                        break;

                    case ValidationContextChangeType.Removed:
                        if (!onlyAddValidation)
                        {
                            if (validationResultAsField != null)
                            {
                                validationContext.RemoveFieldValidationResult(validationResultAsField);
                            }
                            else if (validationResultAsBusinessRule != null)
                            {
                                validationContext.RemoveBusinessRuleValidationResult(validationResultAsBusinessRule);
                            }
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            return changes;
        }
Beispiel #17
0
        /// <summary>
        /// Validates the property.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <param name="validationContext">The context that describes the property to validate.</param>
        /// <param name="validationResults">A collection to hold each failed validation.</param>
        /// <returns>True if the property validates; otherwise, false.</returns>
        public virtual bool TryValidateProperty( object value, IValidationContext validationContext, ICollection<IValidationResult> validationResults )
        {
            Arg.NotNull( validationContext, nameof( validationContext ) );

            ValidationContext context;

            if ( !validationContext.TryGetService( out context ) )
                return true;

            var results = new List<ValidationResult>();
            var valid = Validator.TryValidateProperty( value, context, results );

            if ( validationResults != null )
                validationResults.AddRange( results.Select( r => new ValidationResultAdapter( r ) ) );

            return valid;
        }
        /// <summary>
        /// Проверяет указанную в параметрах <paramref name="obj"/> строку
        /// или объект. Валидация завершается успешно, если значение объекта не равно <c>null</c>
        /// и не равно пустой строке (если объектом является строка и свойство <see cref="AllowEmptyStrings"/>
        /// имеет значение <c>false</c>).
        /// </summary>
        /// 
        /// <remarks>
        /// В качестве включей ошибок выступает пустая строка.
        /// </remarks>
        /// 
        /// <param name="obj">Проверяемый объект.</param>
        /// <param name="context">Валидационный контекст.</param>
        public void Validate(IValidationContext context, object obj)
        {
            var message = Message ?? Resources.Strings.PresenceValidatorMessage;

            if (obj == null)
            {
                context.AddError(message);
            }
            
            var str = obj as string;
            if (str != null)
            {
                if (!AllowEmptyStrings && str.Trim().Length == 0)
                {
                    context.AddError(message);
                }
            }
        }
        public BurningViewModel GetViewModel(int CellKindId, int ModificationId, IValidationContext ValidationContext, IProjectAssembler projectAssembler)
        {
            BlockKind cellKind = _indexHelper.GetCell(CellKindId);
            ModificationKind modification = _indexHelper.GetModification(cellKind, ModificationId);

            List<BurningOptionViewModel> burningOptions = Enumerable.Range(1, cellKind.ChannelsCount)
                                                                    .Select(i => new BurningOptionViewModel(String.Format("Канал {0}", i), i, _burningStatus))
                                                                    .ToList();
            List<BurningMethodViewModel> burningMethods = _burningService.GetBurningMethods(modification.DeviceName)
                                                                         .Select(
                                                                             burningMethod =>
                                                                             new BurningMethodViewModel(burningMethod.Name, burningMethod.Receipt))
                                                                         .ToList();

            var viewModel = new BurningViewModel(burningOptions, burningMethods, _burningStatus);
            var controller = new BurningViewModelController(viewModel, CellKindId, _eventAggregator, _settingsService, ValidationContext, projectAssembler,
                                                            _burningService);
            return viewModel;
        }
Beispiel #20
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Board>();

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Название доски не задано");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var boardExists = await databaseContext.Boards
                                  .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                                  .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => boardExists)
                .AddValidationDetail("Доска с таким именем уже существует");
            }
        }
        public static string[] GetAlertMessages(this IValidationContext validationContext, string validationTag)
        {
            Argument.IsNotNull(() => validationContext);

            var stringLines = validationContext.GetErrors(validationTag).Select(s => " - " + s.Message).ToArray();

            if (stringLines is null)
            {
                return(null);
            }

            var valuableLines = stringLines.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

            if (!valuableLines.Any())
            {
                return(null);
            }

            return(valuableLines);
        }
Beispiel #22
0
        protected override void OnNodeSet()
        {
            base.OnNodeSet();

            var gameDocRegistry = Globals.MEFContainer.GetExportedValue <GameDocumentRegistry>();

            if (gameDocRegistry.MasterDocument == null || gameDocRegistry.MasterDocument == this.As <IGameDocument>())
            {
                m_rootLayers = DomNode.GetChild(Schema.gameType.layersChild);
                m_layers     = new DomNodeListAdapter <ILayer>(m_rootLayers, Schema.layersType.layerChild);

                m_rootLayers.ChildInserted    += DomNode_ChildInserted;
                m_rootLayers.ChildRemoved     += DomNode_ChildRemoved;
                m_rootLayers.AttributeChanged += DomNode_AttributeChanged;
                GameContext        gameContext       = DomNode.Cast <GameContext>();
                IValidationContext validationContext = (IValidationContext)gameContext;
                validationContext.Ended += validationContext_Ended;
                m_activeItem             = m_rootLayers;
            }
        }
        private async Task RunQuery(IValidationContext context)
        {
            Logger.LogInformation(LogDestination.File, "Running the migration query in the source project");

            try
            {
                var workItemUris = await WorkItemTrackingHelpers.GetWorkItemIdAndReferenceLinksAsync(
                    context.SourceClient.WorkItemTrackingHttpClient,
                    context.Config.SourceConnection.Project,
                    context.Config.Query,
                    context.Config.TargetPostMoveTag,
                    context.Config.QueryPageSize - 1 /* Have to subtract -1 from the page size due to a bug in how query interprets page size */);

                context.WorkItemIdsUris = new ConcurrentDictionary <int, string>(workItemUris);
            }
            catch (Exception e)
            {
                throw new ValidationException("Unable to run the migration query", e);
            }
        }
        public BurningViewModelController(BurningViewModel ViewModel, int CellKindId, IEventAggregator EventAggregator, ISettingsService SettingsService,
                                          IValidationContext ValidationContext, IProjectAssembler ProjectAssembler, IBurningService BurningService)
        {
            _viewModel = ViewModel;
            _settingsService = SettingsService;
            _validationContext = ValidationContext;
            _projectAssembler = ProjectAssembler;
            _burningService = BurningService;
            _cellKindId = CellKindId;
            _viewModel.SelectedBurningMethodChanged += ViewModelOnSelectedBurningMethodChanged;

            foreach (BurningOptionViewModel burningOption in _viewModel.BurningOptions)
                burningOption.Activated += BurningOptionOnActivated;

            string preferredBurningMethod = _settingsService.GetPreferredBurningMethod(CellKindId);
            _viewModel.SelectedBurningMethod =
                _viewModel.BurningMethods.FirstOrDefault(m => m.Name == preferredBurningMethod)
                ?? _viewModel.BurningMethods.FirstOrDefault();
            EventAggregator.GetEvent<ProjectChangedEvent>().Subscribe(OnProjectChanged);
        }
Beispiel #25
0
        public async Task ValidateCardName(IValidationContext validationContext, Card card, Card model, Guid accountId)
        {
            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Укажите название карточки");

            if (validationContext.IsValid(model, m => m.Name) && validationContext.IsValid(model, m => m.Id))
            {
                var cardNameExists = await databaseContext.Boards
                                     .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                                     .Where(x => x.Columns.Any(c => c.Id == card.ColumnId))
                                     .SelectMany(x => x.Columns)
                                     .SelectMany(x => x.Cards)
                                     .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => cardNameExists)
                .AddValidationDetail("Карточка с таким названием уже существует");
            }
        }
Beispiel #26
0
        public void Validate(T model, IValidationContext context)
        {
            var shouldExecute = ExecutionCondition?.Invoke(model) ?? true;

            if (!shouldExecute)
            {
                return;
            }

            context.EnterPath(Path);

            if (ErrorId.HasValue)
            {
                context.EnableErrorDetectionMode(ErrorMode, ErrorId.Value);
            }

            RunValidation(model, context);

            context.LeavePath();
        }
Beispiel #27
0
        public FieldValidationManager(IValidatableEntity validatableEntity, IValidationContext validationContext)
        {
            if (validatableEntity == null)
            {
                throw new ArgumentNullException(nameof(IValidatableEntity));
            }

            _validatableEntity = validatableEntity;
            var type = validatableEntity.GetType();

            _validationRules = new List <IValidationRule>(ApplicationContext.ValidationRuleCache.GetValidationRules(type));
            var nonValidated = SharedUtility.ApplicationContext.DomainGraphCache.GetPropertiesAttributes <NonValidated>(type);

            _children = new List <PropertyInfo>(SharedUtility.ApplicationContext.DomainGraphCache.GetPropertiesOfType <IValidatableEntity>(type).Where(x => !nonValidated.ContainsKey(x)));
            _children.AddRange(new List <PropertyInfo>(SharedUtility.ApplicationContext.DomainGraphCache.GetPropertiesOfType <IEnumerable <IValidatableEntity> >(type).Where(x => !nonValidated.ContainsKey(x))));

            _results = new List <IValidationResult>();

            SetValidationContext(validationContext);
        }
        /// <summary>
        /// Check constraint C31
        /// </summary>
        /// <param name="context"></param>
        /// <param name="bcv"></param>
        private void checkC31(IValidationContext context, EA.Package bcv)
        {
            int count_btv = 0;

            //Iterate of the different packages of the business choreography view
            foreach (EA.Package p in bcv.Packages)
            {
                String stereotype = Utility.getStereoTypeFromPackage(p);
                if (stereotype == UMM.bTransactionV.ToString())
                {
                    count_btv++;
                }
            }

            //There must be at least one BusinessTransactionView
            if (count_btv < 1)
            {
                context.AddValidationMessage(new ValidationMessage("Violation of constraint C31.", "A BusinessChoreographyView MUST contain one to many BusinessTransactionViews. \n\nNo BusinessTransactionView could be found.", "BCV", ValidationMessage.errorLevelTypes.ERROR, bcv.PackageID));
            }
        }
Beispiel #29
0
        public Property(
            Expression expression,
            Localizable name,
            TValue initial,
            IPropertyConfiguration configuration,
            IValidationContext validationContext,
            Func <TValue> getter,
            Action <TValue> setter,
            IEnumerable <IValidator <TValue> > validators)
        {
            Name          = name;
            Configuration = configuration;

            _expression        = expression;
            _initial           = initial;
            _validationContext = validationContext;
            _getter            = getter;
            _setter            = setter;
            _validators        = validators;
        }
        /// <summary>
        /// Инициализирует экземпляр класса <see cref="ApplicationBus"/>, используя
        /// в качестве родительского контекста <paramref name="parentModelContext"/>.
        /// </summary>
        /// <param name="parentModelContext"></param>
        public ApplicationBus(
            IModelContext parentModelContext, 
            IEnumerable<IApplicationBusMessageHandler> handlers)
        {
            if (parentModelContext == null)
            {
                throw new ArgumentNullException("parentModelContext");
            }

            _context = parentModelContext.CreateChildContext(
                ContextHierarchy.ApplicationBus, 
                x => x.RegisterInstance(this).As<IApplicationBus>().AsSelf());

            _validationContext = _context.Get<IValidationContext>();

            foreach (var handler in handlers)
            {
                RegisterHandler(handler);
            }
        }
        public async Task Prepare(IValidationContext context)
        {
            context.RequestedFields.Add(FieldNames.AreaPath);
            context.RequestedFields.Add(FieldNames.IterationPath);

            Logger.LogInformation("Reading the area and iteration paths from the source and target accounts");

            try
            {
                var classificationNodes = await WorkItemTrackingHelpers.GetClassificationNodes(context.TargetClient.WorkItemTrackingHttpClient, context.Config.TargetConnection.Project);

                var nodes = new AreaAndIterationPathTree(classificationNodes);
                context.TargetAreaPaths      = nodes.AreaPathList;
                context.TargetIterationPaths = nodes.IterationPathList;
            }
            catch (Exception e)
            {
                throw new ValidationException("Unable to read the classification nodes on the source", e);
            }
        }
Beispiel #32
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var id        = context.GetArgument <Guid>("id");

            var comment = await databaseContext
                          .CardComments
                          .FirstOrDefaultAsync(x => x.Id == id && x.AccountId == accountId);

            validationContext.When("id")
            .Is(() => comment == null)
            .AddValidationDetail("Комментарий не найден");

            if (comment != null)
            {
                validationContext.When()
                .Is(() => comment.CreatedAt.AddHours(1) < DateTime.UtcNow)
                .AddValidationDetail("Комментарий можно удалить только в первый час создания");
            }
        }
Beispiel #33
0
        /// <summary>
        /// A BCC name and an ASCC name shall not be identical when used in an ACC.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        /// <param name="accs"></param>
        private void checkC524l(IValidationContext context, EA.Package p, Dictionary <Int32, EA.Element> accs)
        {
            Dictionary <string, string> names = new Dictionary <string, string>();

            foreach (KeyValuePair <Int32, EA.Element> e in accs)
            {
                //Get all ASCCs
                foreach (EA.Connector con in e.Value.Connectors)
                {
                    //Get all emanating ASCCs of this ACC
                    if (con.Stereotype == UPCC.ASCC.ToString() && con.ClientID == e.Value.ElementID)
                    {
                        //Get the role name of the ASCC
                        String rolename = con.SupplierEnd.Role;


                        if (names.ContainsValue(rolename))
                        {
                            if (rolename == null || rolename == "")
                            {
                                rolename = "No name specified.";
                            }

                            context.AddValidationMessage(new ValidationMessage("Duplicate names of BCCs/ASCCs found.", "A BCC name and an ASCC name shall not be identical when used in an ACC. ACC " + e.Value.Name + " has a BBIE and an ASCC with the same name: " + rolename, "CCLibrary", ValidationMessage.errorLevelTypes.ERROR, p.PackageID));
                        }
                        names.Add(rolename, rolename);
                    }
                }

                //Get all BCCs
                foreach (EA.Attribute bcc in e.Value.Attributes)
                {
                    if (names.ContainsValue(bcc.Name))
                    {
                        context.AddValidationMessage(new ValidationMessage("Duplicate names of BCCs/ASCCs found.", "A BCC name and an ASCC name shall not be identical when used in an ACC. ACC " + e.Value.Name + " has a BBIE and an ASCC with the same name: " + bcc.Name, "CCLibrary", ValidationMessage.errorLevelTypes.ERROR, p.PackageID));
                    }
                    names.Add(bcc.Name, bcc.Name);
                }
                names = new Dictionary <string, string>();
            }
        }
Beispiel #34
0
        protected override PropertySetResult Validate(
            PropertyLite property,
            ChoicePropertyType propertyType,
            IValidationContext validationContext)
        {
            if (IsPropertyValueEmpty(property, propertyType) && propertyType.IsRequired)
            {
                return(new PropertySetResult(property.PropertyTypeId, ErrorCodes.InvalidArtifactProperty, "Custom value or choices should be specified if the field is required."));
            }

            if (!String.IsNullOrEmpty(property.TextOrChoiceValue) && property.ChoiceIds.Count != 0)
            {
                return(new PropertySetResult(property.PropertyTypeId, ErrorCodes.InvalidArtifactProperty, "Custom value and choices cannot be specified simultaneously."));
            }

            if (propertyType.IsValidate && !String.IsNullOrEmpty(property.TextOrChoiceValue))
            {
                return(new PropertySetResult(property.PropertyTypeId, ErrorCodes.InvalidArtifactProperty, "Property does not support custom values."));
            }

            if (!propertyType.AllowsCustomValue() && property.ChoiceIds.Count == 0 && propertyType.IsRequired)
            {
                return(new PropertySetResult(property.PropertyTypeId, ErrorCodes.InvalidArtifactProperty, "Required property value should be specified."));
            }

            if (propertyType.AllowMultiple != true && property.ChoiceIds.Count > 1)
            {
                return(new PropertySetResult(property.PropertyTypeId, ErrorCodes.InvalidArtifactProperty, "Only single choice is allowed."));
            }

            var items            = propertyType.ValidValues;
            var hasInvalidChoice = property.ChoiceIds.Any(c => items.All(i => i.Sid != c));

            if (hasInvalidChoice)
            {
                return(new PropertySetResult(property.PropertyTypeId, ErrorCodes.InvalidArtifactProperty, "Specified choice value does not exist."));
            }

            // Success.
            return(null);
        }
        /// <summary>
        /// Проверяет указанную в <paramref name="value"/> дату на корректность.
        /// </summary>
        /// 
        /// <param name="value">Проверяемая дата</param>
        /// <param name="context">Валидационный контекст.</param>
        /// 
        /// <exception cref="InvalidOperationException">
        ///   Параметр <paramref name="value"/> задан, но не является экземпляром типа <see cref="DateTime"/>.
        /// </exception>
        public void Validate(IValidationContext context, object value)
        {
            if (value == null)
            {
                return;
            }

            if (!(value is DateTime))
            {
                throw new InvalidOperationException(
                    String.Format(Resources.Strings.SqlDateTimeValidatorInvalidObject, GetType(), value.GetType()));
            }

            var dateTime = (DateTime)value;

            var isValid = ((dateTime >= (DateTime)SqlDateTime.MinValue) && (dateTime <= (DateTime)SqlDateTime.MaxValue));
            if (!isValid)
            {
                context.AddError(Message ?? Resources.Strings.SqlDateTimeValidatorMessage);
            }
        }
        /// <summary>
        /// A BDT which is the source of an isEquivalentTo dependency shall have the same number of supplementary
        /// components as the BDT the dependency is targeting.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        /// <param name="bdts"></param>
        private void checkC564i(IValidationContext context, EA.Package p, Dictionary <Int32, EA.Element> bdts)
        {
            foreach (KeyValuePair <Int32, EA.Element> e in bdts)
            {
                if (Utility.isEquivalentToAnotherElement(e.Value))
                {
                    int countSUP = Utility.countAttributesOfElement(e.Value, UPCC.SUP.ToString());


                    //Count the supplementary attributes of the BDT which is the target of the isEquivalentDependency
                    EA.Element supplierElement      = Utility.getTargetOfisEquivalentToDependency(e.Value, context.Repository);
                    int        countSUP_of_supplier = Utility.countAttributesOfElement(supplierElement, UPCC.SUP.ToString());

                    //Do both BDT have the same amount of SUPs?
                    if (countSUP != countSUP_of_supplier)
                    {
                        context.AddValidationMessage(new ValidationMessage("Invalid number of supplementary components found.", "A BDT which is the source of an isEquivalentTo dependency shall have the same number of supplementary components as the BDT the dependency is targeting. The source BDT " + e.Value.Name + " has " + countSUP + " supplementary components but the BDT " + supplierElement.Name + " which is targeted by an isEquivalent dependency has " + countSUP_of_supplier + " supplementary components.", "BDTLibrary", ValidationMessage.errorLevelTypes.ERROR, p.PackageID));
                    }
                }
            }
        }
        /// <summary>
        /// Validate the given PRIMLibrary
        /// </summary>
        /// <param name="context"></param>
        /// <param name="scope"></param>
        internal override void validate(IValidationContext context, string scope)
        {
            EA.Package package = context.Repository.GetPackageByID(Int32.Parse(scope));

            //Get all PRIMs from the given package
            Dictionary <Int32, EA.Element> prims = new Dictionary <int, EA.Element>();

            Utility.getAllElements(package, prims, UPCC.PRIM.ToString());

            checkC514h(context, package);

            checkC514n(context, package);

            checkC544a(context, package, prims);

            checkC544b(context, package, prims);

            checkC544c(context, package, prims);

            checkC544d(context, package, prims);
        }
        /// <summary>
        /// Check the tagged values of the business partner view
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        private void checkTV_BusinessPartnerView(IValidationContext context, EA.Package p)
        {
            //Check the TaggedValues of the bPartnerV
            new TaggedValueValidator().validatePackage(context, p);

            //Check the TaggedValues of the different Stakeholders
            IList <EA.Element> stakeholders = Utility.getAllElements(p, new List <EA.Element>(), UMM.Stakeholder.ToString());

            foreach (EA.Element sth in stakeholders)
            {
                new TaggedValueValidator().validateElement(context, sth);
            }

            //Check the TaggedValues of the different BusinessParnters
            IList <EA.Element> businessPartners = Utility.getAllElements(p, new List <EA.Element>(), UMM.bPartner.ToString());

            foreach (EA.Element bpartner in businessPartners)
            {
                new TaggedValueValidator().validateElement(context, bpartner);
            }
        }
        /// <summary>
        /// Check constraint C3
        /// </summary>
        private void checkC3(IValidationContext context)
        {
            //This constraint is not validated but only an info is given back to the user

            EA.Collection rootPackages = ((EA.Package)(context.Repository.Models.GetAt(0))).Packages;
            int           count        = 0;

            if (rootPackages != null)
            {
                //Iterate over the different packages
                foreach (EA.Package p in rootPackages)
                {
                    if (p.Element != null && p.Element.Stereotype == UMM.bRequirementsV.ToString())
                    {
                        count++;
                    }
                }
            }

            context.AddValidationMessage(new ValidationMessage("Information to constraint C3.", "A BusinessCollaborationModel MAY containt zero to many BusinessRequirementsViews. \n\nYour model contains " + count + " BusinessRequirementsViews.", "BCM", ValidationMessage.errorLevelTypes.INFO, 0));
        }
        private bool CompareField(IValidationContext context, WorkItemField source, WorkItemField target)
        {
            var matches = true;

            if (source.Type != target.Type)
            {
                matches = false;
                Logger.LogWarning(LogDestination.File, $"Target: Field {source.ReferenceName} of type {source.Type} is not of the same type {target.Type}");
            }

            if (matches)
            {
                context.ValidatedFields.Add(source.ReferenceName);
            }
            else
            {
                context.SkippedFields.Add(source.ReferenceName);
            }

            return(matches);
        }
 /// <summary>
 /// A bLibrary may only containt packages of type
 /// BDTLibrary, BIELibrary, CCLibrary, DOCLibrary, ENUMLibrary and PRIMLibrary
 /// </summary>
 /// <param name="context"></param>
 /// <param name="brv"></param>
 private void checkC514a(IValidationContext context, EA.Package d)
 {
     foreach (EA.Package p in d.Packages)
     {
         bool found = false;
         //Get the stereotype of the package
         String stereotype = p.Element.Stereotype;
         foreach (UPCC_Packages upcc in Enum.GetValues(typeof(UPCC_Packages)))
         {
             if (upcc.ToString().Equals(stereotype))
             {
                 found = true;
                 break;
             }
         }
         if (!found)
         {
             context.AddValidationMessage(new ValidationMessage("Package with invalid stereotype found.", "Package " + p.Name + " has an invalid stereotype (" + stereotype + "). A bLibrary shall only contain packages of type bLibrary, BDTLibrary, BIELibrary, CCLibrary, CDTLibrary, DOCLibrary, ENUMLibrary and no other elements.", "bLibrary", ValidationMessage.errorLevelTypes.ERROR, d.PackageID));
         }
     }
 }
Beispiel #42
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var inviteId  = context.GetArgument <Guid>("id");

            var invite = await databaseContext
                         .Invites
                         .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                         .FirstOrDefaultAsync(x => x.Id == inviteId);

            validationContext.When("id")
            .Is(() => invite == null)
            .AddValidationDetail("Приглашение не найдено");

            if (validationContext.IsValid("id"))
            {
                validationContext.When("id")
                .Is(() => invite.AccountId != null)
                .AddValidationDetail("Нельзя удалить использованное приглашение");
            }
        }
Beispiel #43
0
        public IEnumerable <Localizable> Validate(
            IComponentContext <DepthBuffer> context,
            IValidationContext validationContext,
            DepthBuffer depthBuffer)
        {
            if (depthBuffer.LinearZFar <= depthBuffer.LinearZNear)
            {
                yield return(new Localizable(
                                 "ValueLessThan",
                                 context.GetComponentName(entity => entity.LinearZFar),
                                 context.GetComponentName(entity => entity.LinearZNear)));
            }

            if (depthBuffer.DepthMaximum <= depthBuffer.DepthMinimum)
            {
                yield return(new Localizable(
                                 "ValueLessThan",
                                 context.GetComponentName(entity => entity.DepthMaximum),
                                 context.GetComponentName(entity => entity.DepthMinimum)));
            }
        }
Beispiel #44
0
 public ExecutionParameters(
     int userId,
     VersionControlArtifactInfo artifactInfo,
     ItemTypeReuseTemplate reuseTemplate,
     List <WorkflowPropertyType> customPropertyTypes,
     ISaveArtifactRepository saveArtifactRepository,
     IDbTransaction transaction,
     IValidationContext validationContext,
     IReadOnlyList <IPropertyValidator> validators,
     IReusePropertyValidator reuseValidator)
 {
     UserId              = userId;
     ArtifactInfo        = artifactInfo;
     ReuseItemTemplate   = reuseTemplate;
     CustomPropertyTypes = customPropertyTypes;
     SaveRepository      = saveArtifactRepository;
     Transaction         = transaction;
     Validators          = validators;
     ReuseValidator      = reuseValidator;
     ValidationContext   = validationContext;
 }
        /// <summary>
        /// Checks the TV of the Stereotypes from the Business Domain View
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        private void checkTV_BusinessDomainViews(IValidationContext context, EA.Package p)
        {
            //Get all BusinessAreas
            IList <EA.Package> bAreas = Utility.getAllSubPackagesWithGivenStereotypeRecursively(p, new List <EA.Package>(),
                                                                                                UMM.bArea.ToString());
            //Get all ProcessAreas
            IList <EA.Package> pAreas = Utility.getAllSubPackagesWithGivenStereotypeRecursively(p, new List <EA.Package>(),
                                                                                                UMM.ProcessArea.ToString());

            //Check the TaggedValues of the BusinessDomainView package
            new TaggedValueValidator().validatePackage(context, p);

            //Check all BusinessAreas
            foreach (EA.Package bArea in bAreas)
            {
                new TaggedValueValidator().validatePackage(context, bArea);
            }

            //Check all ProcressAreas
            foreach (EA.Package pArea in pAreas)
            {
                new TaggedValueValidator().validatePackage(context, pArea);
            }

            //Get all BusinessProcessUseCases recursively from the Business Domain View
            IList <EA.Element>  bPUCs      = Utility.getAllElements(p, new List <EA.Element>(), UMM.bProcessUC.ToString());
            List <EA.Connector> connectors = new List <EA.Connector>();

            foreach (EA.Element bPUC in bPUCs)
            {
                new TaggedValueValidator().validateElement(context, bPUC);
                foreach (EA.Connector con in bPUC.Connectors)
                {
                    connectors.Add(con);
                }
            }

            //Validate the participates and isOfInterestTo connectors
            new TaggedValueValidator().validateConnectors(context, connectors);
        }
        public IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, IValidationContext validationContext, object container)
        {
            if (metadata.Model == null) return Enumerable.Empty<ModelValidationResult>();

            CustomizeValidatorAttribute validatorAttribute = null;

            foreach (var param in validationContext.ActionContext.ActionDescriptor.GetParameters()
                .Where(p => p.ParameterType == metadata.ModelType)) {
                validatorAttribute = param.GetCustomAttributes<CustomizeValidatorAttribute>().FirstOrDefault();
                if (validatorAttribute != null) break;
            }

            if(validatorAttribute == null)
                validatorAttribute = new CustomizeValidatorAttribute();

            var selector = validatorAttribute.ToValidatorSelector();
            var interceptor = validatorAttribute.GetInterceptor();
            
            var context = new ValidationContext(metadata.Model, new PropertyChain(), selector);

            if (interceptor != null)
            {
                // Allow the user to provide a customized context
                // However, if they return null then just use the original context.
                context = interceptor.BeforeWebApiValidation(validationContext.ActionContext, metadata, context) ?? context;
            }

            var result = validator.Validate(context);

            if (interceptor != null)
            {
                // allow the user to provice a custom collection of failures, which could be empty.
                // However, if they return null then use the original collection of failures. 
                result = interceptor.AfterWebApiValidation(validationContext.ActionContext, metadata, context, result) ?? result;
            }

            return !result.IsValid 
                ? ConvertValidationResultToModelValidationResults(result) 
                : Enumerable.Empty<ModelValidationResult>();
        }
Beispiel #47
0
        /// <summary>
        /// Determines whether or not a rule should execute.
        /// </summary>
        /// <param name="rule">The rule</param>
        /// <param name="propertyPath">Property path (eg Customer.Address.Line1)</param>
        /// <param name="context">Contextual information</param>
        /// <returns>Whether or not the validator can execute.</returns>
        public bool CanExecute(IValidationRule rule, string propertyPath, IValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

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

            var dependencies = context.GetDependencies(propertyPath);

            if (rule != null)
            {
                dependencies = dependencies.Concat(rule.GetDependencies(context));
            }

            if (HasIndexers)
            {
                propertyPath = IndexerMatcher.Value.Replace(propertyPath, "[]");
                dependencies = dependencies.Select(propertyPath => IndexerMatcher.Value.Replace(propertyPath, "[]"));
            }

            // Validator selector only applies to the top level.
            // If we're running in a child context then this means that the child validator has already been selected
            // Because of this, we assume that the rule should continue (i.e. if the parent rule is valid, all children are valid)
            var isChildContext = context.IsChildContext;
            var cascadeEnabled = !context.RootContextData.ContainsKey(DisableCascadeKey);

            return(isChildContext && cascadeEnabled && !PropertyPaths.Any(x => x.Contains('.')) ||
                   rule is IIncludeRule ||
                   Matches(propertyPath) ||
                   dependencies.Any(Matches));

            bool Matches(string otherPath) => PropertyPaths.Any(path => path == otherPath ||
                                                                IsSubPath(otherPath, path) ||
                                                                IsSubPath(path, otherPath));
        }
        public void ValidateFieldsMapping(IValidationContext context)
        {
            if (context.Config.FieldReplacements == null)
            {
                return;
            }

            foreach (var sourceToTargetFields in context.Config.FieldReplacements)
            {
                string         sourceField    = sourceToTargetFields.Key;
                TargetFieldMap targetFieldMap = sourceToTargetFields.Value;

                if (context.FieldsThatRequireSourceProjectToBeReplacedWithTargetProject.Contains(sourceField, StringComparer.OrdinalIgnoreCase) || context.FieldsThatRequireSourceProjectToBeReplacedWithTargetProject.Contains(targetFieldMap.FieldReferenceName, StringComparer.OrdinalIgnoreCase))
                {
                    string unsupportedFields = string.Join(", ", context.FieldsThatRequireSourceProjectToBeReplacedWithTargetProject);
                    throw new ValidationException($"Source fields or field-reference-name cannot be set to any of: {unsupportedFields} in the configuration file.");
                }

                if (!context.SourceFields.ContainsKeyIgnoringCase(sourceField))
                {
                    throw new ValidationException($"Source fields do not contain {sourceField} that is specified in the configuration file.");
                }

                if (targetFieldMap.Value != null && targetFieldMap.FieldReferenceName != null)
                {
                    throw new ValidationException($"Under fields in config, for source field: {sourceField}, you must specify value or field-reference-name, but not both.");
                }
                else if (targetFieldMap.Value == null && string.IsNullOrEmpty(targetFieldMap.FieldReferenceName))
                {
                    throw new ValidationException($"Under fields in config, for source field: {sourceField}, you must specify value or field-reference-name.");
                }
                else if (!string.IsNullOrEmpty(targetFieldMap.FieldReferenceName))
                {
                    if (!context.TargetFields.ContainsKeyIgnoringCase(targetFieldMap.FieldReferenceName))
                    {
                        throw new ValidationException($"Target does not contain the field-reference-name you provided: {targetFieldMap.FieldReferenceName}.");
                    }
                }
            }
        }
        private async Task <IList <WorkItemMigrationState> > FilterWorkItemIds(IValidationContext context, WorkItemTrackingHttpClient client, IDictionary <int, string> workItems)
        {
            // call GetWorkItemIdsForArtifactUrisAsync for target client to get the mapping of artifacturis and ids
            // do a check to see if any of them have already been migrated
            var artifactUris = workItems.Select(a => a.Value).ToList();
            var result       = await ClientHelpers.QueryArtifactUriToGetIdsFromUris(client, artifactUris);

            IList <WorkItemMigrationState> workItemStateList = new List <WorkItemMigrationState>();

            //check if any of the workitems have been migrated before
            foreach (var workItem in workItems)
            {
                try
                {
                    if (ClientHelpers.GetMigratedWorkItemId(result, workItem, out int id))
                    {
                        workItemStateList.Add(new WorkItemMigrationState {
                            SourceId = workItem.Key, TargetId = id, MigrationState = WorkItemMigrationState.State.Existing
                        });
                    }
                    else
                    {
                        workItemStateList.Add(new WorkItemMigrationState {
                            SourceId = workItem.Key, MigrationState = WorkItemMigrationState.State.Create
                        });
                    }
                }
                catch (Exception e)
                {
                    //edge case where we find more than one workitems in the target for the workitem
                    Logger.LogError(LogDestination.File, e, e.Message);
                    //Add this workitem to notmigratedworkitem list
                    workItemStateList.Add(new WorkItemMigrationState {
                        SourceId = workItem.Key, MigrationState = WorkItemMigrationState.State.Error
                    });
                }
            }

            return(workItemStateList);
        }
Beispiel #50
0
        /// <summary>
        /// Called when the object is validating the business rules.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        protected override void OnValidatingBusinessRules(IValidationContext validationContext)
        {
            base.OnValidatingBusinessRules(validationContext);

            lock (_modelLock)
            {
                foreach (var modelObject in _modelObjects)
                {
                    // IDataErrorInfo
                    var dataErrorInfo = modelObject.Value as IDataErrorInfo;
                    if ((dataErrorInfo != null) && !string.IsNullOrEmpty(dataErrorInfo.Error))
                    {
                        validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(dataErrorInfo.Error));
                    }

                    // IDataWarningInfo
                    var dataWarningInfo = modelObject.Value as IDataWarningInfo;
                    if ((dataWarningInfo != null) && !string.IsNullOrEmpty(dataWarningInfo.Warning))
                    {
                        validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(dataWarningInfo.Warning));
                    }

                    // INotifyDataErrorInfo & INotifyDataWarningInfo
                    if (_modelErrorInfo.ContainsKey(modelObject.Key))
                    {
                        var modelErrorInfo = _modelErrorInfo[modelObject.Key];

                        foreach (var error in modelErrorInfo.GetErrors(string.Empty))
                        {
                            validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(error));
                        }

                        foreach (var warning in modelErrorInfo.GetWarnings(string.Empty))
                        {
                            validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(warning));
                        }
                    }
                }
            }
        }
Beispiel #51
0
 public CertPathRevocationAnalysis(IValidationContext ctx, TrustedListInformation info)
 {
     summary = new SignatureValidationResult();
     trustedListInformation = info;
     if (ctx != null && ctx.NeededCertificates != null)
     {
         foreach (CertificateAndContext cert in ctx.NeededCertificates)
         {
             CertificateVerification verif = new CertificateVerification(cert, ctx);
             certificatePathVerification.Add(verif);
         }
     }
     summary.SetStatus(ResultStatus.VALID, null);
     if (certificatePathVerification != null)
     {
         foreach (CertificateVerification verif in certificatePathVerification)
         {
             if (verif.Summary.IsInvalid)
             {
                 summary.SetStatus(ResultStatus.INVALID, verif.Summary.Description ?? "$UI_Signatures_ValidationText_CertificateIsNotValid");
                 break;
             }
             if (verif.Summary.IsUndetermined)
             {
                 summary.SetStatus(ResultStatus.UNDETERMINED, verif.Summary.Description ?? "$UI_Signatures_ValidationText_NoRevocationData");
             }
         }
     }
     if (trustedListInformation != null)
     {
         if (!trustedListInformation.IsServiceWasFound)
         {
             summary.SetStatus(ResultStatus.INVALID, "$UI_Signatures_ValidationText_NoTrustedListServiceWasFound");
         }
     }
     else
     {
         summary.SetStatus(ResultStatus.INVALID, "$UI_Signatures_ValidationText_NoTrustedListServiceWasFound");
     }
 }
Beispiel #52
0
        /// <summary>
        /// For a given BIELibrary there shall not be two ABIEs with the same unique identifier tagged value.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        /// <param name="bies"></param>
        private void checkC574j(IValidationContext context, EA.Package p, Dictionary <Int32, EA.Element> bies)
        {
            Dictionary <Int32, string> values = new Dictionary <Int32, string>();

            foreach (KeyValuePair <Int32, EA.Element> e in bies)
            {
                EA.TaggedValue tv = Utility.getTaggedValue(e.Value, UPCC_TV.uniqueIdentifier.ToString());
                if (tv != null)
                {
                    //Has this unique identifier already been used?
                    if (values.ContainsValue(tv.Value))
                    {
                        //Get the other element with the same unique identifier
                        EA.Element duplicateElement = context.Repository.GetElementByID(Utility.findKey(values, tv.Value));

                        context.AddValidationMessage(new ValidationMessage("Two identical unique identifier tagged values of a BIE detected.", "The unique identifier tagged value of a BIE shall be unique for a given BIE library. " + e.Value.Name + " and " + duplicateElement.Name + " in BIELibrary " + p.Name + " have the same unique identifier.", "BIELibrary", ValidationMessage.errorLevelTypes.ERROR, p.PackageID));
                    }

                    values.Add(e.Value.ElementID, tv.Value);
                }
            }
        }
        /// <summary>
        /// BDT supplementary component cardinality shall be equal to [0..1] if the BDT supplementary component is optional, or [1..1] if mandatory.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        /// <param name="bdts"></param>
        private void checkC564o(IValidationContext context, EA.Package p, Dictionary <Int32, EA.Element> bdts)
        {
            foreach (KeyValuePair <Int32, EA.Element> e in bdts)
            {
                //Fetch all attributes of the given element
                Dictionary <string, EA.Attribute> attributes = Utility.fetchAllAttributesFromElement(e.Value, UPCC.SUP.ToString());

                foreach (KeyValuePair <string, EA.Attribute> a in attributes)
                {
                    String lowerBound = a.Value.LowerBound;
                    String upperBound = a.Value.UpperBound;

                    //The only allowed combinations for the cardinality are [0..1] and [1..1]
                    //[0..1] = lowerBound = 0, upperBound = 1
                    //[1..1] = lowerBound = 1, upperBound = 1 || lowerBound = "", upperBound = ""
                    if (!Utility.isValid_0_1_or_1_1_Cardinality(lowerBound, upperBound))
                    {
                        context.AddValidationMessage(new ValidationMessage("Invalid cardinality found for a BDT.", "BDT supplementary component cardinality shall be equal to [0..1] if the BDT supplementary component is optional, or [1..1] if mandatory. Attribute " + a.Value.Name + " in ACC " + e.Value.Name + " has an invalid cardinality: lower bound: " + lowerBound + " upper bound " + upperBound + ".", "BDTLibrary", ValidationMessage.errorLevelTypes.ERROR, p.PackageID));
                    }
                }
            }
        }
Beispiel #54
0
        public static IFieldInfo Create(PropertyInfo prop, IEditableRoot editableRoot, IField field, object rawValue, IValidationContext validationContext)
        {
            var customAttr = prop.GetCustomAttribute<CommonSettingsAttribute>();
            var promptAttr = prop.GetCustomAttribute<PromptAttribute>();
            var docAttr = prop.GetCustomAttribute<DocumentationAttribute>();
            var fieldTypeAttr = prop.GetCustomAttribute<FieldTypeAttribute>();
            var hasCalculatedAttr = prop.GetCustomAttributes(typeof(CalculatedAttribute), false).Any();
            var hasDefaultExpressionAttr = prop.GetCustomAttributes(typeof(HasDefaultExpressionAttribute), false).Any();

            //Set common properties
            var fieldInfo = CreateFieldInfo(fieldTypeAttr.ColumnType, prop, rawValue, editableRoot);
            fieldInfo.Id = editableRoot.Id;
            fieldInfo.SystemName = field.SystemName;
            fieldInfo.DisplayName = customAttr.Name;
            fieldInfo.Width = customAttr.Width;
            fieldInfo.CanRead = editableRoot.CanReadProperty(prop.Name);
            fieldInfo.IsRequired = validationContext != null && validationContext.IsRequired(editableRoot.ProcessName, field.SystemName, editableRoot.GetCurrentStateGuid());
            fieldInfo.CanRead = editableRoot.CanReadProperty(prop.Name);
            fieldInfo.CanWrite = editableRoot.CanWriteProperty(prop.Name) && !hasCalculatedAttr;
            fieldInfo.BackColor = GetBackColor(editableRoot, prop);
            fieldInfo.Prompt = promptAttr == null
                ? string.Format(CultureInfo.InvariantCulture,
                    LanguageService.Translate("Tooltip_EnterPrompt"), customAttr.Name)
                : promptAttr.PromptString;

            fieldInfo.IsDocumentationAvailable = docAttr != null;

            if (hasCalculatedAttr || hasDefaultExpressionAttr)
            {
                fieldInfo.ExpressionType = hasCalculatedAttr ? FieldExpressionType.Calculated : FieldExpressionType.Default;
                fieldInfo.Expression = GetExpression(editableRoot, prop);
            }

            // docAttr == null ? string.Empty : ClrUnicodeConverter.ToText(docAttr.DocumentationBody),

            return fieldInfo;
        }
 public void Validate(IValidationContext context, object obj)
 {
     _attributesValidator.Validate(context, obj);
     _validatableObjectValidator.Validate(context, obj);
 }
 /// <summary>
 /// Called when the object is validated.
 /// </summary>
 /// <param name="validationContext">The validation context.</param>
 protected virtual void OnValidated(IValidationContext validationContext)
 {
     var handler = _validated;
     if (handler != null)
     {
         handler(this, new ValidationEventArgs(validationContext));
     }
 }
 /// <summary>
 /// Called when the object has validated the business rules.
 /// </summary>
 /// <param name="validationContext">The validation context.</param>
 protected virtual void OnValidatedBusinessRules(IValidationContext validationContext)
 {
     ValidatedBusinessRules.SafeInvoke(this);
 }
 /// <summary>
 /// Called when the object has validated the fields.
 /// </summary>
 /// <param name="validationContext">The validation context.</param>
 protected virtual void OnValidatedFields(IValidationContext validationContext)
 {
     ValidatedFields.SafeInvoke(this);
 }
Beispiel #59
0
        /// <summary>
        /// Gets the changes between two different validation contexts.
        /// </summary>
        /// <param name="firstContext">The first context.</param>
        /// <param name="secondContext">The second context.</param>
        /// <returns>The list of changes.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="firstContext"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="secondContext"/> is <c>null</c>.</exception>
        public static List<ValidationContextChange> GetChanges(IValidationContext firstContext, IValidationContext secondContext)
        {
            Argument.IsNotNull("firstContext", firstContext);
            Argument.IsNotNull("secondContext", secondContext);

            var changes = new List<ValidationContextChange>();

            // Loop all fields, check removed items
            foreach (var fieldValidationResult in firstContext.GetFieldValidations())
            {
                var secondContextFieldValidationResults = secondContext.GetFieldValidations(fieldValidationResult.PropertyName);
                bool stillContainsValidationResult = (from result in secondContextFieldValidationResults
                                                      where result.ValidationResultType == fieldValidationResult.ValidationResultType &&
                                                            string.Compare(result.Message, fieldValidationResult.Message) == 0
                                                      select result).Any();

                if (!stillContainsValidationResult)
                {
                    changes.Add(new ValidationContextChange(fieldValidationResult, ValidationContextChangeType.Removed));
                }
            }

            // Loop all fields, check added items
            foreach (var fieldValidationResult in secondContext.GetFieldValidations())
            {
                var firstContextFieldValidationResults = firstContext.GetFieldValidations(fieldValidationResult.PropertyName);
                bool existedInPreviousVersion = (from result in firstContextFieldValidationResults
                                                 where result.ValidationResultType == fieldValidationResult.ValidationResultType &&
                                                       string.Compare(result.Message, fieldValidationResult.Message) == 0
                                                 select result).Any();

                if (!existedInPreviousVersion)
                {
                    changes.Add(new ValidationContextChange(fieldValidationResult, ValidationContextChangeType.Added));
                }
            }

            // Loop all business rules, check removed items
            foreach (var businessRuleValidation in firstContext.GetBusinessRuleValidations())
            {
                var secondContextBusinessRuleValidationResults = secondContext.GetBusinessRuleValidations();
                bool stillContainsValidationResult = (from result in secondContextBusinessRuleValidationResults
                                                      where result.ValidationResultType == businessRuleValidation.ValidationResultType &&
                                                            string.Compare(result.Message, businessRuleValidation.Message) == 0
                                                      select result).Any();

                if (!stillContainsValidationResult)
                {
                    changes.Add(new ValidationContextChange(businessRuleValidation, ValidationContextChangeType.Removed));
                }
            }

            // Loop all business rules, check added items
            foreach (var businessRuleValidation in secondContext.GetBusinessRuleValidations())
            {
                var firstContextBusinessRuleValidationResults = firstContext.GetBusinessRuleValidations();
                bool existedInPreviousVersion = (from result in firstContextBusinessRuleValidationResults
                                                 where result.ValidationResultType == businessRuleValidation.ValidationResultType &&
                                                       string.Compare(result.Message, businessRuleValidation.Message) == 0
                                                 select result).Any();

                if (!existedInPreviousVersion)
                {
                    changes.Add(new ValidationContextChange(businessRuleValidation, ValidationContextChangeType.Added));
                }
            }

            return changes;
        }
        protected override void OnValidated(IValidationContext validationContext)
        {
            base.OnValidated(validationContext);

            IsValid = !validationContext.HasErrors;
        }