/// <summary>
        /// Creates the <see cref="PropertyComparisonValidator"/> described by the configuration object.
        /// </summary>
        /// <param name="targetType">The type of object that will be validated by the validator.</param>
        /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
        /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
        /// require access to properties.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <returns>The created <see cref="PropertyComparisonValidator"/>.</returns>	
        protected override Validator DoCreateValidator(
            Type targetType,
            Type ownerType,
            MemberValueAccessBuilder memberValueAccessBuilder,
            ValidatorFactory validatorFactory)
        {
            if (string.IsNullOrEmpty(this.PropertyToCompare))
            {
                throw new ConfigurationErrorsException(Resources.ExceptionPropertyToCompareNull);
            }
            PropertyInfo propertyInfo = ValidationReflectionHelper.GetProperty(ownerType, this.PropertyToCompare, false);
            if (propertyInfo == null)
            {
                throw new ConfigurationErrorsException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ExceptionPropertyToCompareNotFound,
                        this.PropertyToCompare,
                        ownerType.FullName));
            }

            return new PropertyComparisonValidator(memberValueAccessBuilder.GetPropertyValueAccess(propertyInfo),
                this.ComparisonOperator,
                this.Negated);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="memberAccessValidatorFactory"></param>
 /// <param name="validatorFactory"></param>
 public ValidatorBuilderBase(
     MemberAccessValidatorBuilderFactory memberAccessValidatorFactory,
     ValidatorFactory validatorFactory)
 {
     this.memberAccessValidatorFactory = memberAccessValidatorFactory;
     this.validatorFactory = validatorFactory;
 }
        /// <summary>
        /// Creates the validator for the specified target and ruleset.
        /// </summary>
        /// <param name="targetType">The <see cref="Type"/>to validate.</param>
        /// <param name="ruleset">The ruleset to use when validating</param>
        /// <param name="mainValidatorFactory">Factory to use when building nested validators.</param>
        /// <returns>A <see cref="Validator"/></returns>
        protected internal override Validator InnerCreateValidator(Type targetType, string ruleset, ValidatorFactory mainValidatorFactory)
        {
            Validator validator =
                GetValidator(validatorFactories.Select(f => f.InnerCreateValidator(targetType, ruleset, mainValidatorFactory)));

            return validator;
        }
 public void Init()
 {
     IConfigurationSource config = ConfigurationSourceFactory.Create();
     this.valFactory = ValidationFactory.DefaultCompositeValidatorFactory;
     this.valFactoryFromConfig = ConfigurationValidatorFactory.FromConfigurationSource(config);
     this.container = new UnityContainer();
     ContainerBootstrapper.Configure(this.container);
 }
 Validator IValidatorDescriptor.CreateValidator(
     Type targetType,
     Type ownerType,
     MemberValueAccessBuilder memberValueAccessBuilder,
     ValidatorFactory validatorFactory)
 {
     return CreateValidator(targetType, ownerType, memberValueAccessBuilder, validatorFactory);
 }
 ///<summary>
 ///</summary>
 ///<param name="validationSettings"></param>
 ///<param name="memberAccessValidatorFactory"></param>
 ///<param name="validatorFactory"></param>
 public ConfigurationValidatorBuilder(
     ValidationSettings validationSettings,
     MemberAccessValidatorBuilderFactory memberAccessValidatorFactory,
     ValidatorFactory validatorFactory)
     : base(memberAccessValidatorFactory, validatorFactory)
 {
     this.validationSettings = validationSettings;
 }
        /// <summary>
        /// Creates the validator for the specified target and ruleset.
        /// </summary>
        /// <param name="targetType">The <see cref="Type"/>to validate.</param>
        /// <param name="ruleset">The ruleset to use when validating</param>
        /// <param name="mainValidatorFactory">Factory to use when building nested validators.</param>
        /// <returns>A <see cref="Validator"/></returns>
        protected internal override Validator InnerCreateValidator(Type targetType, string ruleset, ValidatorFactory mainValidatorFactory)
        {
            ConfigurationValidatorBuilder builder =
                new ConfigurationValidatorBuilder(
                    ValidationSettings.TryGet(ConfigurationSource),
                    MemberAccessValidatorBuilderFactory.Default,
                    mainValidatorFactory);

            return builder.CreateValidator(targetType, ruleset);
        }
 ///<summary>
 ///</summary>
 ///<param name="validationSettings"></param>
 ///<param name="instrumentationProvider"></param>
 ///<param name="memberAccessValidatorFactory"></param>
 ///<param name="validatorFactory"></param>
 public ConfigurationValidatorBuilder(
     ValidationSettings validationSettings,
     IValidationInstrumentationProvider instrumentationProvider,
     MemberAccessValidatorBuilderFactory memberAccessValidatorFactory,
     ValidatorFactory validatorFactory)
     : base(memberAccessValidatorFactory, validatorFactory)
 {
     this.validationSettings = validationSettings;
     this.instrumentationProvider = instrumentationProvider;
 }
        /// <summary>
        /// Creates the validator for the specified target and ruleset.
        /// </summary>
        /// <param name="targetType">The <see cref="Type"/>to validate.</param>
        /// <param name="ruleset">The ruleset to use when validating</param>
        /// <param name="mainValidatorFactory">Factory to use when building nested validators.</param>
        /// <returns>A <see cref="Validator"/></returns>
        protected internal override Validator InnerCreateValidator(
            Type targetType, 
            string ruleset, 
            ValidatorFactory mainValidatorFactory)
        {
            MetadataValidatorBuilder builder =
                new MetadataValidatorBuilder(MemberAccessValidatorBuilderFactory.Default, mainValidatorFactory);

            return builder.CreateValidator(targetType, ruleset);
        }
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            var isPropertyValidation = metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName);

            if (isPropertyValidation) yield break;

            var validatorFactory = new ValidatorFactory();
            var validator = validatorFactory.GetValidator(metadata.ModelType, metadata.Model);

            if (validator != null)
                yield return new FluentModelValidator(metadata, context, validator);
        }
        /// <summary>
        /// Creates the <see cref="Validator"/> described by the configuration object.
        /// </summary>
        /// <param name="targetType">The type of object that will be validated by the validator.</param>
        /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
        /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
        /// require access to properties.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <returns>The created <see cref="Validator"/>.</returns>
        /// <remarks>
        /// Sets the tag and message template to the created validator.
        /// </remarks>
        protected Validator CreateValidator(
            Type targetType,
            Type ownerType,
            MemberValueAccessBuilder memberValueAccessBuilder,
            ValidatorFactory validatorFactory)
        {
            Validator validator = DoCreateValidator(targetType, ownerType, memberValueAccessBuilder, validatorFactory);
            validator.Tag = this.Tag;
            validator.MessageTemplate = this.GetMessageTemplate();

            return validator;
        }
        ///<summary>
        ///</summary>
        ///<param name="configurationSource"></param>
        ///<param name="memberAccessValidatorBuilderFactory"></param>
        ///<param name="validatorFactory"></param>
        ///<returns></returns>
        public static ConfigurationValidatorBuilder FromConfiguration(
            IConfigurationSource configurationSource,
            MemberAccessValidatorBuilderFactory memberAccessValidatorBuilderFactory,
            ValidatorFactory validatorFactory)
        {
            var settings = ValidationSettings.TryGet(configurationSource);

            return
                new ConfigurationValidatorBuilder(
                    settings,
                    memberAccessValidatorBuilderFactory,
                    validatorFactory);
        }
        /// <summary>
        /// Creates the validator for the specified target and ruleset.
        /// </summary>
        /// <param name="targetType">The <see cref="Type"/>to validate.</param>
        /// <param name="ruleset">The ruleset to use when validating.</param>
        /// <param name="mainValidatorFactory">Factory to use when building nested validators.</param>
        /// <returns>A <see cref="Validator"/>.</returns>
        protected internal override Validator InnerCreateValidator(Type targetType, string ruleset, ValidatorFactory mainValidatorFactory)
        {
            if (string.IsNullOrEmpty(ruleset))
            {
                ValidationAttributeValidatorBuilder builder =
                    new ValidationAttributeValidatorBuilder(MemberAccessValidatorBuilderFactory.Default, mainValidatorFactory);

                return builder.CreateValidator(targetType);
            }
            else
            {
                return EmptyValidator;
            }
        }
        /// <summary>
        /// Creates the <see cref="OrCompositeValidator"/> described by the configuration object.
        /// </summary>
        /// <param name="targetType">The type of object that will be validated by the validator.</param>
        /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
        /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
        /// require access to properties.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <returns>The created <see cref="OrCompositeValidator"/>.</returns>
        protected override Validator DoCreateValidator(
            Type targetType,
            Type ownerType,
            MemberValueAccessBuilder memberValueAccessBuilder,
            ValidatorFactory validatorFactory)
        {
            List<Validator> childValidators = new List<Validator>(this.Validators.Count);
            foreach (IValidatorDescriptor validatorData in this.Validators)
            {
                childValidators.Add(validatorData.CreateValidator(targetType, ownerType, memberValueAccessBuilder, validatorFactory));
            }

            return new OrCompositeValidator(childValidators.ToArray());
        }
        ///<summary>
        ///</summary>
        ///<param name="configurationSource"></param>
        ///<param name="memberAccessValidatorBuilderFactory"></param>
        ///<param name="validatorFactory"></param>
        ///<returns></returns>
        public static ConfigurationValidatorBuilder FromConfiguration(
            IConfigurationSource configurationSource,
            MemberAccessValidatorBuilderFactory memberAccessValidatorBuilderFactory,
            ValidatorFactory validatorFactory)
        {
            var instrumentationProvider = ValidationInstrumentationProvider.FromConfigurationSource(configurationSource);
            var settings = ValidationSettings.TryGet(configurationSource, instrumentationProvider);

            return
                new ConfigurationValidatorBuilder(
                    settings,
                    instrumentationProvider,
                    memberAccessValidatorBuilderFactory,
                    validatorFactory);
        }
