/// <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);
     }
 }
Exemple #2
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;
            }
        }
        /// <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());
        }
Exemple #4
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);
        }
		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);
		}
Exemple #6
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);
        }
		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);
		}
Exemple #8
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);
        }
Exemple #9
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);
        }
        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);
        }
        /// <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;
        }
Exemple #12
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);
        }
		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);
		}
Exemple #14
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));
     }
 }
Exemple #15
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);
        }
Exemple #16
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);
        }
Exemple #17
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);
        }
        /// <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));
        }
Exemple #19
0
 public void ReturnErrorForUnknownLanguage()
 {
     Validator <string> validator         = new IdentifierValidator("UnknownLanguage", null);
     ValidationResults  validationResults = validator.Validate("valid");
 }
Exemple #20
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));
        }
		public void ReturnErrorForUnknownLanguage()
		{
			Validator<string> validator = new IdentifierValidator("UnknownLanguage", null);
			ValidationResults validationResults = validator.Validate("valid");
		}
		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);
		}
 public void IdentifierIsValidatedAccordingToRules(string identifier, bool valid) =>
 Assert.Equal(valid, IdentifierValidator.Validate(identifier));
Exemple #24
0
 public void ValidIdentifierIsGenerated(string input, string identifier)
 {
     Assert.True(IdentifierCreator.TryCreateIdentifier(input, out var generatedIdentifier));
     Assert.True(IdentifierValidator.Validate(generatedIdentifier));
     Assert.Equal(identifier, generatedIdentifier);
 }
Exemple #25
0
        /// <summary>
        /// Create a pe class-library 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 a class-library 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="storageType">Underlying enum storage-type to use</param>
        /// <returns>Binary pe file containing the generated class-library</returns>
        public static byte[] ExportClassLibrary(
            this EnumDefinition enumDefinition,
            string assemblyName,
            string @namespace       = null,
            StorageType storageType = StorageType.Implicit)
        {
            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);
            }

            // Define assembly and module.
            using (var assemblyDefinition = AssemblyDefinition.CreateAssembly(
                       assemblyName: new AssemblyNameDefinition(assemblyName, new Version(1, 0, 0, 0)),
                       moduleName: $"{assemblyName}.dll",
                       ModuleKind.Dll))
            {
                // Set the module id to a hash of the enum-definition, this way it should be pretty
                // unique while still being deterministic.
                assemblyDefinition.MainModule.Mvid = new Guid(enumDefinition.Get128BitHash());

                // Get the required references.
                var enumUnderlyingType = storageType.GetCecilTypeReference(
                    typeSystem: assemblyDefinition.MainModule.TypeSystem);
                var enumBaseType = new TypeReference(
                    @namespace: "System",
                    name: "Enum",
                    module: assemblyDefinition.MainModule,
                    scope: assemblyDefinition.MainModule.TypeSystem.CoreLibrary);

                // Create type definition for the enum.
                var enumTypeDefinition = new TypeDefinition(
                    @namespace,
                    name: enumDefinition.Identifier,
                    attributes: TypeAttributes.Public | TypeAttributes.Sealed,
                    baseType: enumBaseType);

                // Add the storage field of the enum.
                enumTypeDefinition.Fields.Add(new FieldDefinition(
                                                  name: "value__",
                                                  FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName,
                                                  fieldType: enumUnderlyingType));

                // Add the enum entries.
                foreach (var entry in enumDefinition.Entries)
                {
                    var entryField = new FieldDefinition(
                        name: entry.Name,
                        attributes:
                        FieldAttributes.Public |
                        FieldAttributes.Static |
                        FieldAttributes.Literal |
                        FieldAttributes.HasDefault,
                        fieldType: enumTypeDefinition);

                    // Set the value of the entry.
                    entryField.Constant = storageType.Cast(entry.Value);

                    enumTypeDefinition.Fields.Add(entryField);
                }

                // Add enum to module.
                assemblyDefinition.MainModule.Types.Add(enumTypeDefinition);

                // Write the pe dll file.
                using (var memoryStream = new MemoryStream())
                {
                    // Supply '0' as the timestamp to make the export deterministic.
                    var writerParams = new WriterParameters
                    {
                        Timestamp = 0
                    };

                    assemblyDefinition.Write(memoryStream, writerParams);
                    return(memoryStream.ToArray());
                }
            }
        }
		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);
		}
		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);
		}
		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);
		}
		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);
		}