public void ValidateSpecificDependencyDiagram(ValidationContext context)
 {
     if (this.DomainClass == null)
     {
         context.LogError("The specific diagram class " + this.Title + " needs to reference a Domain Class.", "MissingDomainClassReference", null); //this);
     }
 }
        public void Validate(ValidationAttribute attribute, object value, ValidationContext validationContext, bool isValid)
        {
            if (isValid)
            {
                attribute.Validate(value, validationContext);
                Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext));

                // Run the validation twice, in case attributes cache anything
                attribute.Validate(value, validationContext);
                Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext));
            }
            else
            {
                Assert.Throws<ValidationException>(() => attribute.Validate(value, validationContext));
                Assert.NotNull(attribute.GetValidationResult(value, validationContext));

                // Run the validation twice, in case attributes cache anything
                Assert.Throws<ValidationException>(() => attribute.Validate(value, validationContext));
                Assert.NotNull(attribute.GetValidationResult(value, validationContext));
            }
            if (!attribute.RequiresValidationContext)
            {
                Assert.Equal(isValid, attribute.IsValid(value));

                // Run the validation twice, in case attributes cache anything
                Assert.Equal(isValid, attribute.IsValid(value));
            }
        }
        internal void ValidateNameIsUnique(ValidationContext context)
        {
            try
            {
                IEnumerable<PatternElementSchema> sameNamedElements;
                if (this.View != null)
                {
                    // Get siblings in the owning view
                    sameNamedElements = this.View.AllElements()
                        .Where(element => element.Name.Equals(this.Name, System.StringComparison.OrdinalIgnoreCase));
                }
                else
                {
                    // Get siblings in the owning element
                    sameNamedElements = this.Owner.AllElements()
                        .Where(element => element.Name.Equals(this.Name, System.StringComparison.OrdinalIgnoreCase));
                }

                if (sameNamedElements.Count() > 1)
                {
                    context.LogError(
                        string.Format(CultureInfo.CurrentCulture, Resources.Validate_PatternElementNameIsNotUnique, this.Name),
                        Resources.Validate_PatternElementNameIsNotUniqueCode, this);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector<ExtensionPointSchema>.GetMethod(n => n.ValidateNameIsUnique(context)).Name);

                throw;
            }
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            return new EnterLeaveListener(_ =>
            {
                _.Match<InlineFragment>(node =>
                {
                    var type = context.TypeInfo.GetLastType();
                    if (node.Type != null && type != null && !type.IsCompositeType())
                    {
                        context.ReportError(new ValidationError(
                            context.OriginalQuery,
                            "5.4.1.3",
                            InlineFragmentOnNonCompositeErrorMessage(context.Print(node.Type)),
                            node.Type));
                    }
                });

                _.Match<FragmentDefinition>(node =>
                {
                    var type = context.TypeInfo.GetLastType();
                    if (type != null && !type.IsCompositeType())
                    {
                        context.ReportError(new ValidationError(
                            context.OriginalQuery,
                            "5.4.1.3",
                            FragmentOnNonCompositeErrorMessage(node.Name, context.Print(node.Type)),
                            node.Type));
                    }
                });
            });
        }
Beispiel #5
0
 public INodeVisitor Validate(ValidationContext context)
 {
     return new EnterLeaveListener(_ =>
     {
         _.Match<Field>(f => Field(context.TypeInfo.GetLastType(), f, context));
     });
 }
        internal void ValidateWizardIdIsValid(ValidationContext context)
        {
            try
            {
                if (this.WizardId != Guid.Empty)
                {
                    if (!this.Owner.GetAutomationSettings<IWizardSettings>().Any(c => c.Id.Equals(this.WizardId)))
                    {
                        if (this.Owner.IsInheritedFromBase &&
                            SettingsValidationHelper.TryToFixId<IWizardSettings>(this.Store, this.Owner, this.WizardId, id => this.WizardId = id))
                        {
                            return;
                        }

                        context.LogError(
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Resources.Validate_WizardIsNotValid),
                            Resources.Validate_WizardIsNotValidCode, this.Extends);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Properties.Resources.ValidationMethodFailed_Error,
                    Reflector<TemplateSettings>.GetMethod(n => n.ValidateWizardIdIsValid(context)).Name);

                throw;
            }
        }
 private void ValidateSpaceInPropertyName(ValidationContext context)
 {
     if (!string.IsNullOrEmpty(Name) && Name.IndexOf(" ") > 0)
     {
         context.LogError("Property names cannot contain spaces", "AW001ValidateSpaceInPropertyNameError", this);
     }
 }
 public void Validate(ValidationContext context)
 {
     if (!IsValid)
     {
         context.Notification.RegisterMessage<ValidatedClass>(x => x.Name, ValidationKeys.REQUIRED);
     }
 }
        /// <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, ValidationContext context) {
            if (string.IsNullOrEmpty(rule.RuleSet)) return true;
            if (!string.IsNullOrEmpty(rule.RuleSet) && rulesetsToExecute.Length > 0 && rulesetsToExecute.Contains(rule.RuleSet)) return true;
            if (rulesetsToExecute.Contains("*")) return true;

            return false;
        }
        /// <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, ValidationContext context)
        {
            // By default we ignore any rules part of a RuleSet.
            if (!string.IsNullOrEmpty(rule.RuleSet)) return false;

            return true;
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var knownFragments = new Dictionary<string, FragmentDefinition>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<FragmentDefinition>(fragmentDefinition =>
            {
              var fragmentName = fragmentDefinition.Name;
              if (knownFragments.ContainsKey(fragmentName))
              {
              var error = new ValidationError(
                  context.OriginalQuery,
                  "5.4.1.1",
                  DuplicateFragmentNameMessage(fragmentName),
                  knownFragments[fragmentName],
                  fragmentDefinition);
            context.ReportError(error);
              }
              else
              {
            knownFragments[fragmentName] = fragmentDefinition;
              }
            });
              });
        }
        internal void ValidateCommandIdAndWizardIdIsNotEmpty(ValidationContext context, EventSettings settings)
        {
            Guard.NotNull(() => context, context);
            Guard.NotNull(() => settings, settings);

            try
            {
                // Ensure not empty
                if (settings.CommandId == Guid.Empty && settings.WizardId == Guid.Empty)
                {
                    context.LogError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.Validate_EventSettingsCommandIdAndWizardIdIsNotEmpty,
                            settings.Name),
                        Resources.Validate_EventSettingsCommandIdAndWizardIdIsNotEmptyCode, settings.Extends);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector<EventSettingsValidations>.GetMethod(n => n.ValidateCommandIdAndWizardIdIsNotEmpty(null, null)).Name);

                throw;
            }
        }
Beispiel #13
0
        /** Re-initializes attributes. */
        public void Reset( Schema schema, XmlElement e )
        {
            XmlAttributeCollection atts = e.Attributes;
            count = atts.Count;

            if( names.Length<count ) {
                // reallocate the buffer
                names = new int[count];
                values = new string[count];
            }

            int j=0;
            for( int i=0; i<count; i++ ) {
                XmlNode att = atts.Item(i);
                if( att.Name=="xmlns" || att.Name.StartsWith("xmlns:") )
                    continue;
                names[j] = schema.GetNameCode( att.NamespaceURI, att.LocalName );
                values[j] = att.Value;
                j++;
            }

            count = j;

            this.context = new XmlElementContext(e);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var memberNames = new[] {validationContext.MemberName};

            PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
            if (otherPropertyInfo == null)
            {
                return new ValidationResult(String.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.EqualTo_UnknownProperty, OtherProperty), memberNames);
            }

            var displayAttribute =
                otherPropertyInfo.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;

            if (displayAttribute != null && !string.IsNullOrWhiteSpace(displayAttribute.Name))
            {
                OtherPropertyDisplayName = displayAttribute.Name;
            }

            object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (!Equals(value, otherPropertyValue))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames);
            }
            return null;
        }
        internal void ValidateTypeNameNotEmpty(ValidationContext context)
        {
            try
            {
                // Ensure not empty
                if (string.IsNullOrEmpty(this.TypeName))
                {
                    context.LogError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.Validate_WizardSettingsTypeIsNotEmpty,
                            this.Name),
                        Resources.Validate_WizardSettingsTypeIsNotEmptyCode, this.Extends);
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector<WizardSettings>.GetMethod(n => n.ValidateTypeNameNotEmpty(context)).Name);

                throw;
            }
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var variableNameDefined = new Dictionary<string, bool>();

            return new EnterLeaveListener(_ =>
            {
                _.Match<VariableDefinition>(varDef => variableNameDefined[varDef.Name] = true);

                _.Match<Operation>(
                    enter: op => variableNameDefined = new Dictionary<string, bool>(),
                    leave: op =>
                    {
                        var usages = context.GetRecursiveVariables(op);
                        usages.Apply(usage =>
                        {
                            var varName = usage.Node.Name;
                            bool found;
                            if (!variableNameDefined.TryGetValue(varName, out found))
                            {
                                var error = new ValidationError(
                                    context.OriginalQuery,
                                    "5.7.4",
                                    UndefinedVarMessage(varName, op.Name),
                                    usage.Node,
                                    op);
                                context.ReportError(error);
                            }
                        });
                    });
            });
        }
		public bool Validate(object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, string keyPrefix) {
			if (type == null) {
				throw new ArgumentNullException("type");
			}

			if (metadataProvider == null) {
				throw new ArgumentNullException("metadataProvider");
			}

			if (actionContext == null) {
				throw new ArgumentNullException("actionContext");
			}

			if (model != null && MediaTypeFormatterCollection.IsTypeExcludedFromValidation(model.GetType())) {
				// no validation for some DOM like types
				return true;
			}

			ModelValidatorProvider[] validatorProviders = actionContext.GetValidatorProviders().ToArray();
			// Optimization : avoid validating the object graph if there are no validator providers
			if (validatorProviders == null || validatorProviders.Length == 0) {
				return true;
			}

			ModelMetadata metadata = metadataProvider.GetMetadataForType(() => model, type);
			ValidationContext validationContext = new ValidationContext {
				MetadataProvider = metadataProvider,
				ActionContext = actionContext,
				ModelState = actionContext.ModelState,
				Visited = new HashSet<object>(),
				KeyBuilders = new Stack<IKeyBuilder>(),
				RootPrefix = keyPrefix
			};
			return this.ValidateNodeAndChildren(metadata, validationContext, container: null);
		}