예제 #16
0
 /// <summary>
 /// Creates the <see cref="ObjectValidator"/> described by the configuration object.
 /// </summary>
 /// <param name="targetType">The type of object that will be validated by the validator.</param>
 /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
 /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
 /// require access to properties.</param>
 /// <param name="validatorFactory">Factory to use when building nested validators.</param>
 /// <returns>The created <see cref="Validator"/>.</returns>
 protected override Validator DoCreateValidator(
     Type targetType,
     Type ownerType,
     MemberValueAccessBuilder memberValueAccessBuilder,
     ValidatorFactory validatorFactory)
 {
     if (this.ValidateActualType)
     {
         return new ObjectValidator(validatorFactory, targetRuleset);
     }
     else
     {
         return new ObjectValidator(targetType, validatorFactory, targetRuleset);
     }
 }
        /// <summary>
        /// Creates the <see cref="ObjectCollectionValidator"/> described by the configuration object.
        /// </summary>
        /// <param name="targetType">The type of object that will be validated by the validator.</param>
        /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
        /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
        /// require access to properties.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <returns>The created <see cref="ObjectCollectionValidator"/>.</returns>
        /// <seealso cref="ObjectCollectionValidator"/>
        protected override Validator DoCreateValidator(
            Type targetType,
            Type ownerType,
            MemberValueAccessBuilder memberValueAccessBuilder,
            ValidatorFactory validatorFactory)
        {
            Type configuredTargetType = this.TargetType;

            if (configuredTargetType != null)
            {
                return new ObjectCollectionValidator(configuredTargetType, validatorFactory, this.TargetRuleset);
            }
            else
            {
                return new ObjectCollectionValidator(validatorFactory, this.TargetRuleset);
            }
        }
