Exemplo n.º 1
0
        public void SuppliesAppropriateParametersToMessageTemplate()
        {
            DomainValidator <int> validator = new DomainValidator <int>(false, 1, 2, 3, 4);

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

            ValidationResults validationResults = new ValidationResults();

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

            Assert.IsFalse(validationResults.IsValid);
            ValidationResult validationResult = ValidationTestHelper.GetResultsList(validationResults)[0];
            Match            match            = TemplateStringTester.Match(validator.MessageTemplate, validationResult.Message);

            Assert.IsTrue(match.Success);
            Assert.IsTrue(match.Groups["param0"].Success);
            Assert.AreEqual(target.ToString(), 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);
        }
Exemplo n.º 2
0
 public UserRole(Guid userId, Guid roleId)
 {
     DomainValidator.ValidateId(userId);
     DomainValidator.ValidateId(roleId);
     UserId = userId;
     RoleId = roleId;
 }
Exemplo n.º 3
0
        public Customer(string name, string streetAddress, string city, string state, string zipCode, string country, string documentNumber, string email, string phone)
        {
            DomainValidator.New()
            .When(string.IsNullOrEmpty(name), "Name is required")
            .When(string.IsNullOrEmpty(streetAddress), "Street Address is required")
            .When(string.IsNullOrEmpty(city), "City is required")
            .When(string.IsNullOrEmpty(state), "State is required")
            .When(string.IsNullOrEmpty(zipCode), "Zip Code is required")
            .When(string.IsNullOrEmpty(country), "Country is required")
            .When(string.IsNullOrEmpty(documentNumber), "Document Number is required")
            .When(string.IsNullOrEmpty(email), "Email is required")
            .When(string.IsNullOrEmpty(phone), "Phone is required");

            this.Name           = name;
            this.StreetAddress  = streetAddress;
            this.City           = city;
            this.State          = state;
            this.ZipCode        = zipCode;
            this.Country        = country;
            this.DocumentNumber = documentNumber;
            this.Email          = email;
            this.Phone          = phone;

            this.Orders = new List <Order>();
        }
Exemplo n.º 4
0
 public StoreCategoryRelation(Guid storeId, Guid categoryId)
 {
     DomainValidator.ValidateId(storeId);
     DomainValidator.ValidateId(categoryId);
     StoreId    = storeId;
     CategoryId = categoryId;
 }
        public void CreatingInstanceWithNonNegated()
        {
            DomainValidator<object> validator = new DomainValidator<object>(false);

            Assert.AreEqual(Resources.DomainNonNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
        }
Exemplo n.º 6
0
 public StoreProductRelation(Guid storeId, Guid productId)
 {
     DomainValidator.ValidateId(storeId);
     DomainValidator.ValidateId(productId);
     StoreId   = storeId;
     ProductId = productId;
 }
Exemplo n.º 7
0
        public void CreatingInstanceWithNonNegated()
        {
            DomainValidator <object> validator = new DomainValidator <object>(false);

            Assert.AreEqual(Resources.DomainNonNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
        }
Exemplo n.º 8
0
 public Category(Guid id, string name)
 {
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateString(name, 2, 60);
     Id   = id;
     Name = name;
 }
Exemplo n.º 9
0
 public AddQuestionProcessor(IDocumentReader <QuestionDto> reader, IDocumentWriter <QuestionDto> writer)
 {
     _reader          = reader;
     _writer          = writer;
     _dtoParser       = new QuestionDtoParser();
     _domainValidator = new DomainValidator();
 }
Exemplo n.º 10
0
        public void AddOrderItem(OrderItem orderItem)
        {
            DomainValidator.New().When(orderItem == null, "OrderItem cannot be null");

            OrderItems.Add(orderItem);
            CalculateTotalItems();
        }
Exemplo n.º 11
0
        public void NegatedAcceptsIntNotIncludedInTheDomain()
        {
            DomainValidator <int> validator = new DomainValidator <int>(true, 1, 2, 3);

            ValidationResults results = validator.Validate(4);

            Assert.IsTrue(results.IsValid);
        }
Exemplo n.º 12
0
        public void NonNegatedRejectsNull()
        {
            DomainValidator <object> validator = new DomainValidator <object>(false);

            ValidationResults results = validator.Validate(null);

            Assert.IsFalse(results.IsValid);
        }
Exemplo n.º 13
0
        public void NegatedRejectsStringIncludedInTheDomain()
        {
            DomainValidator <string> validator = new DomainValidator <string>(true, "a", "b", "c");

            ValidationResults results = validator.Validate("b");

            Assert.IsFalse(results.IsValid);
        }
Exemplo n.º 14
0
        public void NegatedAcceptsStringNotIncludedInTheDomain()
        {
            DomainValidator <string> validator = new DomainValidator <string>(true, "a", "b", "c");

            ValidationResults results = validator.Validate("d");

            Assert.IsTrue(results.IsValid);
        }
Exemplo n.º 15
0
        public void NegatedRejectsIntIncludedInTheDomain()
        {
            DomainValidator <int> validator = new DomainValidator <int>(true, 1, 2, 3);

            ValidationResults results = validator.Validate(2);

            Assert.IsFalse(results.IsValid);
        }
        public DomainValidatorOperation(string keyToValidate, string resultKey, IEnumerable<object> domain, bool negated)
            : base(keyToValidate, resultKey) {

            Validator = new DomainValidator<object>(
                domain,
                negated
            ) { Tag = keyToValidate };
        }
Exemplo n.º 17
0
 public User(Guid id, string userName, string email, Guid clientId)
 {
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateId(clientId);
     Id       = id;
     UserName = userName ?? throw new ArgumentNullException(nameof(userName));
     Email    = email ?? throw new ArgumentNullException(nameof(email));
     ClientId = clientId;
 }
Exemplo n.º 18
0
 private static void Validade(string name, Email email, string password)
 {
     DomainValidator.New()
     .When(string.IsNullOrEmpty(name), "Name is required")
     .When(name.Length > 25, "The maximum allowed for the user name is 25 characters.")
     .When(email == null, "Email is required")
     .When(string.IsNullOrEmpty(password), "Password is required")
     .When(password.Length < 8, "Password is not strong enough");
 }
Exemplo n.º 19
0
 public Client(Guid id, string name, double balance)
 {
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateString(name, 2, 60);
     DomainValidator.ValidateNumber(balance, 0, 100_000_000);
     Id      = id;
     Name    = name;
     Balance = balance;
 }
Exemplo n.º 20
0
        public void ValidatorTest(string domainName, bool expected)
        {
            var logger     = new FakeLogger();
            var seriazlier = new FakeDomainSerializer();

            var  validator = new DomainValidator(logger, seriazlier);
            bool result    = validator.IsValid(domainName);

            Assert.Equal(expected, result);
        }
Exemplo n.º 21
0
        public void ConstructorWithEmptyDomainCreatesCorrectInstance()
        {
            List <object>            domain    = new List <object>();
            DomainValidator <object> validator = new DomainValidator <object>(domain);

            Assert.AreEqual(Resources.DomainNonNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual(false, validator.Negated);
            Assert.AreEqual(0, validator.Domain.Count);
        }
        public void ConstructorWithEmptyDomainCreatesCorrectInstance()
        {
            List<object> domain = new List<object>();
            DomainValidator<object> validator = new DomainValidator<object>(domain);

            Assert.AreEqual(Resources.DomainNonNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual(false, validator.Negated);
            Assert.AreEqual(0, validator.Domain.Count);
        }
Exemplo n.º 23
0
        public bool Charge(double sum)
        {
            DomainValidator.ValidateNumber(sum, 0, 100_000_000);
            if (Balance < sum)
            {
                return(false);
            }

            Balance -= sum;
            return(true);
        }
Exemplo n.º 24
0
        public Order(int customerId, ICollection <OrderItem> orderItems)
        {
            DomainValidator.New()
            .When(customerId == 0, "Customer is required")
            .When(orderItems == null || orderItems.Count == 0, "OrderItems is required");

            this.CustomerId = customerId;
            this.OrderItems = orderItems;

            CalculateTotalItems();
        }
Exemplo n.º 25
0
 public DomainValidatorOperation(string keyToValidate, string resultKey, IEnumerable <object> domain, bool negated)
     : base(keyToValidate, resultKey)
 {
     Validator = new DomainValidator <object>(
         domain,
         negated
         )
     {
         Tag = keyToValidate
     };
 }
Exemplo n.º 26
0
        public void ConstructorWithDomainAsArrayCreatesCorrectInstance()
        {
            object[] domain = new object[] { 1, 2, 3 };
            DomainValidator <object> validator = new DomainValidator <object>(false, 1, 2, 3);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual(Resources.DomainNonNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
            Assert.AreEqual(domain.Length, validator.Domain.Count);
            Assert.AreEqual(3, validator.Domain.Count);
        }
Exemplo n.º 27
0
        public void ConstructorWithDomainAsArrayCreatesAndMessageTemplateCorrectInstance()
        {
            object[] domain = new object[] { 1, 2, 3 };
            DomainValidator <object> validator = new DomainValidator <object>("my message template", 1, 2, 3);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual("my message template", validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
            Assert.AreEqual(domain.Length, validator.Domain.Count);
            Assert.AreEqual(3, validator.Domain.Count);
        }
Exemplo n.º 28
0
        public void ConstructorWithDomainAsListCreatesAndMessageTemplateCorrectInstance()
        {
            List <object>            domain    = new List <object>(new object[] { 1, 2, 3 });
            DomainValidator <object> validator = new DomainValidator <object>(domain, "my message template", true);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual("my message template", validator.MessageTemplate);
            Assert.AreEqual(true, validator.Negated);
            Assert.AreEqual(domain.Count, validator.Domain.Count);
            Assert.AreEqual(3, validator.Domain.Count);
        }
Exemplo n.º 29
0
        public void ConstructorWithDomainAsGenericListAndNegatedCreatesCorrectInstance()
        {
            List <object>            domain    = new List <object>(new object[] { 1, 2, 3 });
            DomainValidator <object> validator = new DomainValidator <object>(domain, true);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual(true, validator.Negated);
            Assert.AreEqual(Resources.DomainNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(domain, validator.Domain);
            Assert.AreEqual(3, validator.Domain.Count);
        }
Exemplo n.º 30
0
 public Product(Guid id, string name, double priceInUAH, ProductStatus productStatus, Guid categoryId)
 {
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateId(categoryId);
     DomainValidator.ValidateString(name, 2, 60);
     DomainValidator.ValidateNumber(priceInUAH, 0, 100_000_000);
     Id            = id;
     Name          = name;
     PriceInUAH    = priceInUAH;
     ProductStatus = productStatus;
     CategoryId    = categoryId;
 }
Exemplo n.º 31
0
 public Purchase(Guid id, Guid clientId, Guid productId, double priceAtPurchaseMoment)
 {
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateId(clientId);
     DomainValidator.ValidateId(productId);
     DomainValidator.ValidateNumber(priceAtPurchaseMoment, 0, 100_000_000);
     Id                    = id;
     ClientId              = clientId;
     ProductId             = productId;
     CreationTime          = DateTimeOffset.UtcNow;
     PriceAtPurchaseMoment = priceAtPurchaseMoment;
 }
Exemplo n.º 32
0
 public Store(Guid id, string name, string location, double profit)
 {
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateString(name, 2, 60);
     DomainValidator.ValidateString(location, 2, 60);
     DomainValidator.ValidateNumber(profit, 0, double.MaxValue);
     Id          = id;
     Name        = name;
     Location    = location;
     Profit      = profit;
     _categories = new List <Category>();
 }
Exemplo n.º 33
0
 public Book(Guid id, Guid clientId, Guid productId, int reserveDaysCount)
 {
     DomainValidator.ValidateNumber(reserveDaysCount, 1, 7);
     DomainValidator.ValidateId(id);
     DomainValidator.ValidateId(clientId);
     DomainValidator.ValidateId(productId);
     Id               = id;
     ClientId         = clientId;
     ProductId        = productId;
     CreationTime     = DateTimeOffset.UtcNow;
     ExpirationTime   = CreationTime.AddDays(reserveDaysCount);
     ReserveDaysCount = reserveDaysCount;
 }
        public void ConstructorWithDomainAsGenericListCreatesCorrectInstance()
        {
            List<object> domain = new List<object>(new object[] { 1, 2, 3 });
            DomainValidator<object> validator = new DomainValidator<object>(domain);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual(Resources.DomainNonNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
            Assert.AreEqual(3, validator.Domain.Count);
            foreach (var item in domain)
            {
                Assert.IsTrue(validator.Domain.Contains(item));
            }
        }
Exemplo n.º 35
0
 static void CreatingAndUsingValidatorsDirectly()
 {
     // Create a Contains Characters Validator and use it to validate a String value.
     Validator charsValidator = new ContainsCharactersValidator("cat", ContainsCharacters.All,
                                                                  "Value must contain {4} of the characters '{3}'.");
     Console.WriteLine("Validating a string value using a Contains Characters Validator...");
     charsValidator.Tag = "Validating the String value 'disconnected'";
     // This overload of the Validate method returns a new ValidationResults
     // instance populated with any/all of the validation errors.
     ValidationResults valResults = charsValidator.Validate("disconnected");
     // Create a Domain Validator and use it to validate an Integer value.
     Validator integerValidator = new DomainValidator<int>("Value must be in the list 1, 3, 7, 11, 13.",
                                                              new int[] { 1, 3, 7, 11, 13 });
     integerValidator.Tag = "Validating the Integer value '42'";
     Console.WriteLine("Validating an integer value using a Domain Validator...");
     // This overload of the Validate method takes an existing ValidationResults
     // instance and adds any/all of the validation errors to it.
     integerValidator.Validate(42, valResults);
     // Create an Or Composite Validator containing two validators.
     // Note that the NotNullValidator is negated to allow NULL values.
     Validator[] valArray = new Validator[] {
           new NotNullValidator(true, "Value can be NULL."),
           new StringLengthValidator(5, RangeBoundaryType.Inclusive, 5, RangeBoundaryType.Inclusive,
                                         "Value must be between {3} ({4}) and {5} ({6}) chars.")
         };
     Validator orValidator = new OrCompositeValidator("Value can be NULL or a string of 5 characters.", valArray);
     // Validate two strings using the Or Composite Validator.
     Console.WriteLine("Validating a NULL value using an Or Composite Validator...");
     orValidator.Validate(null, valResults);  // this will not cause a validation error
     Console.WriteLine("Validating a string value using an Or Composite Validator...");
     orValidator.Validate("MoreThan5Chars", valResults);
     // Validate a single property of an existing class instance.
     // First create a Product instance with an invalid ID value.
     IProduct productWithID = new Product();
     PopulateInvalidProduct(productWithID);
     // Create a Property Value Validator that will use a RegexValidator
     // to validate the property value.
     Validator propValidator = new PropertyValueValidator<Product>("ID",
                         new RegexValidator("[A-Z]{2}[0-9]{4}", "Product ID must be 2 capital letters and 4 numbers."));
     Console.WriteLine("Validating one property of an object using a Property Value Validator...");
     propValidator.Validate(productWithID, valResults);
     // Now display the results of all the previous validation operations.
     ShowValidationResults(valResults);
 }
        public void ConstructorWithDomainAsArrayInConstructorAndNegatedCreatesCorrectInstance()
        {
            object[] domain = new object[] { 1, 2, 3 };
            DomainValidator<object> validator = new DomainValidator<object>(true, domain);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual(Resources.DomainNegatedDefaultMessageTemplate, validator.MessageTemplate);
            Assert.AreEqual(true, validator.Negated);
            Assert.AreEqual(domain.Length, validator.Domain.Count);
            Assert.AreEqual(3, validator.Domain.Count);
        }
        public void ConstructorWithDomainAsArrayCreatesAndMessageTemplateCorrectInstance()
        {
            object[] domain = new object[] { 1, 2, 3 };
            DomainValidator<object> validator = new DomainValidator<object>("my message template", 1, 2, 3);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual("my message template", validator.MessageTemplate);
            Assert.AreEqual(false, validator.Negated);
            Assert.AreEqual(domain.Length, validator.Domain.Count);
            Assert.AreEqual(3, validator.Domain.Count);
        }
        public void ConstructorWithDomainAsListCreatesAndMessageTemplateCorrectInstance()
        {
            List<object> domain = new List<object>(new object[] { 1, 2, 3 });
            DomainValidator<object> validator = new DomainValidator<object>(domain, "my message template", true);

            Assert.IsNotNull(validator.Domain);
            Assert.AreEqual("my message template", validator.MessageTemplate);
            Assert.AreEqual(true, validator.Negated);
            Assert.AreEqual(domain.Count, validator.Domain.Count);
            Assert.AreEqual(3, validator.Domain.Count);
        }
        public void NonNegatedRejectsNull()
        {
            DomainValidator<object> validator = new DomainValidator<object>(false);

            ValidationResults results = validator.Validate(null);

            Assert.IsFalse(results.IsValid);
        }
        public void NegatedRejectsStringIncludedInTheDomain()
        {
            DomainValidator<string> validator = new DomainValidator<string>(true, "a", "b", "c");

            ValidationResults results = validator.Validate("b");

            Assert.IsFalse(results.IsValid);
        }
        public void NegatedAcceptsStringNotIncludedInTheDomain()
        {
            DomainValidator<string> validator = new DomainValidator<string>(true, "a", "b", "c");

            ValidationResults results = validator.Validate("d");

            Assert.IsTrue(results.IsValid);
        }
        public void NegatedRejectsIntIncludedInTheDomain()
        {
            DomainValidator<int> validator = new DomainValidator<int>(true, 1, 2, 3);

            ValidationResults results = validator.Validate(2);

            Assert.IsFalse(results.IsValid);
        }
        public void NegatedAcceptsIntNotIncludedInTheDomain()
        {
            DomainValidator<int> validator = new DomainValidator<int>(true, 1, 2, 3);

            ValidationResults results = validator.Validate(4);

            Assert.IsTrue(results.IsValid);
        }
        public void SuppliesAppropriateParametersToMessageTemplate()
        {
            DomainValidator<int> validator = new DomainValidator<int>(false, 1, 2, 3, 4);
            validator.MessageTemplate = "{0}-{1}-{2}";
            validator.Tag = "tag";
            object target = 24;
            string key = "key";

            ValidationResults validationResults = new ValidationResults();
            validator.DoValidate(target, null, key, validationResults);

            Assert.IsFalse(validationResults.IsValid);
            ValidationResult validationResult = ValidationTestHelper.GetResultsList(validationResults)[0];
            Match match = TemplateStringTester.Match(validator.MessageTemplate, validationResult.Message);
            Assert.IsTrue(match.Success);
            Assert.IsTrue(match.Groups["param0"].Success);
            Assert.AreEqual(target.ToString(), 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 void SuppliesAppropriateParametersToDefaultNegatedMessage()
        {
            DomainValidator<int> validator = new DomainValidator<int>(true, 1, 2, 3, 4);
            validator.Tag = "tag";
            object target = 1;
            string key = "key";

            ValidationResults validationResults = new ValidationResults();
            validator.DoValidate(target, null, key, validationResults);

            Assert.IsFalse(validationResults.IsValid);
            ValidationResult validationResult = ValidationTestHelper.GetResultsList(validationResults)[0];
            Match match = TemplateStringTester.Match(validator.MessageTemplate, validationResult.Message);
            Assert.IsTrue(match.Success);
            Assert.IsFalse(match.Groups["param0"].Success);
            Assert.IsFalse(match.Groups["param1"].Success);
            Assert.IsFalse(match.Groups["param2"].Success);
        }