Пример #1
0
        public void CreatingInstanceWithNegated()
        {
            NotNullValidator validator = new NotNullValidator(true);

            Assert.AreEqual(Resources.NonNullNegatedValidatorDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(true, validator.Negated);
        }
Пример #2
0
        public void SuppliesAppropriateParametersToMessageTemplate()
        {
            NotNullValidator validator = new NotNullValidator();

            validator.MessageTemplate = "{0}|{1}|{2}";
            validator.Tag             = "tag";
            object target = null;
            string key    = "key";

            ValidationResults validationResults = new ValidationResults();

            validator.DoValidate(target, null, key, validationResults);

            Assert.IsFalse(validationResults.IsValid);
            ValidationResult validationResult = ValidationTestHelper.GetResultsList(validationResults)[0];

            System.Text.RegularExpressions.Match match = TemplateStringTester.Match(validator.MessageTemplate, validationResult.Message);
            Assert.IsTrue(match.Success);
            Assert.IsTrue(match.Groups["param0"].Success);
            Assert.AreEqual("", match.Groups["param0"].Value);
            Assert.IsTrue(match.Groups["param1"].Success);
            Assert.AreEqual(key, match.Groups["param1"].Value);
            Assert.IsTrue(match.Groups["param2"].Success);
            Assert.AreEqual(validator.Tag, match.Groups["param2"].Value);
        }
        public List <IValidator> Compile()
        {
            List <IValidator> validators = new List <IValidator>();

            if (Required)
            {
                validators.Add(NotNullValidator.Create());
            }

            validators.Add(FieldTypeValidator);

            if (Min.HasValue)
            {
                validators.Add(MinValidator);
            }

            if (Max.HasValue)
            {
                validators.Add(MaxValidator);
            }

            AddRegexValidatorIfNeeded(validators);

            AddEnumValidatorIfNeeded(validators);

            AddObjectValidatorIfNeeded(validators);

            AddArrayValidatorIfNeeded(validators);

            AddPasswordValidatorIfNeeded(validators);

            AddTagsValidatorIfNeeded(validators);

            return(validators);
        }
Пример #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ErrorHandlingMiddleware" /> class.
 /// </summary>
 /// <param name="requestDelegate">Next middleware.</param>
 /// <param name="logger">Logger instance.</param>
 /// <param name="applicationSettings">Options accessor.</param>
 public ErrorHandlingMiddleware(RequestDelegate requestDelegate, ILogger <ErrorHandlingMiddleware> logger, IOptions <ApplicationSettings> applicationSettings)
 {
     NotNullValidator.ThrowIfNull(applicationSettings, nameof(applicationSettings));
     this.requestDelegate = requestDelegate;
     this.logger          = logger;
     this.includeExceptionDetailsInResponse = applicationSettings.Value.IncludeExceptionStackInResponse;
 }
Пример #5
0
        public void CreatingInstanceWithoutMessageTemplateUsesDefaultTemplate()
        {
            NotNullValidator validator = new NotNullValidator();

            Assert.AreEqual(Resources.NonNullNonNegatedValidatorDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
        }
Пример #6
0
        /// <inheritdoc/>
        public async Task <InvoiceDetailsViewModel> AddInvoiceAsync(InvoiceDetailsViewModel invoice)
        {
            NotNullValidator.ThrowIfNull(invoice, nameof(invoice));
            invoice.Id     = Guid.NewGuid().ToString();
            invoice.SoldBy = new SoldByViewModel()
            {
                Email      = "*****@*****.**",
                Phone      = "9876543210",
                SellerName = "Packt",
            };
            using var invoiceRequest = new StringContent(JsonSerializer.Serialize(invoice), Encoding.UTF8, ContentType);
            var invoiceResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.Value.DataStoreEndpoint}api/invoice"), invoiceRequest).ConfigureAwait(false);

            if (!invoiceResponse.IsSuccessStatusCode)
            {
                await this.ThrowServiceToServiceErrors(invoiceResponse).ConfigureAwait(false);
            }

            var createdInvoiceDAO = await invoiceResponse.Content.ReadFromJsonAsync <Packt.Ecommerce.Data.Models.Invoice>().ConfigureAwait(false);

            // Mapping
            var createdInvoice = this.autoMapper.Map <InvoiceDetailsViewModel>(createdInvoiceDAO);

            return(createdInvoice);
        }
Пример #7
0
        public void DefaultErrorMessage_NotNullValidator()
        {
            var validator = new NotNullValidator();

            Assert.That(validator.ErrorMessageSource, Is.TypeOf(typeof(LocalizedStringSource)));
            Assert.That(validator.ErrorMessageSource.GetString(), Is.EqualTo(Messages.notnull_error));
        }
Пример #8
0
        public IValidationResult CheckForNotNull(object obj, string propName)
        {
            if (MSNotNullValidator == null)
            {
                MSNotNullValidator = new NotNullValidator();
            }

            ValidationResults valResults = MSNotNullValidator.Validate(obj);

            if (valResults != null)
            {
                if (ValidationResult == null)
                {
                    ValidationResult = new MyValidationResult();
                }

                foreach (var varRes in valResults)
                {
                    IValidationMessage val = new MSWrapperMessage(MessageTypes.Error, varRes.Message)
                    {
                        TargetName = propName
                    };
                    ValidationResult.ValidationMessageList.Add(val);
                }
            }
            return(ValidationResult);
        }
Пример #9
0
        public void CreatingInstanceWithMessageTemplateUsesProvidedTemplateAndNnegated()
        {
            NotNullValidator validator = new NotNullValidator(true, "message template override");

            Assert.AreEqual("message template override", validator.MessageTemplate);
            Assert.AreEqual(true, validator.Negated);
        }
Пример #10
0
        public void SetUp()
        {
            _propertyValidator = new NotNullValidator();
            _validatorGlobalizationServiceMock = MockRepository.GenerateStrictMock <IErrorMessageGlobalizationService>();
            _orginalStringSourceMock           = MockRepository.GenerateStrictMock <IStringSource> ();

            _stringSource = new ErrorMessageStringSource(_propertyValidator, _validatorGlobalizationServiceMock, _orginalStringSourceMock);
        }
 public NotNullValidatorOperation(string keyToValidate, string resultKey, bool negated)
     : base(keyToValidate, resultKey)
 {
     Validator = new NotNullValidator(negated, string.Empty)
     {
         Tag = keyToValidate
     };
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ECommerceService"/> class.
        /// </summary>
        /// <param name="httpClientFactory">The HTTP client factory.</param>
        /// <param name="applicationSettings">The application settings.</param>
        public ECommerceService(IHttpClientFactory httpClientFactory, IOptions <ApplicationSettings> applicationSettings)
        {
            NotNullValidator.ThrowIfNull(applicationSettings, nameof(applicationSettings));
            IHttpClientFactory httpclientFactory = httpClientFactory;

            this.httpClient          = httpclientFactory.CreateClient();
            this.applicationSettings = applicationSettings.Value;
        }
        public override IValidator Build()
        {
            IValidator validator = new NotNullValidator();

            ConfigureValidatorMessage(validator);

            return validator;
        }
        public void Format_NotNullValidator()
        {
            var validator = new NotNullValidator();

            var result = _formatter.Format(validator, _typeNameFormatter);

            Assert.That(result, Is.EqualTo("NotNullValidator"));
        }
Пример #15
0
 public static NotNullValidator GetInstance()
 {
     if (uniqueInstance == null)
     {
         uniqueInstance = new NotNullValidator();
     }
     return(uniqueInstance);
 }
Пример #16
0
        public void NegatedValidatorReturnsSuccessForNullReference()
        {
            Validator validator = new NotNullValidator(true);

            ValidationResults validationResults = validator.Validate(null);

            Assert.IsTrue(validationResults.IsValid);
        }
        /// <inheritdoc/>
        public async Task <T> DeserializeEntityAsync <T>(byte[] entity, CancellationToken cancellationToken = default)
        {
            NotNullValidator.ThrowIfNull(entity, nameof(entity));

            using MemoryStream memoryStream = new MemoryStream(entity);
            var value = await JsonSerializer.DeserializeAsync <T>(memoryStream, cancellationToken : cancellationToken);

            return(value);
        }
		public void Should_validate_property_value_without_instance() {
			var validator = new NotNullValidator();
			var parentContext = new ValidationContext(null);
			var rule = new PropertyRule(null, x => null, null, null, typeof(string), null) {
				PropertyName = "Surname"
			};
			var context = new PropertyValidatorContext(parentContext, rule, null);
			var result = validator.Validate(context);
			result.Single().ShouldNotBeNull();
		}
Пример #19
0
        public void IsValidNotNullValue()
        {
            NotNullValidator notNullValidator = new NotNullValidator();

            Assert.IsTrue(notNullValidator.IsValid(new object()));

            const int value = 0;

            Assert.IsTrue(notNullValidator.IsValid(value));
        }
Пример #20
0
        public void isValidWithValue()
        {
            NotNullValidator val = new NotNullValidator();

            Expect.On(ictl).Call(ictl.getValue()).Return(
                "pepe"
                );
            rep.ReplayAll();
            Assert.IsTrue(val.isValid(ictl));
        }
Пример #21
0
        public void isValid()
        {
            NotNullValidator val = new NotNullValidator();

            ictl = rep.Stub <iControl>();
            Expect.On(ictl).Call(ictl.getValue()).Return(String.Empty);

            rep.ReplayAll();
            Assert.IsTrue(val.isValid(ictl));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductsService"/> class.
        /// </summary>
        /// <param name="httpClientFactory">The HTTP Client factory.</param>
        /// <param name="applicationSettings">The application settings.</param>
        /// <param name="autoMapper">The mapper.</param>
        /// <param name="cacheService">cache service.</param>
        public ProductsService(IHttpClientFactory httpClientFactory, IOptions <ApplicationSettings> applicationSettings, IMapper autoMapper, IDistributedCacheService cacheService)
        {
            NotNullValidator.ThrowIfNull(applicationSettings, nameof(applicationSettings));
            IHttpClientFactory httpclientFactory = httpClientFactory;

            this.applicationSettings = applicationSettings;
            this.httpClient          = httpclientFactory.CreateClient();
            this.autoMapper          = autoMapper;
            this.cacheService        = cacheService;
        }
        public void Should_create_notnulladapter_for_notnullvalidator()
        {
            // Given
            var validator = new NotNullValidator();

            // When
            var result = factory.Create(this.rule, validator);

            // Then
            result.ShouldBeOfType <NotNullAdapter>();
        }
Пример #24
0
 public void ValidateSuccess()
 {
     try
     {
         NotNullValidator.Validate <SourceEntity>(null, c => c.Name, "test");
     }
     catch (ApplicationException ex)
     {
         Assert.Contains("Name", ex.Message);
     }
 }
Пример #25
0
        public void NonNegatedValidatorReturnsFailureForNullReference()
        {
            Validator validator = new NotNullValidator();

            ValidationResults validationResults = validator.Validate(null);

            Assert.IsFalse(validationResults.IsValid);
            IList <ValidationResult> resultsList = ValidationTestHelper.GetResultsList(validationResults);

            Assert.AreEqual(1, resultsList.Count);
            Assert.AreEqual(Resources.NonNullNonNegatedValidatorDefaultMessageTemplate, resultsList[0].Message);
        }
        public void Should_validate_property_value_without_instance()
        {
            var validator     = new NotNullValidator();
            var parentContext = new ValidationContext <string>(null);
            var rule          = new PropertyRule(null, x => null, null, null, typeof(string), null)
            {
                PropertyName = "Surname"
            };
            var context = new PropertyValidatorContext(parentContext, rule, null);
            var result  = validator.Validate(context);

            result.Single().ShouldNotBeNull();
        }
        /// <inheritdoc/>
        public async Task <OrderDetailsViewModel> AddOrderAsync(OrderDetailsViewModel order)
        {
            NotNullValidator.ThrowIfNull(order, nameof(order));

            // Order entity is used for Shopping cart and at any point as there can only be one shopping cart, checking for existing shopping cart
            var getExistingOrder = await this.GetOrdersAsync($" e.UserId = '{order.UserId}' and e.OrderStatus = '{OrderStatus.Cart}' ").ConfigureAwait(false);

            OrderDetailsViewModel existingOrder = getExistingOrder.FirstOrDefault();

            if (existingOrder != null)
            {
                order.Id   = existingOrder.Id;
                order.Etag = existingOrder.Etag;
                if (order.OrderStatus == OrderStatus.Submitted.ToString())
                {
                    order.OrderPlacedDate = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
                    order.DeliveryDate    = DateTime.UtcNow.AddDays(5).ToString(CultureInfo.InvariantCulture);
                    Random trackingId = new Random();
                    order.TrackingId = trackingId.Next(int.MaxValue); // generating random tracking number
                }
                else
                {
                    order.Products.AddRange(existingOrder.Products); // For cart append products
                    order.OrderStatus = OrderStatus.Cart.ToString();
                }

                order.OrderTotal = order.Products.Sum(x => x.Price);
                await this.UpdateOrderAsync(order).ConfigureAwait(false);

                return(order);
            }
            else
            {
                order.OrderStatus      = OrderStatus.Cart.ToString();
                order.Id               = Guid.NewGuid().ToString();
                order.OrderTotal       = order.Products.Sum(x => x.Price);
                using var orderRequest = new StringContent(JsonSerializer.Serialize(order), Encoding.UTF8, ContentType);
                var orderResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.Value.DataStoreEndpoint}api/orders"), orderRequest).ConfigureAwait(false);

                if (!orderResponse.IsSuccessStatusCode)
                {
                    await this.ThrowServiceToServiceErrors(orderResponse).ConfigureAwait(false);
                }

                var createdOrderDAO = await orderResponse.Content.ReadFromJsonAsync <Packt.Ecommerce.Data.Models.Order>().ConfigureAwait(false);

                // Mapping
                var createdOrder = this.autoMapper.Map <OrderDetailsViewModel>(createdOrderDAO);
                return(createdOrder);
            }
        }
Пример #28
0
        public void IsValidNullValue()
        {
            NotNullValidator notNullValidator = new NotNullValidator();

            Assert.IsFalse(notNullValidator.IsValid(null));

            object value = null;

            Assert.IsFalse(notNullValidator.IsValid(value));

            int?id = null;

            Assert.IsFalse(notNullValidator.IsValid(id));
        }
Пример #29
0
        public void ReturnsFailureWithOverriddenMessageForNullReference()
        {
            string message = "overriden message";

            Validator validator = new NotNullValidator(message);

            ValidationResults validationResults = validator.Validate(null);

            Assert.IsFalse(validationResults.IsValid);
            IList <ValidationResult> resultsList = ValidationTestHelper.GetResultsList(validationResults);

            Assert.AreEqual(1, resultsList.Count);
            Assert.AreEqual(message, resultsList[0].Message);
        }
        /// <inheritdoc/>
        public async Task <OrderDetailsViewModel> CreateOrUpdateOrder(OrderDetailsViewModel order)
        {
            NotNullValidator.ThrowIfNull(order, nameof(order));
            using var orderRequest = new StringContent(JsonSerializer.Serialize(order), Encoding.UTF8, ContentType);
            var orderResponse = await this.httpClient.PostAsync(new Uri($"{this.applicationSettings.OrdersApiEndpoint}"), orderRequest).ConfigureAwait(false);

            if (!orderResponse.IsSuccessStatusCode)
            {
                await this.ThrowServiceToServiceErrors(orderResponse).ConfigureAwait(false);
            }

            var createdOrder = await orderResponse.Content.ReadFromJsonAsync <OrderDetailsViewModel>().ConfigureAwait(false);

            return(createdOrder);
        }
        public void SetUp()
        {
            _notEmptyValidator      = new NotEmptyValidator(null);
            _notNullValidator       = new NotNullValidator();
            _notEqualValidator      = new NotEqualValidator("test");
            _maximumLengthValidator = new MaximumLengthValidator(30);
            _minimumLengthValidator = new MinimumLengthValidator(5);

            _componenValidationCollectorStub1 = MockRepository.GenerateStub <IComponentValidationCollector>();
            _componenValidationCollectorStub2 = MockRepository.GenerateStub <IComponentValidationCollector>();
            _componenValidationCollectorStub3 = MockRepository.GenerateStub <IComponentValidationCollector>();

            _firstNameExpression = ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.FirstName);
            _lastNameExpression  = ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.LastName);

            _addingPropertyRule1 = AddingComponentPropertyRule.Create(_firstNameExpression, _componenValidationCollectorStub1.GetType());
            _addingPropertyRule1.RegisterValidator(_notEmptyValidator);
            _addingPropertyRule1.RegisterValidator(_notNullValidator);
            _addingPropertyRule1.RegisterValidator(_notEqualValidator);

            _addingPropertyRule2 = AddingComponentPropertyRule.Create(_lastNameExpression, _componenValidationCollectorStub2.GetType());
            _addingPropertyRule2.RegisterValidator(_maximumLengthValidator);

            _addingPropertyRule3 = AddingComponentPropertyRule.Create(_lastNameExpression, _componenValidationCollectorStub2.GetType());
            _addingPropertyRule3.RegisterValidator(_minimumLengthValidator);

            _addingPropertyRule4 = AddingComponentPropertyRule.Create(_lastNameExpression, _componenValidationCollectorStub2.GetType());
            _addingPropertyRule4.RegisterValidator(_notNullValidator);

            _removingPropertyRule1 = RemovingComponentPropertyRule.Create(_firstNameExpression, typeof(CustomerValidationCollector1));
            _removingPropertyRule1.RegisterValidator(typeof(NotEmptyValidator));

            _removingPropertyRule2 = RemovingComponentPropertyRule.Create(_firstNameExpression, typeof(CustomerValidationCollector1));
            _removingPropertyRule2.RegisterValidator(typeof(NotNullValidator), _componenValidationCollectorStub1.GetType());

            _removingPropertyRule3 = RemovingComponentPropertyRule.Create(_firstNameExpression, typeof(CustomerValidationCollector1));
            _removingPropertyRule3.RegisterValidator(typeof(NotNullValidator), typeof(string)); //Unknow collector type!

            _removingPropertyRule4 = RemovingComponentPropertyRule.Create(_lastNameExpression, typeof(CustomerValidationCollector1));
            _removingPropertyRule4.RegisterValidator(typeof(MaximumLengthValidator));

            _propertyValidatorExtractorFactoryMock = MockRepository.GenerateStrictMock <IPropertyValidatorExtractorFactory>();
            _propertyValidatorExtractorMock        = MockRepository.GenerateStrictMock <IPropertyValidatorExtractor>();

            _merger = new OrderPrecedenceValidationCollectorMerger(_propertyValidatorExtractorFactoryMock);
        }