Beispiel #18
0
        private void ValidateProcessRef(ValidationContext context)
        {
            string fileName = Utilities.GetFileNameForStore(this.Store);

            if (fileName == "")
                return;

            IModelBus modelBus = this.Store.GetService(typeof(SModelBus)) as IModelBus;
            //ModelBusAdapterManager manager = modelBus.FindAdapterManagers(fileName).First();
           // ModelBusReference reference = manager.CreateReference(fileName);
            //ModelBusAdapter adapter = modelBus.CreateAdapter(this.ProcessRef);


            if (this.ProcessRef == null)
            {
                string error = string.Format(System.Globalization.CultureInfo.CurrentUICulture,
                    CustomCode.Validation.ValidationResources.EmptyNameError, "Process Reference");
                context.LogError("SubProcess: " + error, "ModelBus", this);

                return;
            }

            /*var process = adapter.ResolveElementReference(this.ProcessRef);

            if (process == null)
            {
                string error = string.Format(System.Globalization.CultureInfo.CurrentUICulture,
                    CustomCode.Validation.ValidationResources.ProcessNotExist, "Process Reference");
                context.LogError("SubProcess: " + error, "ModelBus", this);

                return;
            }*/
        }
        public static void Validate(ValidationElementState state, ValidationContext context, ModelElement currentElement)
		{
			Guard.ArgumentNotNull(context, "context");
			Guard.ArgumentNotNull(currentElement, "currentElement");

            if (ShouldAbortValidation(context))
            {
                return;
            }
            
            try
            {
                InitializeFactory(context);

                if (validatorFactory != null)
                {
                    DoValidate(currentElement, context, CommonRuleSet);
                    DoValidate(currentElement, context, context.Categories.ToString());
                    ShowStatus(currentElement);
                    return;
                }
                // trace when no config service
                context.LogWarning(Resources.NoValidationServiceAvailable, Constants.ValidationCode, currentElement);
            }
            catch (Exception ex)
            {
                context.LogFatal(LogEntry.ErrorMessageToString(ex), Constants.ValidationCode, currentElement);
                Trace.TraceError(ex.ToString());
            }
		}
        internal void ValidateArtifactReferences(ValidationContext context, IProductElement element)
        {
            if (this.UriReferenceService == null)
            {
                return;
            }

            try
            {
                var references = SolutionArtifactLinkReference.GetReferenceValues(element);

                foreach (var reference in references)
                {
                    if (this.UriReferenceService.TryResolveUri<IItemContainer>(reference) == null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.InvariantCulture,
                                Properties.Resources.Validate_ArtifactReferenceNotFound,
                                element.InstanceName, reference.ToString(), ReflectionExtensions.DisplayName(typeof(SolutionArtifactLinkReference))),
                            Properties.Resources.Validate_ArtifactReferenceNotFoundCode,
                            element as ModelElement);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Properties.Resources.ValidationMethodFailed_Error,
                    Reflector<ArtifactReferenceValidation>.GetMethod(n => n.ValidateArtifactReferences(context, element)).Name);

                throw;
            }
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var knownArgs = new Dictionary<string, Argument>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<Field>(field => knownArgs = new Dictionary<string, Argument>());
            _.Match<Directive>(field => knownArgs = new Dictionary<string, Argument>());

            _.Match<Argument>(argument =>
            {
              var argName = argument.Name;
              if (knownArgs.ContainsKey(argName))
              {
              var error = new ValidationError(context.OriginalQuery,
                  "5.3.2",
                  DuplicateArgMessage(argName),
                  knownArgs[argName],
                  argument);
            context.ReportError(error);
              }
              else
              {
            knownArgs[argName] = argument;
              }
            });
              });
        }
		public PropertyValidatorContext(ValidationContext parentContext, PropertyRule rule, string propertyName, object propertyValue)
		{
			ParentContext = parentContext;
			Rule = rule;
			PropertyName = propertyName;
			propertyValueContainer = new Lazy<object>(() => propertyValue);
		}
		public override IEnumerable<ModelValidationResult> Validate(object container) {
			if (Metadata.Model != null) {
				var selector = customizations.ToValidatorSelector();
				var interceptor = customizations.GetInterceptor() ?? (validator as IValidatorInterceptor);
				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.BeforeMvcValidation(ControllerContext, 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.AfterMvcValidation(ControllerContext, context, result) ?? result;
				}

				if (!result.IsValid) {
					return ConvertValidationResultToModelValidationResults(result);
				}
			}
			return Enumerable.Empty<ModelValidationResult>();
		}
        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            // NOTE: Container is never used here, because IValidatableObject doesn't give you
            // any way to get access to your container.

            object model = Metadata.ModelValue;
            if (model == null)
            {
                return Enumerable.Empty<ModelValidationResult>();
            }

            var validatable = model as IValidatableObject;
            if (validatable == null)
            {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        "ValidatableObjectAdapter_IncompatibleType {0} {1}",
                        typeof(IValidatableObject).FullName,
                        model.GetType().FullName
                    )
                );
            }

            var validationContext = new ValidationContext(validatable, null, null);
            return ConvertResults(validatable.Validate(validationContext));
        }
        internal void ValidateCustomizedSettingsOverriddenByCustomizableState(ValidationContext context)
        {
            try
            {
                if (this.IsCustomizationEnabled)
                {
                    if ((this.IsCustomizable == CustomizationState.False)
                        && (this.Policy.IsModified == true))
                    {
                        context.LogWarning(
                            string.Format(CultureInfo.CurrentCulture, Properties.Resources.Validate_CustomizedSettingsOverriddenByCustomizableState, this.Name),
                            Properties.Resources.Validate_CustomizedSettingsOverriddenByCustomizableStateCode, this);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector<CustomizableElementSchemaBase>.GetMethod(n => n.ValidateCustomizedSettingsOverriddenByCustomizableState(context)).Name);

                throw;
            }
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var frequency = new Dictionary<string, string>();

            return new EnterLeaveListener(_ =>
            {
                _.Match<Operation>(
                    enter: op =>
                    {
                        if (context.Document.Operations.Count < 2)
                        {
                            return;
                        }
                        if (string.IsNullOrWhiteSpace(op.Name))
                        {
                            return;
                        }

                        if (frequency.ContainsKey(op.Name))
                        {
                            var error = new ValidationError(
                                context.OriginalQuery,
                                "5.1.1.1",
                                DuplicateOperationNameMessage(op.Name),
                                op);
                            context.ReportError(error);
                        }
                        else
                        {
                            frequency[op.Name] = op.Name;
                        }
                    });
            });
        }
        internal void ValidateNameIsUnique(ValidationContext context)
        {
            try
            {
                IEnumerable<AutomationSettingsSchema> sameNamedElements = this.Owner.AutomationSettings
                    .Where(setting => setting.Name.Equals(this.Name, System.StringComparison.OrdinalIgnoreCase));

                if (sameNamedElements.Count() > 1)
                {
                    // Check if one of the properties is a system property
                    if (sameNamedElements.FirstOrDefault(property => property.IsSystem == true) != null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.CurrentCulture, Properties.Resources.Validate_AutomationSettingsNameSameAsSystem, this.Name),
                            Properties.Resources.Validate_AutomationSettingsNameSameAsSystemCode, this);
                    }
                    else
                    {
                        context.LogError(
                            string.Format(CultureInfo.CurrentCulture, Properties.Resources.Validate_AutomationSettingsNameIsNotUnique, this.Name),
                            Properties.Resources.Validate_AutomationSettingsNameIsNotUniqueCode, this);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector<AutomationSettingsSchema>.GetMethod(n => n.ValidateNameIsUnique(context)).Name);

                throw;
            }
        }
        public void ValidateClassNames(ValidationContext context, IClass cls)
        {
            // Property and Role names must be unique within a class hierarchy.

            List<string> foundNames = new List<string>();
            List<IProperty> allPropertiesInHierarchy = new List<IProperty>();
            List<IProperty> superRoles = new List<IProperty>();
            FindAllAssocsInSuperClasses(superRoles, cls.SuperClasses);

            foreach (IProperty p in cls.GetOutgoingAssociationEnds()) { superRoles.Add(p); }
            foreach (IProperty p in superRoles) { allPropertiesInHierarchy.Add(p); }
            foreach (IProperty p in cls.Members) { allPropertiesInHierarchy.Add(p); }

            foreach (IProperty attribute in allPropertiesInHierarchy)
            {
                string name = attribute.Name;
                if (!string.IsNullOrEmpty(name) && foundNames.Contains(name))
                {
                    context.LogError(
                      string.Format("Duplicate property or role name '{0}' in class '{1}'", name, cls.Name),
                      "001", cls);
                }
                foundNames.Add(name);
            }
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var variableDefs = new List<VariableDefinition>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<VariableDefinition>(def => variableDefs.Add(def));

            _.Match<Operation>(
              enter: op => variableDefs = new List<VariableDefinition>(),
              leave: op =>
              {
            var usages = context.GetRecursiveVariables(op).Select(usage => usage.Node.Name);
            variableDefs.Apply(variableDef =>
            {
              var variableName = variableDef.Name;
              if (!usages.Contains(variableName))
              {
                var error = new ValidationError(context.OriginalQuery, "5.7.5", UnusedVariableMessage(variableName, op.Name), variableDef);
                context.ReportError(error);
              }
            });
              });
              });
        }
 private void ValidateManyToManyValidity(ValidationContext context)
 {
     ReadOnlyCollection<ManyToManyRelation> manyToManySources = ManyToManyRelation.GetLinksToManyToManySources(this);
     foreach (ManyToManyRelation relationship in manyToManySources)
     {
         if (String.IsNullOrEmpty(relationship.EffectiveTable))
             context.LogError(
                 String.Format("Class {0} does not have a table name on it's many to many relation to class {1}",
                               relationship.Source.Name, relationship.Target.Name),
                 "AW001ValidateManyToManyValidity1Error", relationship);
         if (String.IsNullOrEmpty(relationship.EffectiveSourceColumn))
             context.LogError(
                 String.Format("Class {0} does not have a source column name on it's many to many relation to class {1}",
                               relationship.Source.Name, relationship.Target.Name),
                 "AW001ValidateManyToManyValidity2Error", relationship);
         if (String.IsNullOrEmpty(relationship.EffectiveTargetColumn))
             context.LogError(
                 String.Format("Class {0} does not have a target column name on it's many to many relation to class {1}",
                               relationship.Source.Name, relationship.Target.Name),
                 "AW001ValidateManyToManyValidity3Error", relationship);
         if ((relationship.EffectiveSourceRelationType == RelationType.IdBag ||
              relationship.EffectiveTargetRelationType == RelationType.IdBag) &&
             String.IsNullOrEmpty(relationship.EffectiveCollectionIDColumn))
             context.LogError(
                 String.Format("The many to many relationship between {0} and {1} must have a collection id column since it is an IdBag relationship.",
                               relationship.Source.Name, relationship.Target.Name),
                 "AW001ValidateManyToManyValidity4Error", relationship);
    }
 }
 /// <summary>
 /// To validate all properties of the instance
 /// </summary>
 /// <param name="validationContext">Validation context</param>
 /// <returns>Validation Result</returns>
 IEnumerable <ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
 {
     yield break;
 }
Beispiel #32
0
 /// <summary>
 /// To validate all properties of the instance
 /// </summary>
 /// <param name="validationContext">Validation context</param>
 /// <returns>Validation Result</returns>
 IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
 {
     yield break;
 }
Beispiel #33
0
 public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
 {
     yield break;
 }
Beispiel #34
0
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            foreach (var x in base.BaseValidate(validationContext))
            {
                yield return(x);
            }


            // Type (string) pattern
            Regex regexType = new Regex(@"^StepBooleanInput$", RegexOptions.CultureInvariant);

            if (false == regexType.Match(this.Type).Success)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" }));
            }

            yield break;
        }
 /// <summary>
 /// To validate all properties of the instance
 /// </summary>
 /// <param name="validationContext">Validation context</param>
 /// <returns>Validation Result</returns>
 IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
 {
     foreach (var x in base.BaseValidate(validationContext))
     {
         yield return(x);
     }
     yield break;
 }
Beispiel #36
0
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // DisciplineDescriptor (string) maxLength
            if (this.DisciplineDescriptor != null && this.DisciplineDescriptor.Length > 306)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DisciplineDescriptor, length must be less than 306.", new [] { "DisciplineDescriptor" }));
            }

            yield break;
        }
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // Frequency (string) pattern
            Regex regexFrequency = new Regex(@"^(EvryDay)$|^(EvryWorkgDay)$|^(IntrvlDay:((0[2-9])|([1-2][0-9])|3[0-1]))$|^(IntrvlWkDay:0[1-9]:0[1-7])$|^(WkInMnthDay:0[1-5]:0[1-7])$|^(IntrvlMnthDay:(0[1-6]|12|24):(-0[1-5]|0[1-9]|[12][0-9]|3[01]))$|^(QtrDay:(ENGLISH|SCOTTISH|RECEIVED))$", RegexOptions.CultureInvariant);

            if (false == regexFrequency.Match(this.Frequency).Success)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Frequency, must match a pattern of " + regexFrequency, new [] { "Frequency" }));
            }

            // Reference (string) maxLength
            if (this.Reference != null && this.Reference.Length > 35)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Reference, length must be less than 35.", new [] { "Reference" }));
            }

            // Reference (string) minLength
            if (this.Reference != null && this.Reference.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Reference, length must be greater than 1.", new [] { "Reference" }));
            }

            // NumberOfPayments (string) maxLength
            if (this.NumberOfPayments != null && this.NumberOfPayments.Length > 35)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for NumberOfPayments, length must be less than 35.", new [] { "NumberOfPayments" }));
            }

            // NumberOfPayments (string) minLength
            if (this.NumberOfPayments != null && this.NumberOfPayments.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for NumberOfPayments, length must be greater than 1.", new [] { "NumberOfPayments" }));
            }

            yield break;
        }
 /// <summary>
 /// To validate all properties of the instance
 /// </summary>
 /// <param name="validationContext">Validation context</param>
 /// <returns>Validation Result</returns>
 protected IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> BaseValidate(ValidationContext validationContext)
 {
     yield break;
 }
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // PaymentSolution (string) maxLength
            if (this.PaymentSolution != null && this.PaymentSolution.Length > 12)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PaymentSolution, length must be less than 12.", new [] { "PaymentSolution" }));
            }

            // CommerceIndicator (string) maxLength
            if (this.CommerceIndicator != null && this.CommerceIndicator.Length > 20)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CommerceIndicator, length must be less than 20.", new [] { "CommerceIndicator" }));
            }

            yield break;
        }
