コード例 #1
0
        public async Task <ActionResult> GetCustomerById(int customerId)
        {
            LogStart();
            try
            {
                var errorInfo = new ErrorInfo();

                // Customer Id
                errorInfo = IdentifierValidator.Validate(customerId);
                if (errorInfo.ErrorCode != ErrorTypes.OK)
                {
                    throw new BadInputException(errorInfo);
                }

                var customerModel = await _customerRepository.GetCustomerByIdentifierAsync(customerId);

                // Customer
                errorInfo = CustomerObjectValidator.Validate(customerModel, customerId);
                if (errorInfo.ErrorCode != ErrorTypes.OK)
                {
                    throw new NotFoundException(errorInfo);
                }

                // Map
                var result = _mapper.Map <CustomerDto>(customerModel);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                LogError(ex);
                throw ex;
            }
        }
コード例 #2
0
 /// <summary>
 /// Attempts to validate a user-provided identifier.
 /// </summary>
 /// <param name="identifier">The identifier to validate.</param>
 /// <exception cref="PasswordValidationException">Thrown on validation failure.</exception>
 public void Validate(string identifier)
 {
     if (!IdentifierValidator.Validate(identifier, out string errorMessage))
     {
         throw new IdentifierValidationException(errorMessage);
     }
 }
コード例 #3
0
ファイル: CremaDataSet.cs プロジェクト: teize001/Crema
        //[Obsolete]
        //public static Func<string, bool> NameVerifier
        //{
        //    get { return nameVerifier ?? defaultNameVerifier; }
        //    set { nameVerifier = value; }
        //}

        public static void ValidateName(string name)
        {
            if (IdentifierValidator.Verify(name) == false)
            {
                throw new ArgumentException($"{name} is invalid name", nameof(name));
            }
        }
コード例 #4
0
        /// <summary>
        ///		Sets the value of a variable referenced within the expression prior
        ///		to evaluation. This override allows specifying the Type of the variable
        ///		instead of trying to introspect it. Also allows for passing null as the
        ///		value.
        /// </summary>
        /// <param name="name">
        ///		Name of the variable referenced within the expression.
        /// </param>
        /// <param name="value">
        ///		Value of the variable that should be used when evaluating the expression.
        /// </param>
        /// <param name="type">
        ///		The variable Type.
        /// </param>
        public void SetVariable(
            string name,
            object value,
            Type type)
        {
            if (variables.ContainsKey(name))
            {
                variables[name].Value = value;
            }
            else
            {
                if (IdentifierValidator.IsValidIdentifier(name))
                {
                    variables[name] = new Variable
                    {
                        Type  = type,
                        Value = value
                    };

                    initialized = false;
                }
                else
                {
                    throw new ArgumentException("Invalid value passed in for variable name. " +
                                                "Valid variable names must start with a letter or underscore, and not contain any whitespace.");
                }
            }
        }
コード例 #5
0
        public string GetSafeIdentifier(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(name);
            }

            // NOTE: "partial" differs in behavior on macOS vs. Windows, Windows reports "partial" as a valid identifier
            //	This check ensures the same output on both platforms
            switch (name)
            {
            case "partial": return(name);

            // `this` isn't in TypeNameUtilities.reserved_keywords; special-case.
            case "this": return("this_");
            }

            // In the ideal world, it should not be applied twice.
            // Sadly that is not true in reality, so we need to exclude non-symbols
            // when replacing the argument name with a valid identifier.
            // (ReturnValue.ToNative() takes an argument which could be either an expression or mere symbol.)
            if (name [name.Length - 1] != ')' && !name.Contains('.') && !name.StartsWith("@"))
            {
                if (!IdentifierValidator.IsValidIdentifier(name) ||
                    Array.BinarySearch(TypeNameUtilities.reserved_keywords, name) >= 0)
                {
                    name = name + "_";
                }
            }
            return(name.Replace('$', '_'));
        }
コード例 #6
0
 private void ID_TextChanged(object sender, TextChangedEventArgs e)
 {
     if (this.ID.Text != string.Empty && IdentifierValidator.Verify(this.ID.Text) == false)
     {
         //this.blinker.HasError = true;
     }
 }