예제 #18
0
        /// <summary>
        /// <para>Initializes a new instance of the <see cref="ObjectCollectionValidator"/> 
        /// using the supplied ruleset.</para>
        /// </summary>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <param name="targetRuleset">The ruleset to use.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="targetRuleset"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">when <paramref name="validatorFactory"/> is <see langword="null"/>.</exception>
        public ObjectCollectionValidator(ValidatorFactory validatorFactory, string targetRuleset)
            : base(null, null)
        {
            if (validatorFactory == null)
            {
                throw new ArgumentNullException("validatorFactory");
            }
            if (targetRuleset == null)
            {
                throw new ArgumentNullException("targetRuleset");
            }

            this.targetType = null;
            this.targetTypeValidator = null;
            this.targetRuleset = targetRuleset;
            this.validatorFactory = validatorFactory;
        }
        //Validate TaskbarMenuColor
        protected virtual ValidationResult ValidateTaskbarMenuColor(string taskbarMenuColor)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateTheme'.
                //The validator factory will create the validator object based on its key.
                IThemeValidator validator = (IThemeValidator)ValidatorFactory.Create(Keywords.DeleteTheme);

                //Execute validation process
                validationResult = validator.ValidateTaskbarMenuColor(taskbarMenuColor);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
        //Validate GenderIcon
        protected virtual ValidationResult ValidateGenderIcon(Int16 idGender, string genderIcon)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateGender'.
                //The validator factory will create the validator object based on its key.
                IGenderValidator validator = (IGenderValidator)ValidatorFactory.Create(Keywords.UpdateGender);

                //Execute validation process
                validationResult = validator.ValidateGenderIcon(idGender, genderIcon);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
예제 #21
0
        //Validate
        protected virtual ValidationResult ValidateCityId(Int16 cityId)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateUserInfo'.
                //The validator factory will create the validator object based on its key.
                IUserInfoValidator validator = (IUserInfoValidator)ValidatorFactory.Create(Keywords.DeleteUserInfo);

                //Execute validation process
                validationResult = validator.ValidateCityId(cityId);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
        //Validate CityLocationLat
        protected virtual ValidationResult ValidateCityLocationLat(Int64 idCity, float cityLocationLat)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateCity'.
                //The validator factory will create the validator object based on its key.
                ICityValidator validator = (ICityValidator)ValidatorFactory.Create(Keywords.UpdateCity);

                //Execute validation process
                validationResult = validator.ValidateCityLocationLat(idCity, cityLocationLat);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
        //Validate ExpiredDate
        protected virtual ValidationResult ValidateExpiredDate(Int64 idAccessToken, DateTime expiredDate)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateAccessToken'.
                //The validator factory will create the validator object based on its key.
                IAccessTokenValidator validator = (IAccessTokenValidator)ValidatorFactory.Create(Keywords.UpdateAccessToken);

                //Execute validation process
                validationResult = validator.ValidateExpiredDate(idAccessToken, expiredDate);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
        //Validate LanguageID
        protected virtual ValidationResult ValidateLanguageID(string languageID)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateLanguageKeyword'.
                //The validator factory will create the validator object based on its key.
                ILanguageKeywordValidator validator = (ILanguageKeywordValidator)ValidatorFactory.Create(Keywords.DeleteLanguageKeyword);

                //Execute validation process
                validationResult = validator.ValidateLanguageID(languageID);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Use the validation factory to get the validator associated
        //with the validator type
        ValidatorFactory validatorFactory = new ValidatorFactory();
        var Validator = validatorFactory.GetValidator(ValidationType);
        //Execute the validator
        bool isValid = Validator.Validate(value);

        //Validation is successful, return ValidationResult.Succes
        if (isValid)
        {
            return(ValidationResult.Success);
        }
        else     //Return validation error
        {
            return(new ValidationResult(Validator.ErrorMessage));
        }
    }
        public async Task Valid_ResourceOwner_Request()
        {
            var client = await _settings.FindClientByIdAsync("roclient");

            var validator = ValidatorFactory.CreateTokenValidator(_settings, _logger,
                                                                  userService: _users,
                                                                  customRequestValidator: _customRequestValidator);

            var parameters = new NameValueCollection();

            parameters.Add(Constants.TokenRequest.GrantType, Constants.GrantTypes.Password);
            parameters.Add(Constants.TokenRequest.UserName, "bob");
            parameters.Add(Constants.TokenRequest.Password, "bob");
            parameters.Add(Constants.TokenRequest.Scope, "resource");

            var result = await validator.ValidateRequestAsync(parameters, client);

            Assert.IsFalse(result.IsError);
        }
예제 #27
0
        public async System.Threading.Tasks.Task <string> PostAsync()
        {
            string type = Request.Headers.FirstOrDefault(x => x.Key == "Content-Type").Value;
            string data = "";

            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                data = await reader.ReadToEndAsync();
            }
            try
            {
                IValidator validator = ValidatorFactory.createValidator(type);
                return(validator.Validate(data));
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        //Validate ApplicationGroupName
        protected virtual ValidationResult ValidateApplicationGroupName(Int16 idApplicationGroup, string applicationGroupName)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateApplicationGroup'.
                //The validator factory will create the validator object based on its key.
                IApplicationGroupValidator validator = (IApplicationGroupValidator)ValidatorFactory.Create(Keywords.UpdateApplicationGroup);

                //Execute validation process
                validationResult = validator.ValidateApplicationGroupName(idApplicationGroup, applicationGroupName);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
        //Validate LoadingAnimationAudio
        protected virtual ValidationResult ValidateLoadingAnimationAudio(Int16 idTheme, string loadingAnimationAudio)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateTheme'.
                //The validator factory will create the validator object based on its key.
                IThemeValidator validator = (IThemeValidator)ValidatorFactory.Create(Keywords.UpdateTheme);

                //Execute validation process
                validationResult = validator.ValidateLoadingAnimationAudio(idTheme, loadingAnimationAudio);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
예제 #30
0
        public void CheckProviderValidation(DbPlatform platformUnderExecution, DbAltererOptions options, int expectedTotalNumberOfSupportedProviders, int expectedValidationRuns)
        {
            // arrange
            var       providerLocator = new ProviderLocator(new ProviderRegistry());
            int       totalNumberOfSupportedProviders = options.SupportedPlatforms.Sum(n => providerLocator.GetAllForMinimumRequirement(n).Count());
            var       validatorFactory = new ValidatorFactory(providerLocator.GetExactly(platformUnderExecution), options, providerLocator);
            Validator validator        = validatorFactory.Create();

            var    reporter = A.Fake <IMigrationReporter>();
            string errors;
            string warnings;

            // act
            validator.Validate(new[] { reporter }, out errors, out warnings);

            // assert
            Assert.AreEqual(expectedTotalNumberOfSupportedProviders, totalNumberOfSupportedProviders, "Wrong total number of providers.");
            A.CallTo(() => reporter.Report(A <IMigrationContext> ._)).MustHaveHappened(Repeated.Exactly.Times(expectedValidationRuns));
        }
예제 #31
0
        public async Task Valid_Mixed_IdTokenToken_Request_Multiple_Scopes()
        {
            var parameters = new NameValueCollection();

            parameters.Add(Constants.AuthorizeRequest.ClientId, "implicitclient");
            parameters.Add(Constants.AuthorizeRequest.Scope, "openid profile resource");
            parameters.Add(Constants.AuthorizeRequest.RedirectUri, "oob://implicit/cb");
            parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.IdTokenToken);
            parameters.Add(Constants.AuthorizeRequest.Nonce, "abc");

            var validator      = ValidatorFactory.CreateAuthorizeValidator();
            var protocolResult = validator.ValidateProtocol(parameters);

            Assert.IsFalse(protocolResult.IsError);

            var clientResult = await validator.ValidateClientAsync();

            Assert.IsFalse(clientResult.IsError);
        }
예제 #32
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ValidatorFactory.CreateRequiredValidator(rfvCameraNo, txtCameraNo, "请输入摄像头编号");
            ValidatorFactory.CreateRequiredValidator(rfvCustomerAddress, txtCustomerAddress, "请输入用户地址");
            ValidatorFactory.CreateRequiredValidator(rfvCustomerName, txtCustomerName, "请输入用户名称");
            ValidatorFactory.CreateDoubleRangeValidator(RangeValidator1, txtLongitude, 180, -180);
            ValidatorFactory.CreateDoubleRangeValidator(RangeValidator2, txtLatitude, 90, -90);
            //字典
            DataGlobal.LoadDictType(ddlBaudrate, DicType.BaudRate);
            DataGlobal.LoadDictType(ddlCameraKind, DicType.CaremaKind);
            DataGlobal.LoadDictType(ddlCameraType, DicType.CaremaType);
            DataGlobal.LoadDictType(ddlCodeAddr, DicType.CodeAddr);
            DataGlobal.LoadDictType(ddlCodeStream, DicType.CodeStream);
            DataGlobal.LoadDictType(ddlControlProtocol, DicType.ControlProtocol);
            DataGlobal.LoadDictType(ddlCustomerType, DicType.CustomerType);
            DataGlobal.LoadDeviceLevel(ddlDeviceLevel);
            DataGlobal.LoadDictType(ddlDeviceManu, DicType.DeviceManu);
            DataGlobal.LoadDictType(ddlDevicePropertyRight, DicType.DevicePropertyRight);
            DataGlobal.LoadDictType(ddlDeviceState, DicType.DeviceState);
            DataGlobal.LoadDictType(ddlInstallMode, DicType.InstallMode);
            DataGlobal.LoadDictType(ddlPaymentType, DicType.PaymentType);
            DataGlobal.LoadDictType(ddlPowerType, DicType.PowerType);
            DataGlobal.LoadDictType(ddlPowerVoltage, DicType.PowerVoltage);
            DataGlobal.LoadDictType(ddlStorageType, DicType.StorageType);
            DataGlobal.LoadDictType(ddlSwitchinMode, DicType.SWITCHINMODE);
            DataGlobal.LoadDictType(ddlSwitchinPlace, DicType.SWITCHINPLACE);

            hdfCameraID.Value = "0";
            btnModify.Enabled = false;
            if (Request["id"] != null && Request["id"] != "")
            {
                LoadCameraInfo(Request["id"].ToString());
                btnModify.Text = "确定修改";
            }
            else if (Request["dvsid"] != null && Request["dvsid"] != "")
            {
                LoadDvsInfo(Request["dvsid"].ToString(), "0");
                btnModify.Text = "确定新增";
            }
        }
    }
        //Validate AuthenticationCode
        protected virtual ValidationResult ValidateAuthenticationCode(string authenticationCode)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateRefreshToken'.
                //The validator factory will create the validator object based on its key.
                IRefreshTokenValidator validator = (IRefreshTokenValidator)ValidatorFactory.Create(Keywords.DeleteRefreshToken);

                //Execute validation process
                validationResult = validator.ValidateAuthenticationCode(authenticationCode);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
        public async Task Unknown_Scope_Multiple()
        {
            var client = await _settings.FindClientByIdAsync("roclient");

            var validator = ValidatorFactory.CreateTokenValidator(_settings, _logger,
                                                                  userService: _users);

            var parameters = new NameValueCollection();

            parameters.Add(Constants.TokenRequest.GrantType, Constants.GrantTypes.Password);
            parameters.Add(Constants.TokenRequest.Scope, "resource unknown");
            parameters.Add(Constants.TokenRequest.UserName, "bob");
            parameters.Add(Constants.TokenRequest.Password, "bob");

            var result = await validator.ValidateRequestAsync(parameters, client);

            Assert.IsTrue(result.IsError);
            Assert.AreEqual(Constants.TokenErrors.InvalidScope, result.Error);
        }
        //Validate Username
        protected virtual ValidationResult ValidateUsername(Int64 idUser, string username)
        {
            ValidationResult validationResult = new ValidationResult(true);

            try
            {
                //Create Validator based on its Key name : 'Keywords.UpdateUserLogin'.
                //The validator factory will create the validator object based on its key.
                IUserLoginValidator validator = (IUserLoginValidator)ValidatorFactory.Create(Keywords.UpdateUserLogin);

                //Execute validation process
                validationResult = validator.ValidateUsername(idUser, username);
            }
            catch
            {
                //The program will throw error if the validation object doesn't exist. And the default of validation result is true.
            }
            return(validationResult);
        }
예제 #36
0
        public async Task Mixed_Token_Request_Without_OpenId_Scope()
        {
            var parameters = new NameValueCollection();

            parameters.Add(Constants.AuthorizeRequest.ClientId, "implicitclient");
            parameters.Add(Constants.AuthorizeRequest.Scope, "resource profile");
            parameters.Add(Constants.AuthorizeRequest.RedirectUri, "oob://implicit/cb");
            parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.Token);

            var validator      = ValidatorFactory.CreateAuthorizeValidator();
            var protocolResult = validator.ValidateProtocol(parameters);

            Assert.AreEqual(false, protocolResult.IsError);

            var clientResult = await validator.ValidateClientAsync();

            Assert.IsTrue(clientResult.IsError);
            Assert.AreEqual(ErrorTypes.Client, clientResult.ErrorType);
            Assert.AreEqual(Constants.AuthorizeErrors.InvalidScope, clientResult.Error);
        }
        private async Task <CommandResult <TEntity> > SaveOrUpdate(TEntity entity, Func <TEntity, Task <CommandResult <TEntity> > > action)
        {
            var entityValidator = ValidatorFactory?.GetValidator <TEntity>();

            if (entityValidator != null)
            {
                var validationResult = entityValidator.Validate(entity);

                if (!validationResult.IsValid)
                {
                    string validationErrorMessage = String.Join(",", validationResult.Errors.Select(x => x.ErrorMessage).ToArray());
                    return(new CommandResult <TEntity>()
                    {
                        Entity = entity, Result = CommandState.Error, Message = $"Validation has failed :  {validationErrorMessage}"
                    });
                }
            }

            return(await action(entity));
        }
예제 #38
0
        public async Task OpenId_Code_Request_Invalid_RedirectUri()
        {
            var parameters = new NameValueCollection();

            parameters.Add(Constants.AuthorizeRequest.ClientId, "codeclient");
            parameters.Add(Constants.AuthorizeRequest.Scope, "openid");
            parameters.Add(Constants.AuthorizeRequest.RedirectUri, "https://invalid");
            parameters.Add(Constants.AuthorizeRequest.ResponseType, Constants.ResponseTypes.Code);

            var validator      = ValidatorFactory.CreateAuthorizeValidator();
            var protocolResult = validator.ValidateProtocol(parameters);

            Assert.IsFalse(protocolResult.IsError);

            var clientResult = await validator.ValidateClientAsync();

            Assert.IsTrue(clientResult.IsError);
            Assert.AreEqual(ErrorTypes.User, clientResult.ErrorType);
            Assert.AreEqual(Constants.AuthorizeErrors.UnauthorizedClient, clientResult.Error);
        }
        /// <summary>
        /// Gets a list of validators.
        /// </summary>
        /// <returns>
        /// A list of validators.
        /// </returns>
        /// <param name="metadata">The metadata.</param><param name="context">The context.</param>
        public override IEnumerable <ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            bool isModelProperty = ModelMetadataHelper.IsModelProperty(metadata);

            Type modelType = isModelProperty ? metadata.ContainerType : metadata.ModelType;
            IValidationTransformer validationTransformer = GetValidationTransformer(modelType);
            IEntityValidator       validator             = ValidatorFactory.GetValidatorForOptional(validationTransformer == null ? modelType : validationTransformer.ValidationModelType);

            if (isModelProperty)
            {
                return(GetValidatorsForProperty(metadata, context, validator, validationTransformer));
            }

            return(GetValidatorsForModel(metadata, context, validator, validationTransformer));
        }
        public List <ValidationResultMessage> Validate(Package package)
        {
            var messages = new List <ValidationResultMessage>();

            messages.AddRange(ValidatorFactory.GetValidator(ValidationMode, package, AuxiliaryValues).Validate(this));

            if (messages.All(m => m.Status == StatusWords.OK) & ValidationMode != CheckMode.Existing)
            {
                foreach (var attribute in Attributes)
                {
                    messages.AddRange(ValidatorFactory.GetValidator(attribute.ValidationMode, package, attribute.AuxiliaryValues).Validate(attribute));
                }

                foreach (var nestedParameter in NestedParameters)
                {
                    messages.AddRange(ValidatorFactory.GetValidator(nestedParameter.ValidationMode, package, nestedParameter.AuxiliaryValues).Validate(nestedParameter));
                }
            }

            return(messages);
        }
예제 #41
0
        public async Task UseCase_WhenUpdateThumbnail_ReturnRemoteUrl()
        {
            var repo       = new Mock <INewsRepository>();
            var imgService = new Mock <IImageStorageService>();
            var validator  = ValidatorFactory.GetValidValidator <ThumbnailRequest>();
            var logger     = new Mock <ILogger <CreateOrUpdateThumbnailUseCase> >().Object;

            repo.Setup(r => r.GetById(_request.NewsId))
            .ReturnsAsync(new NewsBuilder(_request.NewsId).WithThumbnailURL("http://s3.com/bucketName/ab123cdf3243.jpg").Build());
            imgService.Setup(s => s.Update(It.IsAny <string>(), _request.FileLocalPath))
            .ReturnsAsync((string keyName, string path) => $"http://s3.com/bucketName/{keyName}");

            var useCase  = new CreateOrUpdateThumbnailUseCase(repo.Object, imgService.Object, logger, validator);
            var response = await useCase.Execute(_request);

            response.Status.Should().Be(UseCaseResponseStatus.Success);
            response.Result
            .Should()
            .NotBeNullOrEmpty()
            .And.Contain("http");
        }
        public void ShouldNeverAllowNullResultToBeValid()
        {
            var val = ValidatorFactory.GetValidator <Testable>();
            var t1  = new Testable {
                Id = Guid.NewGuid(), Name = DateTime.Now.Ticks.ToString()
            };

            var exec = val.Against(t1);

            try
            {
                exec.Validate(null);
                Assert.Fail("Expected failure when result is null.");
            }
            catch { }

            var r2 = exec.TryValidate(null);

            Assert.IsFalse(r2.IsValid);
            Assert.AreEqual(1, r2.FailureList.Length);
        }
        /// <summary>
        /// <para>Initializes a new instance of the <see cref="ObjectCollectionValidator"/> for a target type
        /// using the supplied ruleset.</para>
        /// </summary>
        /// <param name="targetType">The target type</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <param name="targetRuleset">The ruleset to use.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="targetType"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">when <paramref name="targetRuleset"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">when <paramref name="validatorFactory"/> is <see langword="null"/>.</exception>
        public ObjectCollectionValidator(Type targetType, ValidatorFactory validatorFactory, string targetRuleset)
            : base(null, null)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (targetRuleset == null)
            {
                throw new ArgumentNullException("targetRuleset");
            }
            if (validatorFactory == null)
            {
                throw new ArgumentNullException("validatorFactory");
            }

            this.targetType          = targetType;
            this.targetTypeValidator = validatorFactory.CreateValidator(targetType, targetRuleset);
            this.targetRuleset       = targetRuleset;
            this.validatorFactory    = null;
        }
예제 #44
0
        /// <summary>
        /// Creates the <see cref="Validator"/> described by the attribute.
        /// </summary>
        /// <param name="targetType">The type of object that will be validated by the validator.</param>
        /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
        /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
        /// require access to properties.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <returns>The created <see cref="Validator"/>.</returns>
        protected override Validator DoCreateValidator(Type targetType,
                                                       Type ownerType,
                                                       MemberValueAccessBuilder memberValueAccessBuilder,
                                                       ValidatorFactory validatorFactory)
        {
            PropertyInfo propertyInfo = ValidationReflectionHelper.GetProperty(ownerType, this.PropertyToCompare, false);

            if (propertyInfo == null)
            {
                throw new InvalidOperationException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Resources.ExceptionPropertyToCompareNotFound,
                              this.PropertyToCompare,
                              ownerType.FullName));
            }

            return(new ebIViewModels.Validation.PropertyComparisonValidator(memberValueAccessBuilder.GetPropertyValueAccess(propertyInfo),
                                                                            this.ComparisonOperator,
                                                                            this.Negated));
        }
예제 #45
0
        public CatalogAggregateValidator(ValidatorFactory factory, ValidatorConfiguration configuration)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

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

            var validators = new List <IValidator>();

            if (configuration.RequirePackageSignature)
            {
                validators.Add(factory.Create(typeof(PackageHasSignatureValidator)));
            }

            _validators = validators;
        }
예제 #46
0
        public async Task Reused_AuthorizationCode()
        {
            var client = await _settings.FindClientByIdAsync("codeclient");

            var store = new TestAuthorizationCodeStore();

            var code = new AuthorizationCode
            {
                Client      = client,
                IsOpenId    = true,
                RedirectUri = new Uri("https://server/cb"),
            };

            await store.StoreAsync("valid", code);

            var validator = ValidatorFactory.CreateTokenValidator(_settings, _logger,
                                                                  authorizationCodeStore: store,
                                                                  customRequestValidator: new DefaultCustomRequestValidator());

            var parameters = new NameValueCollection();

            parameters.Add(Constants.TokenRequest.GrantType, Constants.GrantTypes.AuthorizationCode);
            parameters.Add(Constants.TokenRequest.Code, "valid");
            parameters.Add(Constants.TokenRequest.RedirectUri, "https://server/cb");

            // request first time
            var result = await validator.ValidateRequestAsync(parameters, client);

            Assert.IsFalse(result.IsError);

            // request second time
            validator = ValidatorFactory.CreateTokenValidator(_settings, _logger,
                                                              authorizationCodeStore: store,
                                                              customRequestValidator: new DefaultCustomRequestValidator());

            result = await validator.ValidateRequestAsync(parameters, client);

            Assert.IsTrue(result.IsError);
            Assert.AreEqual(Constants.TokenErrors.InvalidGrant, result.Error);
        }
예제 #47
0
        private void Initialize(IOptions <S3Config> options, INetworkDriver networkDriver, ILoggerFactory loggerFactory)
        {
            Assembly assembly = typeof(S3Config).Assembly;

            SimpleServiceProvider provider = new SimpleServiceProvider((typeof(IOptions <S3Config>), options));

            IEnumerable <IValidator>       validators       = CreateInstances <IValidator>(assembly, provider);
            IEnumerable <IRequestMarshal>  requestMarshals  = CreateInstances <IRequestMarshal>(assembly, provider);
            IEnumerable <IResponseMarshal> responseMarshals = CreateInstances <IResponseMarshal>(assembly, provider);
            IEnumerable <IPostMapper>      postMappers      = CreateInstances <IPostMapper>(assembly, provider);
            IEnumerable <IRequestWrapper>  requestWrappers  = CreateInstances <IRequestWrapper>(assembly, provider).ToList();
            IEnumerable <IResponseWrapper> responseWrappers = CreateInstances <IResponseWrapper>(assembly, provider).ToList();

            ValidatorFactory           validatorFactory     = new ValidatorFactory(validators);
            IMarshalFactory            marshalFactory       = new MarshalFactory(requestMarshals, responseMarshals);
            IPostMapperFactory         postMapperFactory    = new PostMapperFactory(postMappers);
            IScopeBuilder              scopeBuilder         = new ScopeBuilder(options);
            ISigningKeyBuilder         signingKeyBuilder    = new SigningKeyBuilder(options, loggerFactory.CreateLogger <SigningKeyBuilder>());
            ISignatureBuilder          signatureBuilder     = new SignatureBuilder(signingKeyBuilder, scopeBuilder, loggerFactory.CreateLogger <SignatureBuilder>(), options);
            HeaderAuthorizationBuilder authorizationBuilder = new HeaderAuthorizationBuilder(options, scopeBuilder, signatureBuilder, loggerFactory.CreateLogger <HeaderAuthorizationBuilder>());

            ChunkedSignatureBuilder            chunkedBuilder       = new ChunkedSignatureBuilder(signingKeyBuilder, scopeBuilder, loggerFactory.CreateLogger <ChunkedSignatureBuilder>());
            ChunkedContentRequestStreamWrapper chunkedStreamWrapper = new ChunkedContentRequestStreamWrapper(options, chunkedBuilder, signatureBuilder);

            DefaultRequestHandler requestHandler = new DefaultRequestHandler(options, validatorFactory, marshalFactory, postMapperFactory, networkDriver, authorizationBuilder, loggerFactory.CreateLogger <DefaultRequestHandler>(), new[] { chunkedStreamWrapper });

            ObjectOperations objectOperations = new ObjectOperations(requestHandler, requestWrappers, responseWrappers);

            _objectClient = new S3ObjectClient(objectOperations);

            BucketOperations bucketOperations = new BucketOperations(requestHandler);

            _bucketClient = new S3BucketClient(bucketOperations);

            MultipartOperations multipartOperations = new MultipartOperations(requestHandler, requestWrappers, responseWrappers);

            _multipartClient = new S3MultipartClient(multipartOperations, objectOperations);

            Transfer = new Transfer(objectOperations, multipartOperations);
        }
        public void ShouldAllowComparingDifferentTypes()
        {
            var val = ValidatorFactory.GetValidator <Testable, ComplexTestable>();
            var t1  = new ComplexTestable {
                Id = Guid.NewGuid(), Name = new Name {
                    First = "Foo", Last = "Bar"
                }
            };
            var t2 = new Testable {
                Id = t1.Id, Name = $"{t1.Name.First} {t1.Name.Last}"
            };
            var t3 = new Testable {
                Id = t1.Id, Name = "Not Valid"
            };

            val.WithMapping("Name", "Name", (p) => p.ToString());
            var exec = val.Against(t1);

            exec.Validate(t2);

            try
            {
                exec.Validate(t3);
                Assert.Fail("Expected an AssertFailedException from the result validator");
            }
            catch (AssertFailedException e)
            {
                Assert.IsInstanceOfType(e, typeof(AssertFailedException));
            }

            var r1 = exec.TryValidate(t2);

            Assert.IsTrue(r1.IsValid);
            Assert.AreEqual(0, r1.FailureList.Length);

            var r2 = exec.TryValidate(t3);

            Assert.IsFalse(r2.IsValid);
            Assert.AreEqual(1, r2.FailureList.Length);
        }
 public Validator CreateValidator(Type targetType, Type ownerType, MemberValueAccessBuilder memberValueAccessBuilder, ValidatorFactory ignored)
 {
     return new ValidationAttributeValidator(this.attributes);
 }
 /// <summary>
 /// Creates a <see cref="ValidationCallHandler"/> that uses the given
 /// ruleset and <see cref="ValidatorFactory"/> to get the validation rules.
 /// </summary>
 /// <param name="ruleSet">Validation ruleset as specified in configuration.</param>
 /// <param name="validatorFactory">The <see cref="ValidatorFactory"/> to use when building the validator for the 
 /// type of a parameter, or <see langword="null"/> if no such validator is desired.</param>
 /// <param name="handlerOrder">Order of the handler</param>
 public ValidationCallHandler(string ruleSet, ValidatorFactory validatorFactory, int handlerOrder)
 {
     this.ruleSet = ruleSet;
     this.validatorFactory = validatorFactory;
     this.order = handlerOrder;
 }
예제 #51
0
        static void Main(string[] args)
        {
            // Resolve the default ValidatorFactory object from the container.
            valFactory = EnterpriseLibraryContainer.Current.GetInstance<ValidatorFactory>();

            new MenuDrivenApplication("Validation Block Developer's Guide Examples",
                UsingAValidationRuleSetToValidateAnObject,
                ValidatingACollectionOfObjects,
                UsingValidationAttributesAndSelfValidation,
                UsingDataAnnotationsValidationAttributesAndSelfValidation,
                CreatingAndUsingValidatorsDirectly,
                ValidatingParametersInAWCFService).Run();
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="memberAccessValidatorFactory"></param>
 /// <param name="validatorFactory"></param>
 public MetadataValidatorBuilder(
     MemberAccessValidatorBuilderFactory memberAccessValidatorFactory,
     ValidatorFactory validatorFactory)
     : base(memberAccessValidatorFactory, validatorFactory)
 { }
 /// <summary>
 /// Creates the <see cref="ObjectCollectionValidator"/> described by the configuration object.
 /// </summary>
 /// <param name="targetType">The type of object that will be validated by the validator.</param>
 /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
 /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
 /// require access to properties.</param>
 /// <param name="validatorFactory">Factory to use when building nested validators.</param>
 /// <returns>The created <see cref="Validator"/>.</returns>
 protected override Validator DoCreateValidator(
     Type targetType,
     Type ownerType,
     MemberValueAccessBuilder memberValueAccessBuilder,
     ValidatorFactory validatorFactory)
 {
     // avoid supplied target type - that's the type of the collection
     if (this.TargetType != null)
     {
         return new ObjectCollectionValidator(this.TargetType, validatorFactory, this.targetRuleset);
     }
     else
     {
         return new ObjectCollectionValidator(validatorFactory, this.targetRuleset);
     }
 }
예제 #54
0
        /// <summary>
        /// <para>Initializes a new instance of the <see cref="ObjectValidator"/> for a target type
        /// using the supplied ruleset.</para>
        /// </summary>
        /// <param name="targetType">The target type</param>
        /// <param name="targetRuleset">The ruleset to use.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="targetType"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">when <paramref name="targetRuleset"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException">when <paramref name="validatorFactory"/> is <see langword="null"/>.</exception>
        public ObjectValidator(Type targetType, ValidatorFactory validatorFactory, string targetRuleset)
            : base(null, null)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (validatorFactory == null)
            {
                throw new ArgumentNullException("validatorFactory");
            }
            if (targetRuleset == null)
            {
                throw new ArgumentNullException("targetRuleset");
            }

            this.targetType = targetType;
            this.targetTypeValidator = validatorFactory.CreateValidator(targetType, targetRuleset);
            this.targetRuleset = targetRuleset;
            this.validatorFactory = null;
        }
예제 #55
0
파일: SiteService.cs 프로젝트: abrajoe/SKS
 public SiteService(IRepository<Site> reposite, IRepository<Measurement> repomeasurement)
 {
     valFactory = EnterpriseLibraryContainer.Current.GetInstance<ValidatorFactory>();
     this.reposite_ = reposite;
 }
예제 #56
0
 /// <summary>
 /// <para>Initializes a new instance of the <see cref="ObjectCollectionValidator"/> 
 /// using the supplied ruleset.</para>
 /// </summary>
 /// <param name="validatorFactory">Factory to use when building nested validators.</param>
 public ObjectCollectionValidator(ValidatorFactory validatorFactory)
     : this(validatorFactory, string.Empty)
 { }
 /// <summary>
 /// Creates the <see cref="Validator"/> described by the configuration object.
 /// </summary>
 /// <param name="targetType">The type of object that will be validated by the validator.</param>
 /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
 /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
 /// require access to properties.</param>
 /// <param name="validatorFactory">Factory to use when building nested validators.</param>
 /// <returns>The created <see cref="Validator"/>.</returns>
 /// <remarks>
 /// The default implementation invokes <see cref="ValidatorAttribute.DoCreateValidator(Type)"/>. Subclasses requiring access to all
 /// the parameters or this method may override it instead of <see cref="ValidatorAttribute.DoCreateValidator(Type)"/>.
 /// </remarks>
 protected virtual Validator DoCreateValidator(
     Type targetType,
     Type ownerType,
     MemberValueAccessBuilder memberValueAccessBuilder,
     ValidatorFactory validatorFactory)
 {
     return DoCreateValidator(targetType);
 }
예제 #58
0
 public static void Reset()
 {
     if (validatorFactory != null)
     {
         validatorFactory.ResetCache();
         validatorFactory = null;
         GC.Collect(GC.MaxGeneration, GCCollectionMode.Optimized);    
     }
 }
예제 #59
0
        private static void InitializeFactory(ValidationContext context)
        {
            if (validatorFactory == null)
            {
                string rulePath = GetConfigurationRulePath(context);
				if (!string.IsNullOrEmpty(rulePath))
                {
                    validatorFactory = ConfigurationValidatorFactory.FromConfigurationSource(new FileConfigurationSource(rulePath));
				}
            }
        }
예제 #60
0
        /// <summary>
        /// Creates the <see cref="Validator"/> described by the configuration object.
        /// </summary>
        /// <param name="targetType">The type of object that will be validated by the validator.</param>
        /// <param name="ownerType">The type of the object from which the value to validate is extracted.</param>
        /// <param name="memberValueAccessBuilder">The <see cref="MemberValueAccessBuilder"/> to use for validators that
        /// require access to properties.</param>
        /// <param name="validatorFactory">Factory to use when building nested validators.</param>
        /// <returns>The created <see cref="Validator"/>.</returns>
        Validator IValidatorDescriptor.CreateValidator(
            Type targetType,
            Type ownerType,
            MemberValueAccessBuilder memberValueAccessBuilder,
            ValidatorFactory validatorFactory)
        {
            Validator validator = DoCreateValidator(targetType, ownerType, memberValueAccessBuilder, validatorFactory);
            validator.Tag = string.IsNullOrEmpty(this.Tag) ? null : this.Tag;
            validator.MessageTemplate = GetMessageTemplate();

            return validator;
        }