Beispiel #40
0
        private void AddBtn_Click(object sender, EventArgs e)
        {
            // information
            Student st = new Student()
            {
                Name = textBox2.Text,
                SurName = textBox1.Text,
                MiddleName = textBox3.Text,
                Specialty = textBox4.Text,
                Age = (byte)numericUpDown1.Value,
                Course = (byte)numericUpDown2.Value,
                Group = (byte)numericUpDown3.Value,
            };
            try
            {
                st.AverageScore = (float)Convert.ToDouble(textBox5.Text);
            }
            catch { }// MessageBox.Show("Неверное значение среднего балла!", "Проверьте данные!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }

            if (radioButton1.Checked)
                st.Gender = Gender.М;
            if (radioButton2.Checked)
                st.Gender = Gender.Ж;

            st.Birthday = dateTimePicker1.Value;

            Address main = new Address(textBox8.Text, textBox9.Text, textBox10.Text, textBox11.Text, (int)numericUpDown5.Value);

            string validateErrors = "";

            var results = new List<ValidationResult>();
            var context = new ValidationContext(st);
            // валидация студента и запись ошибок
            Validator.TryValidateObject(st, context, results, true);
            context = new ValidationContext(main);
            // валидация адреса и запись ошибок
            Validator.TryValidateObject(main, context, results, true);
            // переводим ошибки в норм формат
            foreach (var error in results)
            {
                validateErrors += $"{error.ErrorMessage}\n";
            }
            // пол почему-то валидатором не чекается. наверн, из-за того, что это перечисление и имеет стандартное значение
            // MessageBox.Show(st.Gender.ToString()); // выдает "М"(((
            if (!radioButton1.Checked && !radioButton2.Checked)
                validateErrors += "Не установлен пол!";
            if (validateErrors.Length != 0)
            {
                MessageBox.Show($"Обнаружены ошибки ввода:\n{validateErrors}", "Проверьте данные!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            st.MainAddress = main;
            
            // дополнительный адрес валидировать не будем
            st.SecondAddress = new Address(textBox12.Text, textBox13.Text, textBox14.Text, textBox15.Text, (int)numericUpDown6.Value);
            // work
            st.Work = new Work(textBox6.Text, textBox7.Text, (int)numericUpDown4.Value);
            Students.Add(st);
            studentCount.Text = $"Студентов: {Students.Count}.";
        }
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // NumRepeatsAllOnFailed (int?) minimum
            if (this.NumRepeatsAllOnFailed < (int?)0)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for NumRepeatsAllOnFailed, must be a value greater than or equal to 0.", new [] { "NumRepeatsAllOnFailed" }));
            }

            // RepeatsPerUserOnFailed (int?) minimum
            if (this.RepeatsPerUserOnFailed < (int?)0)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for RepeatsPerUserOnFailed, must be a value greater than or equal to 0.", new [] { "RepeatsPerUserOnFailed" }));
            }

            // UserGroupId (int?) minimum
            if (this.UserGroupId < (int?)0)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UserGroupId, must be a value greater than or equal to 0.", new [] { "UserGroupId" }));
            }

            yield break;
        }
 /// <summary>
 /// To validate all properties of the instance
 /// </summary>
 /// <param name="validationContext">Validation context</param>
 /// <returns>Validation Result</returns>
 IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
 {
     return this.BaseValidate(validationContext);
 }
Beispiel #43
0
		public ValidationResult AfterMvcValidation(HttpActionContext cc, ValidationContext context, ValidationResult result) {
			return new ValidationResult();
		}
Beispiel #44
0
        /// <summary>
        /// Saves the given post model
        /// </summary>
        /// <param name="model">The post model</param>
        public async Task SaveAsync<T>(T model) where T : PostBase
        {
            // Ensure id
            if (model.Id == Guid.Empty)
            {
                model.Id = Guid.NewGuid();
            }

            // Validate model
            var context = new ValidationContext(model);
            Validator.ValidateObject(model, context, true);

            // Ensure title since this field isn't required in
            // the Content base class
            if (string.IsNullOrWhiteSpace(model.Title))
            {
                throw new ValidationException("The Title field is required");
            }

            // Ensure type id since this field isn't required in
            // the Content base class
            if (string.IsNullOrWhiteSpace(model.TypeId))
            {
                throw new ValidationException("The TypeId field is required");
            }

            // Ensure slug
            if (string.IsNullOrWhiteSpace(model.Slug))
            {
                model.Slug = Utils.GenerateSlug(model.Title, false);
            }
            else
            {
                model.Slug = Utils.GenerateSlug(model.Slug, false);
            }

            // Call hooks & save
            App.Hooks.OnBeforeSave<PostBase>(model);
            await _repo.Save(model).ConfigureAwait(false);
            App.Hooks.OnAfterSave<PostBase>(model);

            if (_cache != null)
            {
                // Clear all categories from cache in case some
                // unused where deleted.
                var categories = await _repo.GetAllCategories(model.BlogId).ConfigureAwait(false);
                foreach (var category in categories)
                {
                    _cache.Remove(category.Id.ToString());
                    _cache.Remove($"Category_{model.BlogId}_{category.Slug}");
                }

                // Clear all tags from cache in case some
                // unused where deleted.
                var tags = await _repo.GetAllTags(model.BlogId).ConfigureAwait(false);
                foreach (var tag in tags)
                {
                    _cache.Remove(tag.Id.ToString());
                    _cache.Remove($"Tag_{model.BlogId}_{tag.Slug}");
                }
            }
        }
Beispiel #45
0
		public ValidationContext BeforeMvcValidation(HttpActionContext cc, ValidationContext context) {
			var newContext = context.Clone(selector: new FluentValidation.Internal.MemberNameValidatorSelector(properties));
			return newContext;
		}
Beispiel #46
0
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // CodeBevoegdGezag (string) minLength
            if (this.CodeBevoegdGezag != null && this.CodeBevoegdGezag.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CodeBevoegdGezag, length must be greater than 1.", new [] { "CodeBevoegdGezag" }));
            }


            // Identificatie (string) minLength
            if (this.Identificatie != null && this.Identificatie.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Identificatie, length must be greater than 1.", new [] { "Identificatie" }));
            }


            // Opschrift (string) minLength
            if (this.Opschrift != null && this.Opschrift.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Opschrift, length must be greater than 1.", new [] { "Opschrift" }));
            }

            yield break;
        }
Beispiel #47
0
		public ValidationContext BeforeMvcValidation(HttpActionContext controllerContext, ValidationContext validationContext) {
			return validationContext;
		}
Beispiel #48
0
		public ValidationContext BeforeMvcValidation(HttpActionContext cc, ValidationContext context) {
			return null;
		}
Beispiel #49
0
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // Name (string) maxLength
            if (this.Name != null && this.Name.Length > 40)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be less than 40.", new [] { "Name" }));
            }

            // Name (string) minLength
            if (this.Name != null && this.Name.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be greater than 1.", new [] { "Name" }));
            }

            yield break;
        }
