public void SetupValidationRules(ModelValidator <ReviewSearchModel> v) { v.RuleFor(x => x.Page).GreaterThan(0); v.RuleFor(x => x.Count).GreaterThan(0); }
protected virtual void SetProperty(HttpActionContext actionContext, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult, ModelValidator requiredValidator) { PropertyDescriptor propertyDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType).GetProperties().Find(propertyMetadata.PropertyName, true /* ignoreCase */); if (propertyDescriptor == null || propertyDescriptor.IsReadOnly) { return; // nothing to do } object value = dtoResult.Model ?? GetPropertyDefaultValue(propertyDescriptor); propertyMetadata.Model = value; // 'Required' validators need to run first so that we can provide useful error messages if // the property setters throw, e.g. if we're setting entity keys to null. See comments in // DefaultModelBinder.SetProperty() for more information. if (value == null) { string modelStateKey = dtoResult.ValidationNode.ModelStateKey; if (bindingContext.ModelState.IsValidField(modelStateKey)) { if (requiredValidator != null) { foreach (ModelValidationResult validationResult in requiredValidator.Validate(propertyMetadata, bindingContext.Model)) { bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message); } } } } if (value != null || TypeHelper.TypeAllowsNullValue(propertyDescriptor.PropertyType)) { try { propertyDescriptor.SetValue(bindingContext.Model, value); } catch (Exception ex) { // don't display a duplicate error message if a binding error has already occurred for this field string modelStateKey = dtoResult.ValidationNode.ModelStateKey; if (bindingContext.ModelState.IsValidField(modelStateKey)) { bindingContext.ModelState.AddModelError(modelStateKey, ex); } } } else { // trying to set a non-nullable value type to null, need to make sure there's a message string modelStateKey = dtoResult.ValidationNode.ModelStateKey; if (bindingContext.ModelState.IsValidField(modelStateKey)) { dtoResult.ValidationNode.Validated += CreateNullCheckFailedHandler(propertyMetadata, value); } } }
public void Validate(ICollection <ValidationError> errors) => ModelValidator.ValidateObject(this, errors, nameof(JobViewModel.Job));
public async Task <object> AddGR(oGoodsReceipt goodsReceipt) { try { if (goodsReceipt == null) { return new { SAPGRDocumentNumber = -1, ReturnMessage = $"Object cannot be null!!" } } ;; oGoodsReceipt _grpo = null; string isOldItem = goodsReceipt.GoodsReceiptLines.Select(x => x.IsOldItem).First(); if (isOldItem == null) { errMsg = string.Format("Item classification cannot be null. (Is Old Item)", goodsReceipt.BatchNumber); var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "Field cannot be null"; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogGoodsReceiptTransaction(goodsReceipt, false, "A", HttpContext.Current.Request.UserHostAddress, _err); throw new HttpResponseException(resp); } goodsReceipt.BatchNumber = isOldItem.ToUpper() == "Y" ? $"R-{goodsReceipt.BatchNumber}" : $"N-{goodsReceipt.BatchNumber}"; if (goodsReceipt.GoodsReceiptLines.Count > 0) { foreach (var l in goodsReceipt.GoodsReceiptLines) { if (l.IsOldItem.ToLower() == "y") { if (l.WarehouseCode == "" || string.IsNullOrEmpty(l.WarehouseCode)) { l.WarehouseCode = ConfigurationManager.AppSettings["DefaultRemaWarehouse"]; l.BinCode = Int32.Parse(ConfigurationManager.AppSettings["DefaultRemaBin"]); } } } } if (!GlobalInstance.Instance.IsConnected) { GlobalInstance.Instance.InitializeSboComObject(); } if (goodsReceipt.BatchNumber != null) { _grpo = await repo.GetByBatchNo(goodsReceipt.BatchNumber); } string validationStr = ModelValidator.ValidateModel(goodsReceipt); if (!string.IsNullOrEmpty(validationStr)) { errMsg = string.Format(validationStr); var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "Object property validation error"; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogGoodsReceiptTransaction(goodsReceipt, false, "A", HttpContext.Current.Request.UserHostAddress, _err); throw new HttpResponseException(resp); } if (_grpo != null) { errMsg = string.Format("Goods Receipt {0} already exist.", goodsReceipt.BatchNumber); var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "Object already exist."; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogGoodsReceiptTransaction(goodsReceipt, false, "A", HttpContext.Current.Request.UserHostAddress, _err); throw new HttpResponseException(resp); } if (repo.Add(goodsReceipt) != 0) { errMsg = GlobalInstance.Instance.SBOErrorMessage; var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "SBO Error"; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogGoodsReceiptTransaction(goodsReceipt, false, "A", HttpContext.Current.Request.UserHostAddress, _err); throw new HttpResponseException(resp); } transactionLogger.LogGoodsReceiptTransaction(goodsReceipt, true, "A", HttpContext.Current.Request.UserHostAddress); var grpo = await repo.GetByBatchNo(goodsReceipt.BatchNumber); return(new { SAPGRDocumentNumber = grpo.DocNo, ReturnMessage = $"Goods receipt {goodsReceipt.BatchNumber} successfully added." }); } catch (HttpResponseException ex) { throw new HttpResponseException(ex.Response); } }
public void SetupValidationRules(ModelValidator <UploadPackageModel> v) { v.RuleFor(x => x.MediaFile).NotNull(); }
public void Validate_WithNullValidators_ShouldBeTrue() { var factory = new Mock<IValidatorFactory>(); factory.Setup(x => x.Create(It.IsAny<Customer>(), It.IsAny<string>())).Returns((IValidator<Customer>[])null); var sut = new ModelValidator(factory.Object); var result = sut.Validate(new Customer()); result.ShouldNotBeNull(); result.IsValid.ShouldBeTrue(); }
public virtual void SetPropertyPublic(HttpActionContext context, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult, ModelValidator requiredValidator) { base.SetProperty(context, bindingContext, propertyMetadata, dtoResult, requiredValidator); }
private async Task SendTicketByMailAsync(TicketDeliveryData args, string ticketValidationUriFormat, string homepageUrl) { if (args.MailSettings == null) { throw new EventManagementException( "The mail settings haven't been configured for the event."); } ModelValidator.Validate(args.MailSettings); if (string.IsNullOrEmpty(args.Ticket.Mail)) { await LogAuditEvent(args, false, "Ticket konnte nicht versendet werden, weil keine E-Mail-Adresse vorhanden ist."); throw new EventManagementException("The ticket has no email address."); } System.IO.Stream stream = await _pdfTicketService .GeneratePdfAsync(args.Ticket.Id, ticketValidationUriFormat); IList <string> recipients = new[] { args.Ticket.Mail }; if (args.MailSettings.EnableDemoMode) { if (args.MailSettings.DemoEmailRecipients.Any()) { _logger.LogWarning("Demo Mode is enabled. The e-mails will be sent to a predefined list of recipients only."); recipients = args.MailSettings.DemoEmailRecipients .Select(r => r.EmailAddress) .ToList(); } else { _logger.LogWarning("Demo Mode is enabled, but no test recipients are defined."); } } var message = new EmailMessage { From = { args.MailSettings.SenderAddress }, To = recipients, Subject = args.MailSettings.Subject, Body = args.MailSettings.Body, Attachments = { new EmailAttachment { FileName = $"ticket-{args.Ticket.TicketNumber}.pdf", ContentType = "application/pdf", Stream = stream } } }; if (!string.IsNullOrEmpty(args.MailSettings.ReplyToAddress)) { message.ReplyTo.Add(args.MailSettings.ReplyToAddress); } var mail = await EmailTemplateService .RenderTicketMailAsync(message, args.Ticket, homepageUrl); try { await _emailService.SendMailAsync(args.MailSettings, mail); } catch { await LogAuditEvent(args, false); throw; } await _ticketDataRepo.UpdateDeliveryStatusAsync(args.Ticket.Id, true, DateTime.UtcNow, TicketDeliveryType.Email); await LogAuditEvent(args, true); }
public void SetupValidationRules(ModelValidator <ReviewModel> v) { v.RuleFor(x => x.Rating).GreaterThan(0).LessThan(6); }
public void SetupValidationRules(ModelValidator <EmailVerificationModel> v) { v.RuleFor(x => x.Code).NotEmpty(); v.RuleFor(x => x.Email).EmailAddress().NotEmpty(); }
public void SetupValidationRules(ModelValidator <UserSearchModel> v) { v.RuleFor(x => x.RowCount).GreaterThanOrEqualTo(1).LessThanOrEqualTo(100); v.RuleFor(x => x.Current).GreaterThanOrEqualTo(1); }
public void SetupValidationRules(ModelValidator <UploadFileModel> v) { v.RuleFor(x => x.MediaFile).NotNull().Must(x => x.Length != 0); v.RuleFor(x => x.ProductId).GreaterThan(0); }
public void Validate_WithRuleNameAndContext_ShouldBeValid() { var validator = new Mock<IValidator<Customer>>(); validator.Setup(x => x.Validate(It.IsAny<Customer>(), It.Is<object>(o => true))).Returns(new ValidationResult()); var factory = new Mock<IValidatorFactory>(); factory.Setup(x => x.Create(It.IsAny<Customer>(), It.IsAny<string>())).Returns(new IValidator<Customer>[] { validator.Object }); var sut = new ModelValidator(factory.Object); var result = sut.Validate(new Customer(), "rulename", new { }); result.IsValid.ShouldBe(true); }
public void Validate_With_ShouldBeFalse() { var validator = new Mock<IValidator<Customer>>(); validator.Setup(x => x.Validate(It.IsAny<Customer>())).Returns(new ValidationResult(new [] {new ValidationFailure(""), })); var factory = new Mock<IValidatorFactory>(); factory.Setup(x => x.Create(It.IsAny<Customer>(), It.IsAny<string>())).Returns(new IValidator<Customer>[] { validator.Object }); var sut = new ModelValidator(factory.Object); var result = sut.Validate(new Customer()); result.IsValid.ShouldBeFalse(); result.Errors.Count.ShouldBe(1); }
public void SetupValidationRules(ModelValidator <OrderDownloadModel> v) { v.RuleFor(x => x.DownloadId).GreaterThan(0); }
public void Test_TrasferReq_ValidModel() { Assert.True(ModelValidator.IsValid(BASE_MODEL)); }
public void GetValidatorsDelegatesToResolver() { // Arrange ModelValidator[] allValidators = new ModelValidator[] { new SimpleModelValidator(), new SimpleModelValidator(), new SimpleModelValidator(), new SimpleModelValidator() }; ModelMetadata metadata = GetMetadata(); ControllerContext controllerContext = new ControllerContext(); Mock<ModelValidatorProvider> resolverProvider1 = new Mock<ModelValidatorProvider>(); resolverProvider1.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[] { allValidators[0], allValidators[1] }); Mock<ModelValidatorProvider> resolverprovider2 = new Mock<ModelValidatorProvider>(); resolverprovider2.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[] { allValidators[2], allValidators[3] }); Resolver<IEnumerable<ModelValidatorProvider>> resolver = new Resolver<IEnumerable<ModelValidatorProvider>>(); resolver.Current = new ModelValidatorProvider[] { resolverProvider1.Object, resolverprovider2.Object }; ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection(resolver); // Act IEnumerable<ModelValidator> returnedValidators = collection.GetValidators(metadata, controllerContext); // Assert Assert.Equal(allValidators, returnedValidators.ToArray()); }
private static IEnumerable <ValidationResult> GetErrosFromModel(object model) { ModelValidator.TryValidate(model, out IEnumerable <ValidationResult> errors); return(errors); }
public async Task <List <object> > AddMultipleJournals(List <oJournal> jrnals) { HttpResponseMessage _resp = new HttpResponseMessage(); List <object> retList = new List <object>(); try { if (!GlobalInstance.Instance.IsConnected) { GlobalInstance.Instance.InitializeSboComObject(); } oJournal j = null; foreach (oJournal jrnal in jrnals) { j = await repo.GetByRDTransId(jrnal.TransactionId); string validationStr = ModelValidator.ValidateModel(jrnal); if (!string.IsNullOrEmpty(validationStr)) { errMsg = string.Format(validationStr); var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "Object property validation error"; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogJournalTransaction(jrnal, false, "A", HttpContext.Current.Request.UserHostAddress, _err); _resp = resp; throw new HttpResponseException(resp); } if (j != null) { errMsg = string.Format("Journal {0} already exist.", jrnal.TransactionId); var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "Object already exist."; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogJournalTransaction(jrnal, false, "A", HttpContext.Current.Request.UserHostAddress, _err); _resp = resp; throw new HttpResponseException(resp); } if (repo.Add(jrnal) != 0) { errMsg = GlobalInstance.Instance.SBOErrorMessage; var resp = new HttpResponseMessage(HttpStatusCode.Conflict); resp.Content = new StringContent(errMsg); resp.ReasonPhrase = "SBO Error"; ErrorLog _err = new ErrorLog(); _err.ErrorCode = (int)HttpStatusCode.Conflict; _err.Message = errMsg; _err.StackTrace = Environment.StackTrace; var err = ErrorLogger.Log(_err); transactionLogger.LogJournalTransaction(jrnal, false, "A", HttpContext.Current.Request.UserHostAddress, _err); _resp = resp; throw new HttpResponseException(resp); } transactionLogger.LogJournalTransaction(jrnal, true, "A", HttpContext.Current.Request.UserHostAddress); var _j = await repo.GetByRDTransId(jrnal.TransactionId); retList.Add(new { SAPTransactionId = _j.TransId, ReturnMessage = $"Journal {jrnal.TransactionId} successfully added." }); } return(retList); } catch (HttpResponseException ex) { throw new HttpResponseException(ex.Response); } }
public void SetupValidationRules(ModelValidator <WidgetModel> v) { v.RuleFor(x => x.ZoneName).NotEmpty(); v.RuleFor(x => x.WidgetSystemName).NotEmpty(); v.RuleFor(x => x.PluginSystemName).NotEmpty(); }
protected override void SetProperty(HttpActionContext actionContext, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult, ModelValidator requiredValidator) { SetPropertyPublic(actionContext, bindingContext, propertyMetadata, dtoResult, requiredValidator); }
public void SetupValidationRules(ModelValidator <DiscountModel> v) { v.RuleFor(x => x.Name).NotEmpty(); }
public void Validate(ICollection <ValidationError> errors) { ModelValidator.ValidateObject(this, errors, nameof(TriggerViewModel.Trigger), nameof(TriggerPropertiesViewModel.Cron)); }
public void SetupValidationRules(ModelValidator <AffiliateSettingsModel> v) { v.RuleFor(x => x.AffiliateCookieName).NotEmpty().When(x => x.EnableAffiliates); }
public void SetupValidationRules(ModelValidator <PluginsSearchModel> v) { v.RuleFor(x => x.Current).GreaterThan(0); v.RuleFor(x => x.RowCount).LessThanOrEqualTo(30).GreaterThanOrEqualTo(0); }
public void SetupValidationRules(ModelValidator <GenerateInvitationLinkModel> v) { v.RuleFor(x => x.Email).EmailAddress(); }
public void Validate(ICollection <ValidationError> errors) => ModelValidator.ValidateObject(this, errors);
public void SetupValidationRules(ModelValidator <MediaUploadModel> v) { v.RuleFor(x => x.MediaFile).NotNull().Must(x => x.Length != 0); }
public static IServiceCollection AddJobsDependencies(this IServiceCollection services, IConfiguration configuration) { var hangFireConfig = configuration.Get <HangfireConfig>(); ModelValidator.ValidateContract(hangFireConfig); int DelayInSecondsByAttemptFunc(long attempt) => hangFireConfig.JobsRetryInterval; GlobalJobFilters.Filters.Add( new AutomaticRetryAttribute { Attempts = hangFireConfig.JobsMaxRetryAttempts, DelayInSecondsByAttemptFunc = DelayInSecondsByAttemptFunc }); var gateWayConfig = hangFireConfig.EuGateway; var eventLogConfig = hangFireConfig.Logging.EventLog; services.Configure <EventLogSettings>(config => { config.SourceName = eventLogConfig.SourceName; config.LogName = eventLogConfig.LogName; config.MachineName = eventLogConfig.MachineName; }); services.AddSingleton(gateWayConfig); services.AddSingleton(hangFireConfig.Jobs.UploadKeysToTheGateway); services.AddSingleton(hangFireConfig.Jobs.DownloadKeysFromTheGateway); services.AddSingleton(hangFireConfig.Jobs.GetCovidStatistics); services.AddHangfire(x => x.UseSqlServerStorage(hangFireConfig.HangFireConnectionString)); services.AddDbContext <DigNDB_SmittestopContext>(opts => opts.UseSqlServer(hangFireConfig.SmittestopConnectionString)); services.AddControllers().AddControllersAsServices(); services.AddLogging(); services.AddAutoMapper(Assembly.GetExecutingAssembly()); services.AddAutoMapper(typeof(CountryMapper)); services.AddScoped <IDatabaseKeysValidationService, DatabaseKeysValidationService>(); services.AddScoped <IZipFileService, ZipFileService>(); services.AddScoped <ISettingsService, SettingsService>(); services.AddSingleton(hangFireConfig); services.AddSingleton <IOriginSpecificSettings>(hangFireConfig); services.AddSingleton <IZipPackageBuilderConfig>(hangFireConfig); services.AddScoped <IZipFileService, ZipFileService>(); services.AddScoped <IGatewayHttpClient, GatewayHttpClient>(); services.AddScoped <ITemporaryExposureKeyRepository, TemporaryExposureKeyRepository>(); services.AddScoped <ISignatureService, SignatureService>(); services.AddScoped <IEncodingService, EncodingService>(); services.AddScoped <IGatewayWebContextReader, GatewayWebContextReader>(); services.AddScoped <IEpochConverter, EpochConverter>(); services.AddScoped <IEFGSKeyStoreService, EFGSKeyStoreService>(); services.AddScoped <IGatewayKeyProvider, GatewayKeyProvider>(); services.AddScoped <IRiskCalculator, RiskCalculator>(); services.AddScoped <IDaysSinceOnsetOfSymptomsDecoder, DaysSinceOnsetOfSymptomsDecoder>(); services.AddScoped <IKeyFilter, KeyFilter>(); services.AddScoped <IGatewaySyncStateSettingsDao, GatewaySyncStateSettingsDao>(); services.AddScoped <IEuGatewayService, EuGatewayService>(); services.AddScoped <IAddTemporaryExposureKeyService, AddTemporaryExposureKeyService>(); services.AddScoped <IFetchCovidStatisticsService, FetchCovidStatisticsService>(); services.AddScoped <ICovidStatisticsFilePackageBuilder, CovidStatisticsFilePackageBuilder>(); services.AddScoped <IDateTimeResolver, DateTimeResolver>(); services.AddScoped <ICovidStatisticsDataExtractingService, CovidStatisticsDataExtractingService>(); services.AddScoped <ICovidStatisticsCsvParser, CovidStatisticsCsvParser>(); services.AddScoped <ICovidStatisticsBuilder, CovidStatisticsBuilder>(); services.AddScoped <ICovidStatisticsRetrieveService, CovidStatisticsRetrieveService>(); services.AddScoped <ICovidStatisticsCsvDataRetrieveService, CovidStatisticsCsvDataRetrieveService>(); services.AddSingleton <IGatewayKeyProvider>( new GatewayKeyProvider(gateWayConfig.AuthenticationCertificateFingerprint, gateWayConfig.SigningCertificateFingerprint)); return(services); }
public void SetupValidationRules(ModelValidator <UserModel> v) { v.RuleFor(x => x.Email).NotEmpty().EmailAddress(); v.RuleFor(x => x.FirstName).NotEmpty(); v.RuleFor(x => x.LastName).NotEmpty(); }
public void SetupValidationRules(ModelValidator <VendorModel> v) { v.RuleFor(x => x.Name).NotEmpty(); v.RuleFor(x => x.Address).NotEmpty(); }
public void ValidCardInfoPasses() { var errors = ModelValidator.ValidateObject(new ExampleModel1()).Errors; Assert.That(errors.Count, Is.EqualTo(0)); }
protected virtual void ValidateModel() { ModelValidator?.Validate(ModelState); }
/// <summary> /// Validates the context against the <see cref="ValidationAttribute"/>. /// </summary> /// <param name="validationContext">The context being validated.</param> /// <returns>An enumerable of the validation results.</returns> public IEnumerable <ModelValidationResult> Validate(ModelValidationContext validationContext) { return(ModelValidator.Validate(validationContext, validator, validationAttribute)); }
public void GetValidators() { // Arrange ModelMetadata metadata = GetMetadata(); ControllerContext controllerContext = new ControllerContext(); ModelValidator[] allValidators = new ModelValidator[] { new SimpleModelValidator(), new SimpleModelValidator(), new SimpleModelValidator(), new SimpleModelValidator(), new SimpleModelValidator() }; Mock<ModelValidatorProvider> provider1 = new Mock<ModelValidatorProvider>(); provider1.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[] { allValidators[0], allValidators[1] }); Mock<ModelValidatorProvider> provider2 = new Mock<ModelValidatorProvider>(); provider2.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[] { allValidators[2], allValidators[3], allValidators[4] }); ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection(); collection.Add(provider1.Object); collection.Add(provider2.Object); // Act IEnumerable<ModelValidator> returnedValidators = collection.GetValidators(metadata, controllerContext); // Assert Assert.Equal(allValidators, returnedValidators.ToArray()); }
public void Validate_WithNoValidators_ShouldBeTrue() { var factory = new Mock<IValidatorFactory>(); factory.Setup(x => x.Create(It.IsAny<Customer>(), It.IsAny<string>())).Throws<Exception>(); var sut = new ModelValidator(factory.Object); Should.Throw<Exception>(() => { var result = sut.Validate(new Customer()); }); }