コード例 #7
0
        /// <summary>
        /// Create cil source-code representation of a <see cref="EnumDefinition"/>.
        /// </summary>
        /// <exception cref="Exceptions.InvalidAssemblyNameException">
        /// Thrown when a invalid assembly name is given.
        /// </exception>
        /// <exception cref="Exceptions.InvalidNamespaceException">
        /// Thrown when a invalid namespace identifier is given.
        /// </exception>
        /// <exception cref="Exceptions.OutOfBoundsValueException">
        /// Thrown when enum value does not fit in given storage-type.
        /// </exception>
        /// <param name="enumDefinition">Enum to generate cil source-code for</param>
        /// <param name="assemblyName">Name of the assembly to generate</param>
        /// <param name="namespace">Optional namespace to add the enum to</param>
        /// <param name="headerMode">Mode to use when adding a header</param>
        /// <param name="indentMode">Mode to use for indenting</param>
        /// <param name="spaceIndentSize">When indenting with spaces this controls how many</param>
        /// <param name="newlineMode">Mode to use for ending lines</param>
        /// <param name="storageType">Underlying enum storage-type to use</param>
        /// <param name="curlyBracketMode">Mode to use when writing curly brackets</param>
        /// <returns>String containing the genenerated cil sourcecode</returns>
        public static string ExportCil(
            this EnumDefinition enumDefinition,
            string assemblyName,
            string @namespace                   = null,
            HeaderMode headerMode               = HeaderMode.Default,
            CodeBuilder.IndentMode indentMode   = CodeBuilder.IndentMode.Spaces,
            int spaceIndentSize                 = 4,
            CodeBuilder.NewlineMode newlineMode = CodeBuilder.NewlineMode.Unix,
            StorageType storageType             = StorageType.Implicit,
            CurlyBracketMode curlyBracketMode   = CurlyBracketMode.NewLine)
        {
            if (enumDefinition == null)
            {
                throw new ArgumentNullException(nameof(enumDefinition));
            }

            if (string.IsNullOrEmpty(assemblyName) || !IdentifierValidator.Validate(assemblyName))
            {
                throw new InvalidAssemblyNameException(assemblyName);
            }

            if (!string.IsNullOrEmpty(@namespace) && !IdentifierValidator.ValidateNamespace(@namespace))
            {
                throw new InvalidNamespaceException(@namespace);
            }

            foreach (var oobEntry in enumDefinition.Entries.Where(e => !storageType.Validate(e.Value)))
            {
                throw new OutOfBoundsValueException(storageType, oobEntry.Value);
            }

            var builder = new CodeBuilder(indentMode, spaceIndentSize, newlineMode);

            if (headerMode != HeaderMode.None)
            {
                builder.AddHeader();
                builder.WriteEndLine();
            }

            // Add reference to mscorlib.
            builder.WriteLine(".assembly extern mscorlib { }");
            builder.WriteEndLine();

            // Add assembly info.
            builder.Write($".assembly {assemblyName}");
            StartScope(builder, curlyBracketMode);
            builder.WriteLine(".ver 1:0:0:0");
            EndScope(builder);
            builder.WriteEndLine();

            // Add module info.
            builder.WriteLine($".module {assemblyName}.dll");
            builder.WriteEndLine();

            // Add enum class.
            builder.AddEnum(enumDefinition, storageType, curlyBracketMode, @namespace);

            return(builder.Build());
        }
