• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ValidationContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ValidationContext的典型用法代码示例。如果您正苦于以下问题:C# ValidationContext类的具体用法?C# ValidationContext怎么用?C# ValidationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ValidationContext类属于命名空间,在下文中一共展示了ValidationContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Validate

        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));
                    }
                });
            });
        }
开发者ID:graphql-dotnet,项目名称:graphql-dotnet,代码行数:31,代码来源:FragmentsOnCompositeTypes.cs


示例2: ValidateSpaceInPropertyName

 private void ValidateSpaceInPropertyName(ValidationContext context)
 {
     if (!string.IsNullOrEmpty(Name) && Name.IndexOf(" ") > 0)
     {
         context.LogError("Property names cannot contain spaces", "AW001ValidateSpaceInPropertyNameError", this);
     }
 }
开发者ID:mgagne-atman,项目名称:Projects,代码行数:7,代码来源:ModelClassPropertyValidation.cs


示例3: Validate

 public INodeVisitor Validate(ValidationContext context)
 {
     return new EnterLeaveListener(_ =>
     {
         _.Match<Field>(f => Field(context.TypeInfo.GetLastType(), f, context));
     });
 }
开发者ID:mwatts,项目名称:graphql-dotnet,代码行数:7,代码来源:ScalarLeafs.cs


示例4: Validate

        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;
              }
            });
              });
        }
开发者ID:graphql-dotnet,项目名称:graphql-dotnet,代码行数:26,代码来源:UniqueFragmentNames.cs


示例5: CanExecute

        /// <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;
        }
开发者ID:grammarware,项目名称:fodder,代码行数:14,代码来源:src_ServiceStack_ServiceInterface_Validation_MultiRuleSetValidatorSelector.cs


示例6: ValidateTypeNameNotEmpty

        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;
            }
        }
开发者ID:NuPattern,项目名称:NuPattern,代码行数:25,代码来源:WizardSettings.Validation.cs


示例7: Validate

		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>();
		}
开发者ID:AVee,项目名称:ServiceStack,代码行数:26,代码来源:FluentValidationModelValidator.cs


示例8: ValidateClassNames

        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);
            }
        }
开发者ID:keithshort1,项目名称:MyLoProto,代码行数:25,代码来源:PLDBValidationConstraints.cs


示例9: Validate

        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));
        }
开发者ID:Chunhui-Liu,项目名称:Blog,代码行数:27,代码来源:ValidatableObjectAdapter.cs


示例10: ValidateCustomizedSettingsOverriddenByCustomizableState

        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;
            }
        }
开发者ID:StevenVanDijk,项目名称:NuPattern,代码行数:25,代码来源:CustomizableElementSchema.Validation.cs


示例11: ValidateNameIsUnique

        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;
            }
        }
开发者ID:StevenVanDijk,项目名称:NuPattern,代码行数:34,代码来源:AutomationSettingsSchema.Validation.cs


示例12: Validate

        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;
                        }
                    });
            });
        }
开发者ID:graphql-dotnet,项目名称:graphql-dotnet,代码行数:34,代码来源:UniqueOperationNames.cs


示例13: Validate

        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);
              }
            });
              });
              });
        }
开发者ID:graphql-dotnet,项目名称:graphql-dotnet,代码行数:25,代码来源:NoUnusedVariables.cs


示例14: Validate

		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);
		}
开发者ID:jango2015,项目名称:FluentValidation,代码行数:35,代码来源:FluentValidationBodyModelValidator.cs


示例15: PropertyValidatorContext

		public PropertyValidatorContext(ValidationContext parentContext, PropertyRule rule, string propertyName, object propertyValue)
		{
			ParentContext = parentContext;
			Rule = rule;
			PropertyName = propertyName;
			propertyValueContainer = new Lazy<object>(() => propertyValue);
		}
开发者ID:JeremySkinner,项目名称:FluentValidation,代码行数:7,代码来源:PropertyValidatorContext.cs


示例16: IsValid

        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;
        }
开发者ID:jordivila,项目名称:Net_MVC_NLayer_Generator,代码行数:25,代码来源:EqualToAttribute.cs


示例17: ValidateManyToManyValidity

 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);
    }
 }
开发者ID:mgagne-atman,项目名称:Projects,代码行数:29,代码来源:ModelClassValidation.cs


示例18: ValidateCommandIdAndWizardIdIsNotEmpty

        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;
            }
        }
开发者ID:NuPattern,项目名称:NuPattern,代码行数:28,代码来源:EventSettings.Validation.cs


示例19: ValidateArtifactReferences

        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;
            }
        }
开发者ID:NuPattern,项目名称:NuPattern,代码行数:34,代码来源:ArtifactReferencesValidation.cs


示例20: CanExecute

        /// <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;
        }
开发者ID:austinvernsonger,项目名称:ServiceStack,代码行数:14,代码来源:DefaultValidatorSelector.cs



注:本文中的ValidationContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ValidationErrorCollection类代码示例发布时间:2022-05-24
下一篇:
C# Validation类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap