private ValidatorProvider GetProvider() { var provider = new ValidatorProvider(); provider.Register( StringValidator.NotEmpty, ValidatorCollection.Create <string>() .Add(e => (!string.IsNullOrEmpty(e), "Can't be empty"))); provider.Register( StringValidator.MinLength3, ValidatorCollection.Create <string>() .Add(e => (e.Length >= 3, "Length must be at least 3"))); provider.Register( StringValidator.MinLength7, ValidatorCollection.Create <string>() .Add(e => (e.Length >= 7, "Length must be at least 7"))); provider.Register( StringValidator.Lowercase, ValidatorCollection.Create <string>() .Add(e => (e == e.ToLower(), "Must be in lowercase"))); return(provider); }
public async Task <IHttpActionResult> UpdateBannerAsync(int id, Banner json) { if (id <= 0) { throw new BadRequestException(ResultCode.ArgumentException, "请选择要更新的Banner"); } if (json == null) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var banner = await this.m_BannerStorage.GetAsync(id); if (banner == null) { throw new BadRequestException(ResultCode.ArgumentException, "更新的案例不存在"); } banner.title = json.title; banner.image_url = json.image_url; banner.type = json.type; banner.link_url = json.link_url; banner.sort = json.sort; ValidatorProvider.ThrowIfInValidate <BannerValidator, Banner>(banner); int count = await this.m_BannerStorage.UpdateAsync(json); if (count <= 0) { throw new BadRequestException(ResultCode.ActionFail, "更新失败"); } return(Json(JsonApiResult.Ok(""))); }
public BaseFacts() { ServiceProviderMock = new Mock <IServiceProvider>(); LoggerMock = new Mock <ILogger <ValidatorProvider> >(); Target = new ValidatorProvider(ServiceProviderMock.Object, LoggerMock.Object); }
public async Task <IHttpActionResult> UpdateCaseAsync(int id, CaseInfo json) { if (id <= 0) { throw new BadRequestException(ResultCode.ArgumentException, "请选择要更新的案例"); } if (json == null) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var cases = await this.m_CaseInfoStorage.GetAsync(id); if (cases == null) { throw new BadRequestException(ResultCode.ArgumentException, "更新的案例不存在"); } cases.title = json.title; cases.imgurl = json.imgurl; cases.typeid = json.typeid; cases.link = json.link; cases.seecount = json.seecount; cases.prizecount = json.prizecount; cases.sort = json.sort; ValidatorProvider.ThrowIfInValidate <CaseInfoValidator, CaseInfo>(cases); int count = await this.m_CaseInfoStorage.UpdateAsync(json); if (count <= 0) { throw new BadRequestException(ResultCode.ActionFail, "更新失败"); } return(Json(JsonApiResult.Ok(""))); }
public void ThrowsOnUnknownValidator() { const string validatorName = "someNonExistentValidator"; var provider = new ValidatorProvider(ServiceProviderMock.Object, LoggerMock.Object); var ex = Assert.Throws <ArgumentException>(() => provider.GetValidator(validatorName)); Assert.Contains(validatorName, ex.Message); }
protected virtual void BindValidatorProvider(IModuleContext context, IIocContainer container) { IValidatorProvider validatorProvider = new ValidatorProvider(); validatorProvider.Register(typeof(ValidatableViewModelValidator)); validatorProvider.Register(typeof(DataAnnotationValidatior)); ServiceProvider.ValidatorProvider = validatorProvider; container.BindToConstant(validatorProvider); }
private void CreateValidator <T>(ICodeStep <T> result, XElement stepElement) where T : ILessonValidationObject { var provider = new ValidatorProvider <T>(); var validationKey = stepElement.GetChildElementStringValue(LessonXmlElements.ValidationKeyElement); var validationNamespace = stepElement.Parent.Parent.GetChildElementStringValue(LessonXmlElements.ValidatorsNamespaceElement); result.Validator = provider.CreateValidator(validationKey, validationNamespace); }
public void GetValidators_Simple_Inheritance() { var provider = new ValidatorProvider(); provider.AddTypeValidator(typeof(object), typeof(FakeValidator)); var result = provider.GetValidators(typeof(ValidatorProviderTest)); Assert.Equal(typeof(FakeValidator), result.Single()); }
public void GetValidators_Generic_IntEnumerable(Type targetType) { var provider = new ValidatorProvider(); provider.AddTypeValidator(typeof(IEnumerable <>), typeof(EnumerableValidator <>)); var result = provider.GetValidators(targetType); Assert.Equal(typeof(EnumerableValidator <int>), result.Single()); }
public void GetValidationMessageIfInvalidInputProvided_StartTimeInFuture_ReturnsNull() { CustomTask customTask = new CustomTask(); customTask.Id = 1; customTask.CreationTime = Convert.ToDateTime("2040-12-10T00:00:00"); TaskValidationMessage validationMessageBeforeNameSet = ValidatorProvider.GetValidationMessageIfInvalidInputProvided(customTask); Assert.NotNull(validationMessageBeforeNameSet); }
public async Task DoesNotBackUpThePackageWhenThereAreNoValidators() { const string validation1 = "validation1"; Configuration.Validations = new List <ValidationConfigurationItem> { new ValidationConfigurationItem() { Name = validation1, TrackAfter = TimeSpan.FromDays(1), RequiredValidations = new List <string> { } } }; ValidatorProvider .Setup(x => x.IsNuGetProcessor(validation1)) .Returns(false); Guid validationTrackingId = Guid.NewGuid(); ValidationStorageMock .Setup(vs => vs.GetValidationSetAsync(validationTrackingId)) .ReturnsAsync((PackageValidationSet)null) .Verifiable(); ValidationStorageMock .Setup(vs => vs.OtherRecentValidationSetForPackageExists(It.IsAny <IValidatingEntity <Package> >(), It.IsAny <TimeSpan>(), validationTrackingId)) .ReturnsAsync(false); PackageValidationSet createdSet = null; ValidationStorageMock .Setup(vs => vs.CreateValidationSetAsync(It.IsAny <PackageValidationSet>())) .Returns <PackageValidationSet>(pvs => Task.FromResult(pvs)) .Callback <PackageValidationSet>(pvs => createdSet = pvs) .Verifiable(); ValidationStorageMock .Setup(vs => vs.GetValidationSetCountAsync(It.IsAny <IValidatingEntity <Package> >())) .ReturnsAsync(1); var provider = CreateProvider(); var packageValidationMessageData = new ProcessValidationSetData( Package.PackageRegistration.Id, Package.NormalizedVersion, validationTrackingId, ValidatingType.Package, Package.Key); var actual = await provider.TryGetOrCreateValidationSetAsync(packageValidationMessageData, PackageValidatingEntity); PackageFileServiceMock.Verify( x => x.BackupPackageFileFromValidationSetPackageAsync(It.IsAny <PackageValidationSet>()), Times.Never); }
public void GetValidationMessageInInvalidInputProvider_NullName_ReturnsNotNull() { CustomTask customTask = new CustomTask(); customTask.Id = 1; customTask.Description = "Description"; TaskValidationMessage validationMessageBeforeNameSet = ValidatorProvider.GetValidationMessageIfInvalidInputProvided(customTask); Assert.NotNull(validationMessageBeforeNameSet); }
public async Task <IHttpActionResult> UploadEditorImageAsync() { object data = null; string tempDir = HttpContext.Current.Server.MapPath("~/temp"); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } string dateStr = DateTime.Now.ToString("yyyy-MM-dd"); string dstDir = HttpContext.Current.Server.MapPath("~/upload/file/editor/image/") + dateStr + "/"; if (!Directory.Exists(dstDir)) { Directory.CreateDirectory(dstDir); } var fileProvider = new MultipartFormDataStreamProvider(tempDir); var multipart = await Request.Content.ReadAsMultipartAsync(fileProvider); try { ValidatorProvider.ThrowIfEqual(multipart.FileData.Count, 0, "请选择上传的文件"); var fileData = multipart.FileData[0]; var fileName = fileData.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\"", ""); var ext = Path.GetExtension(fileName).ToLower(); string[] picExts = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" }; ValidatorProvider.ThrowIfNotIn(ext, picExts, "上传的图片格式不正确"); var fi = new FileInfo(fileData.LocalFileName); ValidatorProvider.ThrowIfMoreThan((int)fi.Length, 5 * 1024 * 1024, "上传的图片不能大于5M"); string file = Guid.NewGuid().ToString("N") + ext; File.Move(fileData.LocalFileName, Path.Combine(dstDir, file)); var uri = Request.RequestUri; data = new { url = $"/upload/file/editor/image/{dateStr}/{file}", fullurl = $"{WebConfigs.UrlPrefix}upload/file/editor/image/{dateStr}/{file}" }; } catch (Exception e) { throw e; } finally { Request.RemoveTempFile(multipart.FileData); } return(Json(JsonApiResult.Ok(data))); }
public void GetValidators_Both_IntEnumerable(Type targetType) { var provider = new ValidatorProvider(); provider.AddTypeValidator(typeof(IEnumerable <>), typeof(EnumerableValidator <>)); provider.AddTypeValidator(typeof(IEnumerable <int>), typeof(EnumerableValidator <int>)); var result = provider.GetValidators(targetType).ToList(); Assert.Equal(2, result.Count); Assert.Equal(typeof(EnumerableValidator <int>), result.First()); Assert.Equal(typeof(EnumerableValidator <int>), result.Last()); }
public void Validate_Valid() { ValidatorProvider p = new ValidatorProvider(); this.GetMessages(Data.Checkout.OrderPlaced_Valid).ForEach(m => { ValidatorResult result = p.Validate(m); m.EventId.ShouldEqual(28); result.ShouldNotBeNull(); result.IsValid.ShouldBeTrue(); result.Messages.Any().ShouldBeFalse(); }); }
public void Validate_Invalid() { ValidatorProvider p = new ValidatorProvider(); this.GetMessages(Data.Cart.PrintCart_Invalid).ForEach(m => { ValidatorResult result = p.Validate(m); m.EventId.ShouldEqual(25); result.ShouldNotBeNull(); result.IsValid.ShouldBeFalse(); result.Messages.Any().ShouldBeTrue(); }); }
protected virtual void OnModelUpdated(BindingContext context) { IEnumerable <ModelValidator> validators = ValidatorProvider.GetValidators(context.ModelType); ModelValidationContext inner = new ModelValidationContext(context.ModelName, context.Model); foreach (ModelValidator validator in validators) { foreach (ValidationError error in validator.Validate(inner)) { context.ModelState.Add(error.Key, error); } } }
public void VmShouldAddValidatorsForEntity() { var entity = new object(); StateManager.CreateSnapshot = o => new EntitySnapshotMock(); var viewModel = GetViewModel <TestEditableViewModel>(); ValidatorProvider.Register <SpyValidator>(); viewModel.InitializeEntity(entity, true); var validator = (SpyValidator)viewModel.GetValidators().Single(v => v.Context.Instance == entity); validator.Context.Instance.ShouldEqual(entity); }
public void Validate_Valid() { ValidatorProvider p = new ValidatorProvider(); this.GetMessages(Data.Pdp.ViewProductPdf_Valid).ForEach(m => { ValidatorResult result = p.Validate(m); m.EventId.ShouldEqual(12); result.ShouldNotBeNull(); result.IsValid.ShouldBeTrue(); result.Messages.Any().ShouldBeFalse(); }); }
public static IServiceCollection AddValidation(this IServiceCollection services) { services.AddSingleton <ValidationModelBuilder>(); services.AddScoped <IValidationProvider, ValidationProvider>(); services.AddScoped(typeof(RequiredValidator <>)); var provider = new ValidatorProvider(); provider.AddTypeValidator(typeof(IEnumerable <>), typeof(EnumerableValidator <>)); services.AddSingleton <IValidatorProvider>(provider); return(services); }
public void SmokeTest() { ServiceProviderMock .Setup(sp => sp.GetService(typeof(TestValidator1))) .Returns(() => new TestValidator1()); var provider = new ValidatorProvider(ServiceProviderMock.Object, LoggerMock.Object); var result = provider.GetValidator(nameof(TestValidator1)); ServiceProviderMock .Verify(sp => sp.GetService(typeof(TestValidator1)), Times.Once()); Assert.IsType <TestValidator1>(result); }
public async Task <ActionResult <CustomTask> > PostCustomTask(CustomTask customTask) { TaskValidationMessage validationMessage = ValidatorProvider.GetValidationMessageIfInvalidInputProvided(customTask); if (validationMessage != null) { return(StatusCode(422, validationMessage.Message)); } _context.Tasks.Add(customTask); await _context.SaveChangesAsync(); return(CreatedAtAction("GetCustomTask", new { id = customTask.Id }, customTask)); }
public void GetValidationMessageIfInvalidInputProvided_CorrectInput_ReturnsNull() { CustomTask customTask = new CustomTask(); customTask.Id = 1; customTask.Name = "Name"; customTask.Description = "Some description"; customTask.CreationTime = Convert.ToDateTime("2012-12-10T00:00:00"); customTask.FinishedTime = Convert.ToDateTime("2014-12-10T00:00:00"); TaskValidationMessage validationMessage = ValidatorProvider.GetValidationMessageIfInvalidInputProvided(customTask); Assert.Null(validationMessage); }
public async Task <IHttpActionResult> AddCaseAsync(CaseInfo json) { if (json == null) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } ValidatorProvider.ThrowIfInValidate <CaseInfoValidator, CaseInfo>(json); int count = await this.m_CaseInfoStorage.InsertAsync(json); if (count <= 0) { throw new BadRequestException(ResultCode.ActionFail, "添加失败"); } return(Json(JsonApiResult.Ok(""))); }
/// <summary> /// 对model进行验证 /// </summary> /// <param name="model"></param> /// <returns></returns> public override bool TryValidateModel(object model) { try { if (!this.ModelState.IsValid) { return(this.ModelState.IsValid); } if (model == null) { return(base.TryValidateModel(model)); } var modelType = model.GetType(); var validator = ValidatorProvider.GetValidator(modelType); if (validator == null) { return(base.TryValidateModel(model)); } var modelValidator = new ValidationModelValidator(validator); var array = modelValidator.ValidateModel(model); if (array.IsNullOrEmpty()) { return(base.TryValidateModel(model)); } if (array.Any()) { foreach (var a in array) { this.ModelState.AddModelError(a.MemberName, a.Message); } return(false); } return(base.TryValidateModel(model)); } catch { } return(base.TryValidateModel(model)); }
public async Task <IHttpActionResult> AddArticleAsync(Article json) { if (json == null) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } ValidatorProvider.ThrowIfInValidate <ArticleValidator, Article>(json); json.created = json.created.ToLocalTime(); int count = await this.m_ArticleStorage.InsertAsync(json); if (count <= 0) { throw new BadRequestException(ResultCode.ActionFail, "添加失败"); } return(Json(JsonApiResult.Ok(""))); }
public async Task <IHttpActionResult> AddCommenttAsync(Comment json) { if (json == null) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //获取ip地址 json.ipaddress = Request.GetUserHostAddress(); ValidatorProvider.ThrowIfInValidate <CommentValidator, Comment>(json); int count = await this.m_CommentStorage.InsertAsync(json); if (count <= 0) { throw new BadRequestException(ResultCode.ActionFail, "添加失败"); } return(Json(JsonApiResult.Ok(""))); }
public void CachesEvaluatedTypes() { var messages = new ConcurrentBag <string>(); var serviceProvider = new Mock <IServiceProvider>(); var loggerFactory = new LoggerFactory().AddXunit(_output); var innerLogger = loggerFactory.CreateLogger <ValidatorProvider>(); var logger = new RecordingLogger <ValidatorProvider>(innerLogger); _output.WriteLine("Initializing the first instance."); var targetA = new ValidatorProvider(serviceProvider.Object, logger); var messageCountA = logger.Messages.Count; _output.WriteLine("Initializing the second instance."); var targetB = new ValidatorProvider(serviceProvider.Object, logger); var messageCountB = logger.Messages.Count; Assert.Equal(messageCountA, messageCountB); }
/// <summary> /// 对model进行验证 /// </summary> /// <param name="model"></param> /// <returns></returns> public new bool TryValidateModel(object model) { if (!this.ModelState.IsValid) { return(this.ModelState.IsValid); } if (model == null) { return(base.TryValidateModel(model)); } var modelType = model.GetType(); var validator = ValidatorProvider.GetValidator(modelType); if (validator == null) { return(base.TryValidateModel(model)); } var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType); var modelValidator = new ValidationModelValidator(metadata, this.ControllerContext, validator); var array = modelValidator.ValidateModel(model); if (array.IsNullOrEmpty()) { return(base.TryValidateModel(model)); } if (array.Any()) { foreach (var a in array) { this.ModelState.AddModelError(a.MemberName, a.Message); } return(false); } return(base.TryValidateModel(model)); }
/// <summary> /// 对model进行验证 /// </summary> /// <param name="model"></param> /// <returns></returns> public bool TryValidateModel(object model) { if (!this.ModelState.IsValid) { return(this.ModelState.IsValid); } if (model == null) { this.ModelState.AddModelError("parameter", new ArgumentNullException()); return(this.ModelState.IsValid); } var modelType = model.GetType(); var validator = ValidatorProvider.GetValidator(modelType); if (validator == null) { return(this.ModelState.IsValid); } var modelValidator = new ValidationModelValidator(new System.Web.Http.Validation.ModelValidatorProvider[0], validator); var array = modelValidator.ValidateModel(model); if (array.IsNullOrEmpty()) { return(this.ModelState.IsValid); } if (array.Any()) { foreach (var a in array) { this.ModelState.AddModelError(a.MemberName, a.Message); } return(false); } return(this.ModelState.IsValid); }