コード例 #8
0
        public void ReturnFailureForEmptyIdentifier()
        {
            Validator <string> validator         = new IdentifierValidator();
            ValidationResults  validationResults = validator.Validate(string.Empty);

            Assert.IsFalse(validationResults.IsValid);
            Assert.AreEqual(1, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #9
0
		public void ReturnFailureForInvalidDefaultLengthIdentifier()
		{
			Validator<string> validator = new IdentifierValidator();
			ValidationResults validationResults = validator.Validate("asdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

			Assert.IsFalse(validationResults.IsValid);
			Assert.AreEqual(1, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #10
0
        public void IdentifierWithValidNameIsValid()
        {
            var alert = new Alert();
            alert.Identifier = "43b080713727";

            var identifierValidator = new IdentifierValidator(alert);
            Assert.True(identifierValidator.IsValid);
        }
コード例 #11
0
		public void ReturnFailureForEmptyIdentifier()
		{
			Validator<string> validator = new IdentifierValidator();
			ValidationResults validationResults = validator.Validate(string.Empty);

			Assert.IsFalse(validationResults.IsValid);
			Assert.AreEqual(1, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #12
0
        public void ReturnFailureForInvalidIdentifierByLanguage()
        {
            Validator <string> validator         = new IdentifierValidator("VB", null);
            ValidationResults  validationResults = validator.Validate("?asd");

            Assert.IsFalse(validationResults.IsValid);
            Assert.AreEqual(1, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #13
0
        public void ReturnSuccessForValidIdentifierByLanguage()
        {
            Validator <string> validator         = new IdentifierValidator("VB", null);
            ValidationResults  validationResults = validator.Validate("test");

            Assert.IsTrue(validationResults.IsValid);
            Assert.AreEqual(0, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #14
0
        public void ReturnFailureForInvalidDefaultLengthIdentifier()
        {
            Validator <string> validator         = new IdentifierValidator();
            ValidationResults  validationResults = validator.Validate("asdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

            Assert.IsFalse(validationResults.IsValid);
            Assert.AreEqual(1, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #15
0
 public IdentifierValidatorTests()
 {
     _pidUriTemplateService   = new Mock <IPidUriTemplateService>();
     _pidUriGenerationService = new Mock <IPidUriGenerationService>();
     _consumerGroupService    = new Mock <IConsumerGroupService>();
     _validator = new IdentifierValidator(_pidUriTemplateService.Object, _pidUriGenerationService.Object, _consumerGroupService.Object);
     _metadata  = new MetadataBuilder().GenerateSamplePidUri().Build();
 }
コード例 #16
0
ファイル: UserCollection.cs プロジェクト: sedrion/Crema
 private static bool VerifyName(string name)
 {
     if (NameValidator.VerifyName(name) == false)
     {
         return(false);
     }
     return(IdentifierValidator.Verify(name));
 }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EnumBuilder"/> class
        /// </summary>
        /// <exception cref="Exceptions.InvalidEnumNameException">
        /// Thrown when name is not a valid identifier.
        /// </exception>
        /// <param name="name">Name of the enum</param>
        public EnumBuilder(string name)
        {
            if (!IdentifierValidator.Validate(name))
            {
                throw new Exceptions.InvalidEnumNameException(this.name);
            }

            this.name = name;
        }
コード例 #18
0
ファイル: UserItemTest.cs プロジェクト: s2quake/JSSoft.Crema
        public async Task Name_User_TestAsync()
        {
            var userItemFilter = new UserItemFilter(typeof(IUser));
            var userItem       = await userItemFilter.GetUserItemAsync(app);

            var condition = IdentifierValidator.Verify(userItem.Name);

            Assert.IsTrue(condition);
        }
コード例 #19
0
        public void AttributeBasedConstructorWithEmptyAttributeCollection()
        {
            Validator <string> validator = new IdentifierValidator((NameValueCollection)null);

            ValidationResults validationResults = validator.Validate("test");

            Assert.IsTrue(validationResults.IsValid);
            Assert.AreEqual(0, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #20
0
        public void Invalid(string value)
        {
            IValidator <Identifier> validator = new IdentifierValidator();

            var target = new ValidationTarget <Identifier>(new Identifier(value));

            validator.Validate(target);
            Assert.True(target.GetResult().HasErrors);
        }
コード例 #21
0
        public void IdentifierWithCommaIsInvalid()
        {
            var alert = new Alert();
            alert.Identifier = "43b080713727,";

            var identifierValidator = new IdentifierValidator(alert);
            Assert.False(identifierValidator.IsValid);
            Assert.Equal(typeof(IdentifierError), identifierValidator.Errors.ElementAt(0).GetType());
            Assert.Equal(1, identifierValidator.Errors.Count());
        }
コード例 #22
0
        public static string NextInvalidIdentifier()
        {
            string name;

            while (IdentifierValidator.Verify((name = NextWord())) == true)
            {
                ;
            }
            return(name);
        }
コード例 #23
0
        public void IsValidIdentifier()
        {
            Assert.IsTrue(IdentifierValidator.IsValidIdentifier("name"));
            Assert.IsTrue(IdentifierValidator.IsValidIdentifier("Name_With_Underscores"));

            // Yes, this is "wrong" -- keywords aren't identifiers -- but the keyword check is done elsewhere.
            Assert.IsTrue(IdentifierValidator.IsValidIdentifier("true"));

            Assert.IsFalse(IdentifierValidator.IsValidIdentifier("name-with-hyphens and spaces"));
            Assert.IsFalse(IdentifierValidator.IsValidIdentifier("123"));
        }
コード例 #24
0
		public void ReturnFailureForInvalidConfigurableLengthIdentifier()
		{
			NameValueCollection atts = new NameValueCollection();
			atts.Add("length", "4");

			Validator<string> validator = new IdentifierValidator(atts);
			ValidationResults validationResults = validator.Validate("ABCDE");

			Assert.IsFalse(validationResults.IsValid);
			Assert.AreEqual(1, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #25
0
        public void ReturnFailureForInvalidConfigurableLengthIdentifier()
        {
            NameValueCollection atts = new NameValueCollection();

            atts.Add("length", "4");

            Validator <string> validator         = new IdentifierValidator(atts);
            ValidationResults  validationResults = validator.Validate("ABCDE");

            Assert.IsFalse(validationResults.IsValid);
            Assert.AreEqual(1, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #26
0
 public override ValidationResult Validate(object value, CultureInfo cultureInfo)
 {
     try
     {
         IdentifierValidator.Validate(value.ToString());
         return(new ValidationResult(true, null));
     }
     catch (Exception e)
     {
         return(new ValidationResult(false, e.Message));
     }
 }
コード例 #27
0
        public void IgnoreEmptyValuesIfOptionalFlagTrue()
        {
            NameValueCollection attributes = new NameValueCollection();

            attributes.Add("optionalValue", "True");

            Validator <string> validator = new IdentifierValidator(attributes);

            ValidationResults validationResults = validator.Validate("");

            Assert.IsTrue(validationResults.IsValid);
            Assert.AreEqual(0, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #28
0
        public void AttributeBasedConstructor()
        {
            NameValueCollection attributes = new NameValueCollection();

            attributes.Add("language", "VB");

            Validator <string> validator = new IdentifierValidator(attributes);

            ValidationResults validationResults = validator.Validate("test");

            Assert.IsTrue(validationResults.IsValid);
            Assert.AreEqual(0, (new List <ValidationResult>(validationResults)).Count);
        }
コード例 #29
0
        /// <summary>
        /// Create csharp source-code representation of a <see cref="EnumDefinition"/>.
        /// </summary>
        /// <exception cref="Exceptions.InvalidNamespaceException">
        /// Thrown when a invalid namespace identifier is given.
        /// </exception>
        /// <exception cref="Exceptions.OutOfBoundsValueException">
        /// Thrown when enum value does not fit in given storage-type.
        /// </exception>
        /// <param name="enumDefinition">Enum to generate csharp source-code for</param>
        /// <param name="namespace">Optional namespace to add the enum to</param>
        /// <param name="headerMode">Mode to use when adding a header</param>
        /// <param name="indentMode">Mode to use for indenting</param>
        /// <param name="spaceIndentSize">When indenting with spaces this controls how many</param>
        /// <param name="newlineMode">Mode to use for ending lines</param>
        /// <param name="storageType">Underlying enum storage-type to use</param>
        /// <param name="curlyBracketMode">Mode to use when writing curly brackets</param>
        /// <returns>String containing the genenerated csharp sourcecode</returns>
        public static string ExportCSharp(
            this EnumDefinition enumDefinition,
            string @namespace                   = null,
            HeaderMode headerMode               = HeaderMode.Default,
            CodeBuilder.IndentMode indentMode   = CodeBuilder.IndentMode.Spaces,
            int spaceIndentSize                 = 4,
            CodeBuilder.NewlineMode newlineMode = CodeBuilder.NewlineMode.Unix,
            StorageType storageType             = StorageType.Implicit,
            CurlyBracketMode curlyBracketMode   = CurlyBracketMode.NewLine)
        {
            if (enumDefinition == null)
            {
                throw new ArgumentNullException(nameof(enumDefinition));
            }

            if (!string.IsNullOrEmpty(@namespace) && !IdentifierValidator.ValidateNamespace(@namespace))
            {
                throw new InvalidNamespaceException(@namespace);
            }

            foreach (var oobEntry in enumDefinition.Entries.Where(e => !storageType.Validate(e.Value)))
            {
                throw new OutOfBoundsValueException(storageType, oobEntry.Value);
            }

            var builder = new CodeBuilder(indentMode, spaceIndentSize, newlineMode);

            if (headerMode != HeaderMode.None)
            {
                builder.AddHeader();
                builder.WriteEndLine();
            }

            builder.WriteLine("using System.CodeDom.Compiler;");
            builder.WriteEndLine();

            if (string.IsNullOrEmpty(@namespace))
            {
                builder.AddEnum(enumDefinition, storageType, curlyBracketMode);
            }
            else
            {
                builder.AddNamespace(
                    @namespace,
                    b => b.AddEnum(enumDefinition, storageType, curlyBracketMode),
                    curlyBracketMode);
            }

            return(builder.Build());
        }
コード例 #30
0
        static string EnsureValidIdentifer(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(name);
            }

            name = IdentifierValidator.CreateValidIdentifier(name);

            if (char.IsNumber(name [0]))
            {
                name = $"_{name}";
            }

            return(name);
        }
コード例 #31
0
        /// <summary>
        /// Add a entry to the enum.
        /// </summary>
        /// <exception cref="Exceptions.InvalidEnumEntryNameException">
        /// Thrown when name is not a valid identifier.
        /// </exception>
        /// <exception cref="Exceptions.DuplicateEnumEntryNameException">
        /// Thrown when name is not unique.
        /// </exception>
        /// <exception cref="Exceptions.DuplicateEnumEntryValueException">
        /// Thrown when value is not unique.
        /// </exception>
        /// <param name="name">Name of the entry</param>
        /// <param name="value">Value of the entry</param>
        /// <param name="comment">Optional comment about the entry</param>
        public void PushEntry(string name, long value, string comment = null)
        {
            if (!IdentifierValidator.Validate(name))
            {
                throw new Exceptions.InvalidEnumEntryNameException(this.name, name);
            }

            if (this.entries.Any(e => e.Name == name))
            {
                throw new Exceptions.DuplicateEnumEntryNameException(this.name, name);
            }

            if (this.entries.Any(e => e.Value == value))
            {
                throw new Exceptions.DuplicateEnumEntryValueException(this.name, value);
            }

            this.entries.Add(new EnumEntry(name, value, comment));
        }
コード例 #32
0
        private static bool ValidateIdentifier(string identifier)
        {
            if (String.IsNullOrEmpty(identifier))
            {
                return(false);
            }

            if (!IdentifierValidator.IsLetter(identifier[0]))
            {
                return(false);
            }

            for (int i = 1; i < identifier.Length; ++i)
            {
                if (!IdentifierValidator.IsValidCharacter(identifier[i]))
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #33
0
 public void CreateValidIdentifier_Encoded()
 {
     Assert.AreEqual("my_x45_identifier_x36_test", IdentifierValidator.CreateValidIdentifier("my-identifier$test", true));
     Assert.AreEqual("myidentifier_x55357__x56842_test", IdentifierValidator.CreateValidIdentifier("myidentifier😊test", true));
 }
コード例 #34
0
ファイル: CremaDataSet.cs プロジェクト: teize001/Crema
 public static bool VerifyName(string name)
 {
     return(IdentifierValidator.Verify(name));
 }
コード例 #35
0
		public void AttributeBasedConstructorWithEmptyAttributeCollection()
		{
			Validator<string> validator = new IdentifierValidator((NameValueCollection)null);

			ValidationResults validationResults = validator.Validate("test");

			Assert.IsTrue(validationResults.IsValid);
			Assert.AreEqual(0, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #36
0
		public void ReturnSuccessForValidIdentifierByLanguage()
		{
			Validator<string> validator = new IdentifierValidator("VB", null);
			ValidationResults validationResults = validator.Validate("test");

			Assert.IsTrue(validationResults.IsValid);
			Assert.AreEqual(0, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #37
0
        public async Task <IActionResult> UpdateCustomer(int id, UpdateCustomerRequest request)
        {
            var errorInfo = new ErrorInfo();

            // Verify customer identifier from route and request body
            errorInfo = IdentifierValidator.Validate(id, request.CustomerIdentifier);
            if (errorInfo.ErrorCode != ErrorTypes.OK)
            {
                throw new BadInputException(errorInfo);
            }

            // Find customer to update
            var currentCustomer = await _customerRepository.GetCustomerByIdentifierAsync(id);

            // Customer
            errorInfo = CustomerObjectValidator.Validate(currentCustomer, id);
            if (errorInfo.ErrorCode != ErrorTypes.OK)
            {
                throw new BadInputException(errorInfo);
            }

            bool isModified = false;

            // Fullname
            if (request.FullName != null && currentCustomer.FullName != request.FullName)
            {
                errorInfo = FullNameValidator.Validate(request.FullName, out string fullName);
                if (errorInfo.ErrorCode != ErrorTypes.OK)
                {
                    throw new BadInputException(errorInfo);
                }

                isModified = true;
                currentCustomer.FullName = fullName;
            }

            // Date of Birth
            if (request.DateOfBirth != null && currentCustomer.DateOfBirth.ToString() != request.DateOfBirth)
            {
                errorInfo = DateTimeValidator.Validate(request.DateOfBirth, out DateTime? validDate);
                if (errorInfo.ErrorCode != ErrorTypes.OK)
                {
                    throw new BadInputException(errorInfo);
                }

                isModified = true;
                currentCustomer.DateOfBirth = validDate;
                currentCustomer.Age         = CalculateAge.Calculate(request.DateOfBirth);
            }

            // Validate ICollection Address
            if (request?.Address != null)
            {
                foreach (var item in request.Address)
                {
                    errorInfo = AddressValidator.Validate(item);
                    if (errorInfo.ErrorCode != ErrorTypes.OK)
                    {
                        throw new BadInputException(errorInfo);
                    }
                }

                isModified = true;
                currentCustomer.Address = _mapper.Map <List <AddressModel> >(request.Address);
            }

            if (isModified)
            {
                // TODO: To implement the updated and created date in Model
                // newCustomer.UpdatedDate = DateTime.UtcNow;
                await _customerRepository.UpdateCustomerAsync(currentCustomer);
            }

            // Map Journal Model to Journal Dto
            var resultDto = _mapper.Map <CustomerDto>(currentCustomer);

            return(Ok(resultDto));
        }
コード例 #38
0
		public void AttributeBasedConstructor()
		{
			NameValueCollection attributes = new NameValueCollection();
			attributes.Add("language", "VB");

			Validator<string> validator = new IdentifierValidator(attributes);

			ValidationResults validationResults = validator.Validate("test");

			Assert.IsTrue(validationResults.IsValid);
			Assert.AreEqual(0, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #39
0
		public void ReturnFailureForInvalidIdentifierByLanguage()
		{
			Validator<string> validator = new IdentifierValidator("VB", null);
			ValidationResults validationResults = validator.Validate("?asd");

			Assert.IsFalse(validationResults.IsValid);
			Assert.AreEqual(1, (new List<ValidationResult>(validationResults)).Count);
		}
コード例 #40
0
		public void ReturnErrorForUnknownLanguage()
		{
			Validator<string> validator = new IdentifierValidator("UnknownLanguage", null);
			ValidationResults validationResults = validator.Validate("valid");
		}
コード例 #41
0
		public void IgnoreEmptyValuesIfOptionalFlagTrue()
		{
			NameValueCollection attributes = new NameValueCollection();
			attributes.Add("optionalValue", "True");

			Validator<string> validator = new IdentifierValidator(attributes);

			ValidationResults validationResults = validator.Validate("");

			Assert.IsTrue(validationResults.IsValid);
			Assert.AreEqual(0, (new List<ValidationResult>(validationResults)).Count);
		}