/// <summary> /// 处理规范化结果 /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // 执行 Action 并获取结果 var actionExecutedContext = await next(); // 如果出现异常,则不会进入该过滤器 if (actionExecutedContext.Exception != null) { return; } // 获取控制器信息 var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; // 判断是否支持 MVC 规范化处理 if (!UnifyContext.CheckSupportMvcController(context.HttpContext, actionDescriptor, out _)) { return; } // 判断是否跳过规范化处理 if (UnifyContext.CheckSucceededNonUnify(actionDescriptor.MethodInfo, out var unifyResult)) { return; } // 处理 BadRequestObjectResult 类型规范化处理 if (actionExecutedContext.Result is BadRequestObjectResult badRequestObjectResult) { // 解析验证消息 var validationMetadata = ValidatorContext.GetValidationMetadata(badRequestObjectResult.Value); var result = unifyResult.OnValidateFailed(context, validationMetadata); if (result != null) { actionExecutedContext.Result = result; } // 打印验证失败信息 App.PrintToMiniProfiler("validation", "Failed", $"Validation Failed:\r\n{validationMetadata.Message}", true); } else { IActionResult result = default; // 检查是否是有效的结果(可进行规范化的结果) if (UnifyContext.CheckVaildResult(actionExecutedContext.Result, out var data)) { result = unifyResult.OnSucceeded(actionExecutedContext, data); } // 如果是不能规范化的结果类型,则跳过 if (result == null) { return; } actionExecutedContext.Result = result; } }
public string BuildJS(ValidatorContext context) { var attr = context.Attribute <ContainsAllAttribute>(); var arrJson = JsonConvert.SerializeObject(attr.Characters); return($"value => {arrJson}.every(o => value.indexOf(o) != -1)"); }
public string BuildForModelType(Type modelType) { var js = new StringBuilder(); js.Append("({"); foreach (var prop in modelType.GetProperties()) { var context = new ValidatorContext(null, prop); js.Append(prop.Name + ":["); foreach (var val in Validators.ForProperty(prop)) { js.Append("(").Append(val.BuildJS(context)).Append("),"); } js.Append("],"); } js.Append("})"); //return new JavaScriptCompressor().Compress(js.ToString()); return(new JsMinifier().Minify(js.ToString())); }
public IEnumerable <IValidator> CreateContentValidators(ValidatorContext context, ValidatorFactory createFieldValidator) { foreach (var validatorTag in ValidatorTags(context.Schema.Properties.Tags)) { yield return(new CompositeUniqueValidator(validatorTag, contentRepository)); } }
public ValidatorResult Check(object value, ValidatorContext context) { var attr = context.Attribute <ContainsAllAttribute>(); var str = (string)value; return(attr.Characters.All(str.Contains)); }
public ValidatorResult Check(object value, ValidatorContext context) { var attr = context.Attribute <StringLengthAttribute>(); var str = (string)value; return(str.Length >= attr.MinimumLength && str.Length <= attr.MaximumLength ? ValidatorResult.Success : attr.ErrorMessage ?? $"@$ must be between {attr.MinimumLength} and {attr.MaximumLength} characters long"); }
public override bool IsValidValue(object obj, ValidatorContext context) { if(obj == null) return false; var str = obj as string; if (str == null || AllowStringEmpty) return true; return !string.IsNullOrWhiteSpace(str); }
/// <summary> /// Registers the validator for. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity">The entity.</param> /// <param name="validator">The validator.</param> public static void RegisterValidatorFor <T>(IValidator <T> validator, ValidatorContext context) where T : IValidatable <T> { ValidatorKey key = new ValidatorKey(); key.EntityType = typeof(T); key.ValidatorContext = context; validators.Add(string.Format(KEY, key.EntityType.ToString(), key.ValidatorContext.ToString()), validator); }
private IValidatorContext CreateContextInternal(object instanceToValidate) { Should.NotBeNull(instanceToValidate, nameof(instanceToValidate)); EnsureNotDisposed(); var ctx = new ValidatorContext(instanceToValidate, PropertyMappings, IgnoreProperties, Settings.Metadata, this.GetIocContainer(true, false)); ctx.ValidationMetadata.AddOrUpdate(ValidationConstants.ViewModel, this); return(ctx); }
public IEnumerable <IValidator> CreateValueValidators(ValidatorContext context, IField field, ValidatorFactory createFieldValidator) { if (field is IField <ReferencesFieldProperties> references) { yield return(new ReferencesValidator(references.Properties.IsRequired, references.Properties, ids => { var result = ids.Select(x => (schemaId, x, Status.Published)).ToList(); return Task.FromResult <IReadOnlyList <(DomainId SchemaId, DomainId Id, Status Status)> >(result); }));
void IOpenXmlSimpleTypeValidator.Validate(ValidatorContext context) { if (!context.Version.AtLeast(OfficeVersion) && context.Value?.HasValue == true && !context.McContext.IsIgnorableNs(context.QName.Namespace)) { context.CreateError( id: "Sch_UndeclaredAttribute", description: SR.Format(ValidationResources.Sch_UndeclaredAttribute, context.QName), errorType: ValidationErrorType.Schema); } }
public ValidatorResult Check(object value, ValidatorContext context) { var attr = context.Attribute <MaxLengthAttribute>(); return(value is string str ? str.Length <= attr.Length ? ValidatorResult.Success : attr.ErrorMessage ?? $"@$ must be less than {attr.Length} characters long" : value is Array arr ? arr.Length <= attr.Length ? ValidatorResult.Success : attr.ErrorMessage ?? $"@$ must be less than {attr.Length} items long" : throw new ArgumentException("Invalid type", nameof(value))); }
/// <summary> /// Gets the validator for. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity">The entity.</param> /// <returns></returns> public static IValidator <T> GetValidatorFor <T>(T entity, ValidatorContext context) where T : IValidatable <T> { ValidatorKey key = new ValidatorKey(); key.EntityType = typeof(T); key.ValidatorContext = context; return(validators[string.Format(KEY, key.EntityType.ToString(), key.ValidatorContext.ToString())] as IValidator <T>); }
private void ParseTokenOperators(IEnumerable <RawTokenDecorator> decorators, List <TransformerContext> tokenTransformers, List <ValidatorContext> tokenValidators) { foreach (var decorator in decorators) { TransformerContext transformerContext = null; ValidatorContext validatorContext = null; foreach (var operatorType in transformers) { if (string.Compare(decorator.Name, operatorType.Name, StringComparison.InvariantCultureIgnoreCase) == 0 || string.Compare($"{decorator.Name}Transformer", operatorType.Name, StringComparison.InvariantCultureIgnoreCase) == 0) { transformerContext = new TransformerContext(operatorType); foreach (var arg in decorator.Args) { transformerContext.Parameters.Add(arg); } tokenTransformers.Add(transformerContext); break; } } if (transformerContext != null) { continue; } foreach (var validatorType in validators) { if (string.Compare(decorator.Name, validatorType.Name, StringComparison.InvariantCultureIgnoreCase) == 0 || string.Compare($"{decorator.Name}Validator", validatorType.Name, StringComparison.InvariantCultureIgnoreCase) == 0) { validatorContext = new ValidatorContext(validatorType); foreach (var arg in decorator.Args) { validatorContext.Parameters.Add(arg); } tokenValidators.Add(validatorContext); break; } } if (validatorContext == null) { throw new TokenizerException($"Unknown Token Operation: {decorator.Name}"); } } }
private static bool IsRequired(ValidatorContext context, FieldProperties properties) { var isRequired = properties.IsRequired; if (context.Action == ValidationAction.Publish) { isRequired = isRequired || properties.IsRequiredOnPublish; } return(isRequired); }
public ValidatorResult Check(object value, ValidatorContext context) { var attr = context.Attribute <RegularExpressionAttribute>(); if (!Regex.IsMatch((string)value, attr.Pattern)) { return(attr.ErrorMessage ?? "Invalid format"); } return(true); }
public void Validate(ValidatorContext ctx, TType type, DType data) { if (type.IsNullable && data == null) { return; } if (!_datas.Contains(data)) { ctx.Assembly.Agent.Error("记录 {0}:{1} (来自文件:{2}) 值不在set:{3}中", ValidatorContext.CurrentRecordPath, data, ValidatorContext.CurrentVisitor.CurrentValidateRecord.Source, _valueSetStr); } }
public void Execute(ValidatorContext context, string id) { var key = context.Validator.PublicKey; var commandData = new Dictionary <string, object>(); commandData.Add("type", "set_validator_key"); commandData.Add("key", key.GetChangeableCopy()); var command = context.MainFactory.CreateInstance <ICommand>(commandData); var json = fastJSON.JSON.ToJSON(command.GetInfo()); context.Server.SendMessage(json, id); }
public IEnumerable <IValidator> CreateValueValidators(ValidatorContext context, IField field, ValidatorFactory createFieldValidator) { if (field is IField <AssetsFieldProperties> assets) { yield return(new AssetsValidator(assets.Properties.IsRequired, assets.Properties, ids => { var result = ids.Select(TestAssets.Document).ToList(); return Task.FromResult <IReadOnlyList <IAssetInfo> >(result); })); } }
public void Execute(ValidatorContext context, string connectionId) { if (context.RegisteredUsers.CanRegister(Id)) { context.RegisteredUsers.FillUserKey(Id, Key); Console.WriteLine($"User {Id} registered"); } var canLogin = context.RegisteredUsers.CanLogin(Id); var command = new LoginAcceptanceCommand(canLogin); context.Server.SendCommand(command, connectionId); }
public IEnumerable <IValidator> CreateValueValidators(ValidatorContext context, IField field, ValidatorFactory createFieldValidator) { if (context.Mode == ValidationMode.Optimized) { yield break; } var isRequired = IsRequired(context, field.RawProperties); if (field is IField <AssetsFieldProperties> assetsField) { var checkAssets = new CheckAssets(async ids => { return(await assetRepository.QueryAsync(context.AppId.Id, null, Q.Empty.WithIds(ids), default)); }); yield return(new AssetsValidator(isRequired, assetsField.Properties, checkAssets)); } if (field is IField <ReferencesFieldProperties> referencesField) { var checkReferences = new CheckContentsByIds(async ids => { return(await contentRepository.QueryIdsAsync(context.AppId.Id, ids, SearchScope.All, default)); }); yield return(new ReferencesValidator(isRequired, referencesField.Properties, checkReferences)); } if (field is IField <NumberFieldProperties> numberField && numberField.Properties.IsUnique) { var checkUniqueness = new CheckUniqueness(async filter => { return(await contentRepository.QueryIdsAsync(context.AppId.Id, context.SchemaId.Id, filter, default)); }); yield return(new UniqueValidator(checkUniqueness)); } if (field is IField <StringFieldProperties> stringField && stringField.Properties.IsUnique) { var checkUniqueness = new CheckUniqueness(async filter => { return(await contentRepository.QueryIdsAsync(context.AppId.Id, context.SchemaId.Id, filter, default)); }); yield return(new UniqueValidator(checkUniqueness)); } }
public override bool IsValidValue(object obj, ValidatorContext context) { try { var span = TimeSpan.Parse((string) obj, CultureInfo.CurrentUICulture); if (!_mustBePositive && span.Ticks >= 0) return true; TimeSpan.Parse("-100000000000000000000000000"); return true; } catch (Exception e) when(e is FormatException || e is OverflowException || e is ArgumentException) { _message = e.Message; return false; } }
/// <summary> /// Wraps the error. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="REQUEST">The type of the equest.</typeparam> /// <typeparam name="RESPONSE">The type of the esponse.</typeparam> /// <param name="request">The request.</param> /// <param name="response">The response.</param> /// <param name="context">The context.</param> /// <exception cref="PayUException"></exception> /*protected AbstractResponse WrapError<REQUEST, RESPONSE>( * AbstractPostRequestStrategy<REQUEST, RESPONSE> requestStrategy) * where RESPONSE : AbstractResponse * { * requestStrategy.SendRequest(); * RESPONSE response = requestStrategy.RestResponse.Data; * * response * * return null; * }*/ public void Validate <T, REQUEST>(REQUEST request, ValidatorContext context) where REQUEST : AbstractRequest <T> where T : IValidatable <T> { IEnumerable <string> brokenRules; if (!request.Entity.Validate <T>(out brokenRules, context)) { StringBuilder msg = new StringBuilder(); foreach (var brokeRule in brokenRules) { msg.AppendLine(brokeRule); } throw new PayUException(ErrorCode.INVALID_PARAMETERS, FormatErrorMessage(msg.ToString())); } }
/// <summary> /// 处理规范化结果 /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // 排除 Mvc 视图 var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; if (typeof(Controller).IsAssignableFrom(actionDescriptor.ControllerTypeInfo)) { await next(); return; } var actionExecutedContext = await next(); // 如果没有异常再执行 if (actionExecutedContext.Exception == null && !UnifyContext.IsSkipUnifyHandlerOnSucceedReturn(actionDescriptor.MethodInfo, out var unifyResult)) { // 处理规范化结果 if (unifyResult != null) { // 处理 BadRequestObjectResult 验证结果 if (actionExecutedContext.Result is BadRequestObjectResult badRequestObjectResult) { // 解析验证消息 var(validationResults, validateFaildMessage, modelState) = ValidatorContext.OutputValidationInfo(badRequestObjectResult.Value); var result = unifyResult.OnValidateFailed(context, modelState, validationResults, validateFaildMessage); if (result != null) { actionExecutedContext.Result = result; } // 打印验证失败信息 App.PrintToMiniProfiler("validation", "Failed", $"Validation Failed:\r\n{validateFaildMessage}", true); } else { var result = unifyResult.OnSucceeded(actionExecutedContext); if (result != null) { actionExecutedContext.Result = result; } } } } }
public void Execute(ValidatorContext context, string id) { var validator = context.Validator; if (!context.RegisteredUsers.CanVote(Id)) { var command = new DeclineVoteCommand(); context.Server.SendCommand(command, id); } else if (validator.VerifyBulletin(BlindedSigned, Blinded, context.RegisteredUsers.GetSignKey(Id))) { var signedByValidator = validator.SignBulletin(Blinded); Console.WriteLine("bulletin validated"); context.RegisteredUsers.SetVoted(Id); var command = new SendElectorSignedCommand(signedByValidator); context.Server.SendCommand(command, id); } }
/// <summary> /// Create a <see cref="ValidatorContext" /> instance from a <see cref="ValidatorContext" />. /// </summary> /// <param name="configuration">The configuration instance.</param> /// <returns>A new <see cref="ValidatorContext" /> instance.</returns> public static ValidatorContext ToContext(this SolutionValidatorConfigurationSection configuration) { Argument.IsNotNull(() => configuration); var validatorContext = new ValidatorContext(); if (configuration.FolderStructure != null) { CreateFolderStructureContext(configuration, validatorContext); } if (configuration.ProjectFile != null) { CreateProjectFileContext(configuration, validatorContext); } return(validatorContext); }
public async Task <ActionResult <Training> > PostTraining(Training training) { ValidatorContext validatorContext = new ValidatorContext(); validatorContext.AddValidators(new DateOrderValidator(training)); if (validatorContext.ContainsError()) { Response.Headers.Add("statusText", validatorContext.ErrorMessage); return(BadRequest("Bad Request")); } _context.Trainings.Add(training); await _context.SaveChangesAsync(); Response.Headers.Add("statusText", "Resource Created"); return(CreatedAtAction("GetTraining", new { id = training.Id }, training)); }
private List <IValidatorRunEntry> RunValidatorInstance(ValidatorInstanceInfo info) { var startTime = DateTime.Now; IValidatorProxy validatorProxy = null; try { validatorProxy = _validatorProvider.GetValidatorProxy(info.ValidatorId); IValidatorInstance validatorInstance = _validatorProvider.GetValidatorInstance(info.ValidatorId, info.ValidatorInstanceId); log.Debug("Validator: {ValidatorId} Version: {ValidatorVersion}{NewLine} Description: {Description}", validatorProxy.ValidatorId, validatorProxy.Version.ToString(), Environment.NewLine, validatorProxy.Description); log.Debug("ValidatorInstance: {Name} Description: {Description} beginning to validate.", validatorInstance.Name, validatorInstance.Description); IValidator validator = validatorProxy.Create(validatorInstance); IValidatorContext vc = new ValidatorContext(); IList <IValidatorResult> results = validator.Execute(vc); var endTime = DateTime.Now; log.Debug("ValidatorInstance: {Name} finished validating. Start: {start} End: {end}", validatorInstance.Name, startTime.ToString(), endTime.ToString()); log.Debug("ValidatorInstance: {Name} returned {resultCount} results.", validatorInstance.Name, results.Count); List <IValidatorRunEntry> runEntries = results.Select(x => new ValidatorRunEntry(startTime, endTime, x, validator.FilterSequence) { } as IValidatorRunEntry).ToList(); return(runEntries); } catch (Exception ex) { log.Error(ex, "{ValidatorProxy} execution caused Error: {Message}", validatorProxy.ValidatorId, ex.Message); var vr = new ValidatorResult(validatorProxy.ValidatorId, ex.Message, ValidatorResultCode.Error, UnhandledExceptionResultCode); var vre = new ValidatorRunEntry(startTime, DateTime.Now, vr); return(new List <IValidatorRunEntry>() { vre }); } }
private void btn_Save_Click(object sender, EventArgs e) { ValidatorContext validate = new ValidatorContext(new EmailValidator()); ValidatorContext phone = new ValidatorContext(new PhoneValidator()); if (validate.validation(txt_UserId.Text)) { if (phone.validation(txt_Phone.Text)) { if (txt_Password.Text != txt_Password2.Text || txt_Password.Text == "") { MessageBox.Show("Please make sure the password 2 is same as Pasword 1"); txt_Password.Text = ""; txt_Password2.Text = ""; } else { //////////need to finish MessageBox.Show("Need to add the Logic"); // SignUpClass signUp = new SignUpClass(); // signUp.InsertData(txt_UserId.Text, txt_Password.Text, txt_FirstName.Text, txt_LastName.Text, txt_RSA.Text); txt_UserId.Text = ""; txt_Password.Text = ""; txt_Password2.Text = ""; txt_FirstName.Text = ""; txt_LastName.Text = ""; txt_Phone.Text = ""; } } else { MessageBox.Show("Please enter a valid phone!"); } } else { MessageBox.Show("Please enter a valid e-mail!"); } }
public void ValidateRelativityProcessorCaseStatisticsRowsFoundSucceeds(IList <CaseStatisticsMonthly> caseStatsMonthlyList, IList <CaseStatistics> caseStatsList, List <ConfigSection> fakeSections, IList <DataCollectionsRuns> dataCollectionRunsList, IList <UserCollectionsRuns> userCollectionRunsList, BillingValidatorSettings billingSettings) { var kernel = this.GetBillingValidatorWithAllKernelBindings(); var relBillingRepo = kernel.Get <IRelativityBillingRepo>(); var relProvidersRepo = kernel.Get <IRelativityProvidersRepo>(); var billingValidator = new BillingRanValidator(relBillingRepo, relProvidersRepo, billingSettings); relBillingRepo.GetCaseStatistics(Arg.Any <DateTime>()).ReturnsForAnyArgs(caseStatsList); relBillingRepo.GetCaseStatisticsMonthly(Arg.Any <DateTime>()).ReturnsForAnyArgs(caseStatsMonthlyList); relProvidersRepo.GetDataCollectionsRuns(Arg.Any <DateTime>()).ReturnsForAnyArgs(dataCollectionRunsList); relProvidersRepo.GetUserCollectionsRuns(Arg.Any <DateTime>()).ReturnsForAnyArgs(userCollectionRunsList); var validatorContext = new ValidatorContext(); IList <IValidatorResult> results = billingValidator.Execute(validatorContext); Assert.Equal(results.Where(r => r.ResultCode == ValidatorResultCode.Success).Count(), 4); }
private static void CreateProjectFileContext(SolutionValidatorConfigurationSection configuration, ValidatorContext validatorContext) { Argument.IsNotNull(() => configuration); Argument.IsNotNull(() => validatorContext); validatorContext.ProjectFile.CheckOutPutPath = configuration.ProjectFile.OutputPath.Check; validatorContext.ProjectFile.OutputPath = configuration.ProjectFile.OutputPath.Value; validatorContext.ProjectFile.CheckRequiredConfigurations = configuration.ProjectFile.RequiredConfigurations.Check; validatorContext.ProjectFile.CheckIdentical = configuration.ProjectFile.CheckIdentical.Check; validatorContext.ProjectFile.CheckPropertyValues = configuration.ProjectFile.CheckForValue.Check; if (configuration.ProjectFile.RequiredConfigurations != null) { foreach (ConfigurationNameElement configurationNameElement in configuration.ProjectFile.RequiredConfigurations) { validatorContext.ProjectFile.RequiredConfigurations.Add(configurationNameElement.Name); } } if (configuration.ProjectFile.CheckIdentical != null) { foreach (PropertiesToMatchElement propertiesToMatchElement in configuration.ProjectFile.CheckIdentical) { validatorContext.ProjectFile.IdenticalChecks.Add(new IdenticalCheck { PropertyName = propertiesToMatchElement.PropertyName, OtherPropertyName = propertiesToMatchElement.OtherPropertyName }); } } if (configuration.ProjectFile.CheckForValue != null) { foreach (PropertyToCheckElement propertyToCheckElement in configuration.ProjectFile.CheckForValue) { validatorContext.ProjectFile.Properties.Add(new Property { Name = propertyToCheckElement.PropertyName, Value = propertyToCheckElement.Value }); } } }
private static void CreateFolderStructureContext(SolutionValidatorConfigurationSection configuration, ValidatorContext validatorContext) { Argument.IsNotNull(() => configuration); Argument.IsNotNull(() => validatorContext); validatorContext.FolderStructure.DefinitionFilePath = configuration.FolderStructure.DefinitionFilePath; validatorContext.FolderStructure.Check = configuration.FolderStructure.Check; }