Пример #32
0
        public void SetUp()
        {
            _defaultMessageEvaluatorMock       = MockRepository.GenerateStrictMock <IDefaultMessageEvaluator>();
            _validatorGlobalizationServiceMock = MockRepository.GenerateStrictMock <IErrorMessageGlobalizationService>();

            _validator1          = new NotNullValidator();
            _errorMessageSource1 = _validator1.ErrorMessageSource;
            _validator2          = new NotEmptyValidator(null);
            _errorMessageSource2 = _validator2.ErrorMessageSource;
            _validator3          = new NotEqualValidator("test");
            _errorMessageSource3 = _validator3.ErrorMessageSource;

            _propertyRule = PropertyRule.Create(ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.LastName));
            _propertyRule.AddValidator(_validator1);
            _propertyRule.AddValidator(_validator2);
            _propertyRule.AddValidator(_validator3);

            _service = new ValidationRuleGlobalizationService(_defaultMessageEvaluatorMock, _validatorGlobalizationServiceMock);
        }
        public void Should_create_notnulladapter_for_notnullvalidator()
        {
            // Given
            var validator = new NotNullValidator();

            // When
            var result = factory.Create(this.rule, validator);

            // Then
            result.ShouldBeOfType<NotNullAdapter>();
        }
 public void Should_validate_property_value_without_instance()
 {
     var validator = new NotNullValidator();
     var context = new PropertyValidatorContext("Surname", null, null as object, null);
     validator.Validate(context).Single().ShouldNotBeNull();
 }
Пример #35
0
		public static NotNullValidator GetInstance() {
			if(uniqueInstance == null) uniqueInstance = new NotNullValidator();
			return uniqueInstance;
		}
Пример #36
0
 public void NotNullValidator_should_fail_if_value_is_null()
 {
     var validator = new NotNullValidator();
     var result = validator.Validate(new PropertyValidatorContext("name", new object(), x => null));
     result.Single();
 }
Пример #37
0
 public void NotNullValidator_should_pass_if_value_has_value()
 {
     var validator = new NotNullValidator();
     var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => "Jeremy"));
     result.Count().ShouldEqual(0);
 }
Пример #38
0
 public void Not_null_validator_should_work_ok_with_non_nullable_value_type()
 {
     var validator = new NotNullValidator();
     var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => 3));
     result.Count().ShouldEqual(0);
 }
Пример #39
0
 public void When_the_validator_fails_the_error_message_should_be_set()
 {
     var validator = new NotNullValidator();
     var result = validator.Validate(new PropertyValidatorContext("name", null, x => null));
     result.Single().ErrorMessage.ShouldEqual("'name' must not be empty.");
 }