Beispiel #50
0
		public ValidationResult AfterMvcValidation(HttpActionContext controllerContext, ValidationContext validationContext, ValidationResult result) {
			return new ValidationResult(); //empty errors
		}
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            foreach (var x in base.BaseValidate(validationContext))
            {
                yield return(x);
            }


            // Type (string) pattern
            Regex regexType = new Regex(@"^AirBoundaryConstructionAbridged$", RegexOptions.CultureInvariant);

            if (this.Type != null && false == regexType.Match(this.Type).Success)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" }));
            }



            // AirMixingPerArea (double) minimum
            if (this.AirMixingPerArea < (double)0)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for AirMixingPerArea, must be a value greater than or equal to 0.", new [] { "AirMixingPerArea" }));
            }

            // AirMixingSchedule (string) maxLength
            if (this.AirMixingSchedule != null && this.AirMixingSchedule.Length > 100)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for AirMixingSchedule, length must be less than 100.", new [] { "AirMixingSchedule" }));
            }

            // AirMixingSchedule (string) minLength
            if (this.AirMixingSchedule != null && this.AirMixingSchedule.Length < 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for AirMixingSchedule, length must be greater than 1.", new [] { "AirMixingSchedule" }));
            }

            yield break;
        }
Beispiel #52
0
 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     return(base.IsValid(value, validationContext));
 }
Beispiel #53
0
 IValidatableObject.Validate(ValidationContext validationContext)
 {
     yield break;
 }
Beispiel #54
0
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // SettlementMethod (string) maxLength
            if (this.SettlementMethod != null && this.SettlementMethod.Length > 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for SettlementMethod, length must be less than 1.", new [] { "SettlementMethod" }));
            }

            // FraudScreeningLevel (string) maxLength
            if (this.FraudScreeningLevel != null && this.FraudScreeningLevel.Length > 1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FraudScreeningLevel, length must be less than 1.", new [] { "FraudScreeningLevel" }));
            }

            yield break;
        }
Beispiel #55
0
 public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     // No special validations needed
     return Enumerable.Empty<ValidationResult>();
 }
Beispiel #56
0
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // Name (string) maxLength
            if (this.Name != null && this.Name.Length > 1024)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be less than 1024.", new [] { "Name" }));
            }



            // FileSize (int) maximum
            if (this.FileSize > (int)2147483647)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FileSize, must be a value less than or equal to 2147483647.", new [] { "FileSize" }));
            }

            // FileSize (int) minimum
            if (this.FileSize < (int)0)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FileSize, must be a value greater than or equal to 0.", new [] { "FileSize" }));
            }

            // Folder (string) maxLength
            if (this.Folder != null && this.Folder.Length > 1024)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Folder, length must be less than 1024.", new [] { "Folder" }));
            }


            // Title (string) maxLength
            if (this.Title != null && this.Title.Length > 1024)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Title, length must be less than 1024.", new [] { "Title" }));
            }


            yield break;
        }
Beispiel #57
0
 public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
 {
     throw new NotImplementedException();
 }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime currentDateTime;

            if (DateTime.TryParse(value.ToString(), out currentDateTime))
            {
                if (Mode == DateValidatorMode.OverOrEqualToProperty)
                {
                    DateTime refPropertyDate;
                    Object   instance = validationContext.ObjectInstance;
                    Type     type     = instance.GetType();
                    Object   data     = type.GetProperty(this.RefProperty).GetValue(instance, null);

                    if (data != null && data is DateTime)
                    {
                        refPropertyDate = (DateTime)data;
                    }
                    else
                    {
                        return(new ValidationResult("Property reference date is null or not DateTime value"));
                    }

                    if (DateTime.Compare(currentDateTime, refPropertyDate) >= 0)
                    {
                        return(ValidationResult.Success);
                    }
                    else
                    {
                        return(new ValidationResult("Current DateTime is lower than min property"));
                    }
                }
                else if (Mode == DateValidatorMode.OverNow)
                {
                    DateTime minDateTime;
                    if (MinDate.Equals("Now"))
                    {
                        minDateTime = DateTime.Now;
                    }
                    else
                    {
                        DateTime dt;
                        if (!DateTime.TryParse(MinDate, out dt))
                        {
                            return(new ValidationResult("Cannot parse reference min date to date"));
                        }
                        else
                        {
                            minDateTime = dt;
                        }
                    }

                    if (DateTime.Compare(currentDateTime, minDateTime.Date) >= 0)
                    {
                        return(ValidationResult.Success);
                    }
                    else
                    {
                        return(new ValidationResult("Current DateTime is lower than Now or min DateTime"));
                    }
                }
            }
            else
            {
                return(new ValidationResult("Cannot parse to date"));
            }

            return(new ValidationResult("Error"));
        }
Beispiel #59
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var errors = new List <ValidationResult>();

            return(errors);
        }
        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // WalletDivision (int?) maximum
            if (this.WalletDivision > (int?)7)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for WalletDivision, must be a value less than or equal to 7.", new [] { "WalletDivision" }));
            }

            // WalletDivision (int?) minimum
            if (this.WalletDivision < (int?)1)
            {
                yield return(new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for WalletDivision, must be a value greater than or equal to 1.", new [] { "WalletDivision" }));
            }

            yield break;
        }