internal IValidationResult AccessCode(AccessCode accessCode)
        {
            IValidationResult validationResult = new ValidationResult();

            // Do not permit site admins to be added.
            if (accessCode.Role == Role.SiteAdmin)
            {
                validationResult.AddError("Role.Type", "A SiteAdmin may not be added.");
            }

            // Null checks.
            if (accessCode.Description == string.Empty || accessCode.Description == null)
            {
                validationResult.AddError("Description.Null", "Description can not be empty or null.");
            }
            else
            {
                // Range checks.
                if (accessCode.Description.Length > 30)
                {
                    validationResult.AddError("Description.Length", "Description should be less than 30 characters in length.");
                }
            }

            return validationResult;
        }
 public void When_passed_multiple_errors_Should_aggregate_the_error_messages()
 {
     var result = new ValidationResult();
     result.AddError<object>(o => o.GetType(), "foo");
     result.AddError<object>(o => o.GetType(), "bar");
     result.GetAllErrors().Count.ShouldEqual(1);
 }
        internal IValidationResult ShipFit(ShipFit shipFit)
        {
            IValidationResult validationResult = new ValidationResult();

            // Check that the ship fit has a valid account id.
            if (shipFit.AccountId < 0 || shipFit.AccountId > int.MaxValue)
            {
                validationResult.AddError("AccountId.Range_" + shipFit.ShipFitId.ToString(), "AccountId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the int data type.");
            }

            // Null checks.
            if (shipFit.Notes == null)
            {
                validationResult.AddError("Notes.Null", "Notes cannot be null.");
            }

            if (shipFit.Name == null)
            {
                validationResult.AddError("Name.Null", "Name cannot be null.");
            }

            if (shipFit.Role == null)
            {
                validationResult.AddError("Role.Null", "Role cannot be null.");
            }

            return validationResult;
        }
        /// <summary>
        /// Evaluates the rule for the given request.  The <b>RegexRule</b> applies its
        /// regular expression pattern to its specified field in the given request.
        /// </summary>
        /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param>
        /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the
        ///			rule and any validation errors that occurred.</returns>
        public override ValidationResult Evaluate(
            MvcRequest request)
        {
            ValidationResult result = new ValidationResult {
                Passed = false
            };

            string fieldVal = request[Field.EvaluatePropertyValue()];
            // TODO: what if fieldVal is null??  is it valid or not??

            //  if the field value is null and the check is not explicitly for null,
            //  add the error
            if (fieldVal == null) {
                if (this.Pattern == NULL_PATTERN) {
                    result.Passed = true;
                } else {
                    result.AddError(Field, ErrorId);
                }
            } else {
                bool passed = Regex.IsMatch(fieldVal, this.Pattern);

                if (passed) {
                    result.Passed = true;
                } else {
                    result.AddError(Field, ErrorId);
                }
            }

            return result;
        }
        internal IValidationResult ApiKey(IEveDataApiKey apiKeyInfo)
        {
            IValidationResult validationResult = new ValidationResult();

            // Define the bitwise masks for both character and corporation api keys.
            const int charContractMask = 67108864;
            const int corpContractMask = 8388608;
            int checkResult = 0;

            // Perform a bitwise AND to determine if contract access is available on the api key.
            if (apiKeyInfo.Type == EveDataApiKeyType.Character || apiKeyInfo.Type == EveDataApiKeyType.Account)
            {
                checkResult = apiKeyInfo.AccessMask & charContractMask;

                if (checkResult == 0)
                {
                    validationResult.AddError("ApiKey.AccessMask", "A character api key must have 'Contracts' access enabled.");
                }
            }
            else if (apiKeyInfo.Type == EveDataApiKeyType.Corporation)
            {
                checkResult = apiKeyInfo.AccessMask & corpContractMask;

                if (checkResult == 0)
                {
                    validationResult.AddError("ApiKey.AccessMask", "A corporation api key must have 'Contracts' access enabled.");
                }
            }

            return validationResult;
        }
        internal IValidationResult Account(Account account)
        {
            IValidationResult validationResult = new ValidationResult();

            var subscriptionPlan = this.doctrineShipsRepository.GetSubscriptionPlan(account.SubscriptionPlanId);

            // Null checks.
            if (account.Description == string.Empty || account.Description == null)
            {
                validationResult.AddError("Description.Null", "Description can not be empty or null.");
            }
            else
            {
                // Range checks.
                if (account.Description.Length > 30)
                {
                    validationResult.AddError("Description.Length", "Description should be less than 30 characters in length.");
                }
            }

            // Does the subscription plan exist in the database?
            if (subscriptionPlan == null)
            {
                validationResult.AddError("SubscriptionPlan.Null", "The subscription plan does not exist in the database.");
            }

            return validationResult;
        }
 public void Should_process_messages()
 {
     var result = new ValidationResult();
     result.AddError<object>(x => x.ToString(), "Message");
     result.AddError<object>(x => x.ToString(), "Another");
     result.GetErrors<object>(x => x.ToString()).ShouldContain("Message");
     result.GetErrors<object>(x => x.ToString()).ShouldContain("Another");
 }
		public void Format_SeveralErrorsWithSameMessageButDifferentTarges_OutputsOnlyOneMessage()
		{
			// ARRANGE
			var validationResult = new ValidationResult();
			validationResult.AddError("target1", "Error1");
			validationResult.AddError("target2", validationResult.ErrorList[0].ErrorText);

			var formatter = new NumberedListValidationResultFormatter();
			var expectedFormattedString = validationResult.ErrorList[0].ErrorText;

			// ACT
			var actualFormattedString = formatter.Format(validationResult);

			// VERIFY
			Assert.Equal(expectedFormattedString, actualFormattedString);
		}
        internal IValidationResult SalesAgent(SalesAgent salesAgent)
        {
            IValidationResult validationResult = new ValidationResult();

            // Is the salesAgent id valid?
            if (salesAgent.SalesAgentId <= 0 || salesAgent.SalesAgentId > int.MaxValue)
            {
                validationResult.AddError("SalesAgentId.Range", "SalesAgentId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the int data type.");
            }

            // Does the salesAgent already exist in the database?
            if (this.doctrineShipsRepository.GetSalesAgent(salesAgent.SalesAgentId) != null)
            {
                validationResult.AddError("SalesAgentId.Exists", "SalesAgentId already exists in the database.");
            }

            return validationResult;
        }
        internal IValidationResult Component(Component component)
        {
            IValidationResult validationResult = new ValidationResult();

            // Is the component id valid?
            if (component.ComponentId <= 0 || component.ComponentId > int.MaxValue)
            {
                validationResult.AddError("ComponentId.Range_" + component.ComponentId.ToString(), "ComponentId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the int data type.");
            }

            // Does the component already exist in the database?
            if (this.doctrineShipsRepository.GetComponent(component.ComponentId) != null)
            {
                validationResult.AddError("ComponentId.Exists_" + component.ComponentId.ToString(), "ComponentId already exists in the database.");
            }

            return validationResult;
        }
        internal IValidationResult ShipFitComponent(ShipFitComponent shipFitComponent)
        {
            IValidationResult validationResult = new ValidationResult();

            // Check that the ship fit component has a valid quantity.
            if (shipFitComponent.Quantity <= 0 || shipFitComponent.Quantity > long.MaxValue)
            {
                validationResult.AddError("Quantity.Range_" + shipFitComponent.ShipFitComponentId.ToString(), "Quantity can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the long data type.");
            }

            return validationResult;
        }
        internal IValidationResult ApiKey(IEveDataApiKey apiKeyInfo)
        {
            IValidationResult validationResult = new ValidationResult();

            // Check the access mask of the key is correct.
            if (apiKeyInfo.Type == EveDataApiKeyType.Character || apiKeyInfo.Type == EveDataApiKeyType.Account)
            {
                if (apiKeyInfo.AccessMask != 67108864)
                {
                    validationResult.AddError("ApiKey.AccessMask", "A character api key must have an access mask of 67108864 ('Contracts' Only).");
                }
            }
            else if (apiKeyInfo.Type == EveDataApiKeyType.Corporation)
            {
                if (apiKeyInfo.AccessMask != 8388608)
                {
                    validationResult.AddError("ApiKey.AccessMask", "A corporation api key must have an access mask of 8388608 ('Contracts' Only).");
                }
            }

            return validationResult;
        }
        internal IValidationResult Customer(Customer customer)
        {
            IValidationResult validationResult = new ValidationResult();

            // Is the customer id valid?
            if (customer.CustomerId <= 0 || customer.CustomerId > int.MaxValue)
            {
                validationResult.AddError("CustomerId.Range", "CustomerId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the long data type.");
            }

            // Is the customer name valid?
            if (customer.Name == string.Empty || customer.Name == null)
            {
                validationResult.AddError("CustomerName.Null", "CustomerName can not be empty or null.");
            }

            // Does the customer already exist in the database?
            if (this.doctrineShipsRepository.GetCustomer(customer.CustomerId) != null)
            {
                validationResult.AddError("CustomerId.Exists", "CustomerId already exists in the database.");
            }

            return validationResult;
        }
        internal IValidationResult Contract(Contract contract)
        {
            IValidationResult validationResult = new ValidationResult();

            // Is the contract id valid?
            if (contract.ContractId <= 0 || contract.ContractId > long.MaxValue)
            {
                validationResult.AddError("ContractId.Range", "ContractId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the long data type.");
            }

            // Does the contract already exist in the database?
            if (this.doctrineShipsRepository.GetContract(contract.ContractId) != null)
            {
                validationResult.AddError("ContractId.Exists", "ContractId already exists in the database.");
            }

            // Does the ship fit exist in the database?
            if (this.doctrineShipsRepository.GetShipFit(contract.ShipFitId) == null)
            {
               validationResult.AddError("ShipFitId.Exists", "ShipFitId does not exist in the database.");
            }

            return validationResult;
        }
Exemple #15
0
        /// <summary>
        /// Evaluates the rule for the given request.  The <b>OrRule</b> short circuits
        /// on the first successful child rule, with a passed status.
        /// </summary>
        /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param>
        /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the
        ///			rule and any validation errors that occurred.</returns>
        public override ValidationResult Evaluate(
            MvcRequest request)
        {
            ValidationResult result = new ValidationResult { Passed = false };

            // TODO: if cnt is 0 should we return true or false??
            int cnt = children.Count;
            for (int k = 0; k < cnt && !result.Passed; k++) {
                IValidationRule rule = children[k];
                        //  evaluate the child rule
                ValidationResult childResult = rule.Evaluate(request);
                        //  clear out any previous validation errors
                result.ClearErrors();
                        //  if the child rule passed, set this rule to passed,
                        //  if not, add the errors from the child to the OrRule's result
                if (childResult.Passed) {
                    result.Passed = true;
                } else {
                    result.AddErrors(childResult.Errors);

                    if (rule.StopOnFail || childResult.StopProcessing) {
                        result.StopProcessing = true;
                        break;
                    }
                }
            }

                    //  if the OrRule did not pass and the is a specific error identified
                    //  for the OrRule, replace any errors from the children with the one
                    //  for the OrRule
            if (!result.Passed && (ErrorId != 0)) {
                result.ClearErrors();
                result.AddError(Field, ErrorId);
            }

            return result;
        }
Exemple #16
0
        public void ShouldCreateNewColumnsWithErrors()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddWorksheetParser <FakeClass>(x => x.WithParser <ClosedXmlParser <FakeClass> >().WithMap <MyWorksheetMap>());

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var expectedItens = new List <FakeClass>
            {
                FakeClass.CreateItem(),
                FakeClass.CreateItem(false, false, false),
                FakeClass.CreateItem(false, false, true)
            };

            var parser = serviceProvider.GetService <WorksheetParser <FakeClass> >();

            expectedItens.ForEach(x => x.Bonus *= 0.1M);
            var validationResult = new ValidationResult <FakeClass>();
            var error            = new Error("Field TX_NAME can´t not be null", 3, 2);

            validationResult.AddError(error);
            validationResult.AddItem(expectedItens.First());
            validationResult.AddItem(expectedItens.Last());

            var headers = new MyWorksheetMap().GetFields().Select(s => s.Name).ToList();

            using var worksheet = CreateStream(expectedItens, headers);
            var itens = parser.Parse(worksheet, worksheetName);

            using var streamWithErros = parser.WriteErrorsWithSummary(worksheet, worksheetName, itens.Errors);

            using var workbookWithErrors = new XLWorkbook(streamWithErros);
            var reader = new ClosedXmlReader(workbookWithErrors, worksheetName);

            reader.CountColumns().Should().Be(headers.Count() + 1);
        }
Exemple #17
0
        public Task <ValidationResult> ValidateAsync(UnlockUserCommand item)
        {
            var result = new ValidationResult();

            if (string.IsNullOrEmpty(item.Email))
            {
                result.AddError(nameof(item.Email), "Enter an email address");
            }
            if (!string.IsNullOrEmpty(item.Email) && !IsEmailValid(item.Email))
            {
                result.AddError(nameof(item.Email), "Enter a valid email address");
            }
            if (string.IsNullOrEmpty(item.UnlockCode))
            {
                result.AddError(nameof(item.UnlockCode), "Enter an unlock code");
            }

            if (!string.IsNullOrEmpty(item.Email) && !string.IsNullOrEmpty(item.UnlockCode) && item.User == null)
            {
                result.AddError(nameof(item.UnlockCode), "Unlock code is not correct");
            }

            if (!result.IsValid())
            {
                return(Task.FromResult(result));
            }


            var matchingUnlockCode = item.User.SecurityCodes?.OrderByDescending(sc => sc.ExpiryTime)
                                     .FirstOrDefault(sc => sc.Code.Equals(item.UnlockCode, StringComparison.CurrentCultureIgnoreCase) &&
                                                     sc.CodeType == Domain.SecurityCodeType.UnlockCode);

            if (matchingUnlockCode == null)
            {
                result.AddError(nameof(item.UnlockCode), "Unlock code is not correct");
            }
            else if (matchingUnlockCode.ExpiryTime < DateTime.UtcNow && ConfigurationManager.AppSettings["UseStaticCodeGenerator"].Equals("false", StringComparison.CurrentCultureIgnoreCase))
            {
                result.AddError(nameof(item.UnlockCode), "Unlock code has expired");
                return(Task.FromResult(result));
            }

            return(Task.FromResult(result));
        }
Exemple #18
0
        public override ValidationResult Validate(ResetPasswordViewModel viewModel)
        {
            var validationResult = new ValidationResult <ResetPasswordViewModel>();

            if (string.IsNullOrWhiteSpace(viewModel.Token))
            {
                validationResult.AddError(
                    x => x.Token,
                    translationManager.GetTranslationLabel(LanguageId, "Dashboard:Admin:EmptyToken"));
            }

            if (!string.Equals(viewModel.Password, viewModel.PasswordCheck))
            {
                validationResult.AddError(
                    x => x.Password,
                    translationManager.GetTranslationLabel(LanguageId, "Dashboard:Admin:PasswordMismatch"));
                validationResult.AddError(
                    x => x.PasswordCheck,
                    translationManager.GetTranslationLabel(LanguageId, "Dashboard:Admin:PasswordMismatch"));
            }

            if (string.IsNullOrWhiteSpace(viewModel.Password))
            {
                validationResult.AddError(
                    x => x.Password,
                    translationManager.GetTranslationLabel(LanguageId, "Dashboard:Admin:EmptyPassword"));
            }

            if (string.IsNullOrWhiteSpace(viewModel.PasswordCheck))
            {
                validationResult.AddError(
                    x => x.PasswordCheck,
                    translationManager.GetTranslationLabel(LanguageId, "Dashboard:Admin:EmptyPassword"));
            }

            if (PasswordStrengthCheck.GetPasswordStrength(viewModel.Password) != PasswordStrength.VeryStrong)
            {
                validationResult.AddError(
                    m => m.Password,
                    translationManager.GetTranslationLabel(LanguageId, "Dashboard:Admin:WeakPassword"));
            }

            return(validationResult);
        }
Exemple #19
0
        public async Task <int> RegisterUser(UserRegistrationDto userDto)
        {
            User domainUser = Mapper.Map <User>(userDto);

            domainUser.OwnerId = UserId;
            IdentityResult result = await _identityUserManager
                                    .CreateAsync(domainUser, userDto.Password);

            if (!result.Succeeded)
            {
                IValidationResult validation = new ValidationResult();

                foreach (IdentityError error in result.Errors)
                {
                    validation.AddError(error.Code, error.Description);
                }

                throw new ValidationException(validation);
            }

            User userInfo = await _identityUserManager.FindByEmailAsync(userDto.Email);

            return(userInfo.Id);
        }
Exemple #20
0
        /// <summary>
        /// Updates a doctrine for a particular account.
        /// </summary>
        /// <param name="doctrine">A partially populated doctrine object to be updated.</param>
        /// <returns>Returns a validation result object.</returns>
        internal IValidationResult UpdateDoctrine(Doctrine doctrine)
        {
            IValidationResult validationResult = new ValidationResult();

            var existingDoctrine = this.doctrineShipsRepository.GetDoctrine(doctrine.DoctrineId);

            if (existingDoctrine != null)
            {
                if (existingDoctrine.AccountId != doctrine.AccountId)
                {
                    validationResult.AddError("Doctrine.Permission", "The doctrine being modified does not belong to the requesting account.");
                }
                else
                {
                    // Map the updates to the existing doctrine.
                    existingDoctrine.Name        = doctrine.Name;
                    existingDoctrine.Description = doctrine.Description;
                    existingDoctrine.ImageUrl    = doctrine.ImageUrl;
                    existingDoctrine.IsOfficial  = doctrine.IsOfficial;
                    existingDoctrine.IsDormant   = doctrine.IsDormant;
                    existingDoctrine.LastUpdate  = DateTime.UtcNow;

                    // Validate the doctrine updates.
                    validationResult = this.doctrineShipsValidation.Doctrine(existingDoctrine);
                    if (validationResult.IsValid == true)
                    {
                        // Update the existing record, save and log.
                        this.doctrineShipsRepository.UpdateDoctrine(existingDoctrine);
                        this.doctrineShipsRepository.Save();
                        logger.LogMessage("Doctrine '" + existingDoctrine.Name + "' Successfully Updated For Account Id: " + existingDoctrine.AccountId, 2, "Message", MethodBase.GetCurrentMethod().Name);
                    }
                }
            }

            return(validationResult);
        }
Exemple #21
0
        private static void ValidateApprenticeship(ValidationResult result, IncentiveApplicationApprenticeshipDto apprenticeship)
        {
            if (apprenticeship.ApprenticeshipId == default)
            {
                result.AddError("Apprenticeship.ApprenticeshipId", "Is not set");
            }

            if (apprenticeship.DateOfBirth == default)
            {
                result.AddError("Apprenticeship.DateOfBirth", "Is not set");
            }

            if (apprenticeship.PlannedStartDate == default)
            {
                result.AddError("Apprenticeship.PlannedStartDate", "Is not set");
            }

            if (apprenticeship.ULN == default)
            {
                result.AddError("Apprenticeship.ULN", "Is not set");
            }

            if (string.IsNullOrEmpty(apprenticeship.FirstName))
            {
                result.AddError("Apprenticeship.FirstName", "Is not set");
            }

            if (string.IsNullOrEmpty(apprenticeship.LastName))
            {
                result.AddError("Apprenticeship.LastName", "Is not set");
            }

            if (apprenticeship.UKPRN == default)
            {
                result.AddError("Apprenticeship.UKPRN", "Is not set");
            }
        }
        internal IValidationResult Doctrine(Doctrine doctrine)
        {
            IValidationResult validationResult = new ValidationResult();

            // Check that the doctrine has a valid account id.
            if (doctrine.AccountId < 0 || doctrine.AccountId > int.MaxValue)
            {
                validationResult.AddError("AccountId.Range", "AccountId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the int data type.");
            }

            // Null & empty checks.
            if (doctrine.Name == null || doctrine.Name == string.Empty)
            {
                validationResult.AddError("Name.Null", "Name cannot be null or empty.");
            }

            if (doctrine.Description == null)
            {
                validationResult.AddError("Description.Null", "Description cannot be null.");
            }

            if (doctrine.ImageUrl == null)
            {
                validationResult.AddError("ImageUrl.Null", "ImageUrl cannot be null.");
            }

            if (doctrine.LastUpdate == null)
            {
                validationResult.AddError("LastUpdate.Null", "LastUpdate cannot be null.");
            }

            // Is this a https url?
            if (doctrine.ImageUrl != string.Empty && doctrine.ImageUrl.Length >= 5)
            {
                if (doctrine.ImageUrl.Substring(0, 5) != "https")
                {
                    validationResult.AddError("ImageUrl.Https", "ImageUrl must start with https. Please use an image hosting service such as imgur that supports https.");
                }
            }

            return(validationResult);
        }
        internal IValidationResult Doctrine(Doctrine doctrine)
        {
            IValidationResult validationResult = new ValidationResult();

            // Check that the doctrine has a valid account id.
            if (doctrine.AccountId < 0 || doctrine.AccountId > int.MaxValue)
            {
                validationResult.AddError("AccountId.Range", "AccountId can not be less than or equal to 0. Also, the upper limit cannot exceed the max value of the int data type.");
            }

            // Null & empty checks.
            if (doctrine.Name == null || doctrine.Name == string.Empty )
            {
                validationResult.AddError("Name.Null", "Name cannot be null or empty.");
            }

            if (doctrine.Description == null)
            {
                validationResult.AddError("Description.Null", "Description cannot be null.");
            }

            if (doctrine.ImageUrl == null)
            {
                validationResult.AddError("ImageUrl.Null", "ImageUrl cannot be null.");
            }

            if (doctrine.LastUpdate == null)
            {
                validationResult.AddError("LastUpdate.Null", "LastUpdate cannot be null.");
            }

            // Is this a https url?
            if (doctrine.ImageUrl != string.Empty && doctrine.ImageUrl.Length >= 5)
            {
                if (doctrine.ImageUrl.Substring(0, 5) != "https")
                {
                    validationResult.AddError("ImageUrl.Https", "ImageUrl must start with https. Please use an image hosting service such as imgur that supports https.");
                }
            }

            return validationResult;
        }
        public Task <ValidationResult> ValidateAsync(CreateCourseDemandCommand item)
        {
            var result = new ValidationResult();

            if (string.IsNullOrEmpty(item.CourseDemand.OrganisationName))
            {
                result.AddError(nameof(item.CourseDemand.OrganisationName));
            }
            if (string.IsNullOrEmpty(item.CourseDemand.ContactEmailAddress))
            {
                result.AddError(nameof(item.CourseDemand.ContactEmailAddress));
            }
            else
            {
                try
                {
                    var emailAddress = new MailAddress(item.CourseDemand.ContactEmailAddress);
                    if (!emailAddress.Address.Equals(item.CourseDemand.ContactEmailAddress, StringComparison.CurrentCultureIgnoreCase))
                    {
                        result.AddError(nameof(item.CourseDemand.ContactEmailAddress));
                    }
                }
                catch (FormatException)
                {
                    result.AddError(nameof(item.CourseDemand.ContactEmailAddress));
                }
            }

            if (item.CourseDemand.Course.Id == 0 || item.CourseDemand.Course.Level == 0 || string.IsNullOrEmpty(item.CourseDemand.Course.Title) || string.IsNullOrEmpty(item.CourseDemand.Course.Route))
            {
                result.AddError(nameof(item.CourseDemand.Course));
            }

            if (item.CourseDemand.Location.Lat == 0 || item.CourseDemand.Location.Lon == 0 ||
                string.IsNullOrEmpty(item.CourseDemand.Location.Name))
            {
                result.AddError(nameof(item.CourseDemand.Location));
            }

            return(Task.FromResult(result));
        }
Exemple #25
0
        public Task <ValidationResult> ValidateAsync(PasswordResetCommand item)
        {
            var validationResult = new ValidationResult();

            var resetCode = item.User?.SecurityCodes?.OrderByDescending(sc => sc.ExpiryTime)
                            .FirstOrDefault(sc => sc.Code.Equals(item.PasswordResetCode, StringComparison.InvariantCultureIgnoreCase) &&
                                            sc.CodeType == Domain.SecurityCodeType.PasswordResetCode);

            if (resetCode == null)
            {
                validationResult.AddError(nameof(item.PasswordResetCode), "Reset code is invalid");
            }
            else if (resetCode.ExpiryTime < DateTime.UtcNow && ConfigurationManager.AppSettings["UseStaticCodeGenerator"].Equals("false", StringComparison.CurrentCultureIgnoreCase))
            {
                validationResult.AddError(nameof(item.PasswordResetCode), "Reset code has expired");
            }

            if (string.IsNullOrEmpty(item.Password))
            {
                validationResult.AddError(nameof(item.Password), "Enter a password");
            }
            else if (!_passwordService.CheckPasswordMatchesRequiredComplexity(item.Password))
            {
                validationResult.AddError(nameof(item.Password), "Password requires upper and lowercase letters, a number and at least 8 characters");
            }

            if (string.IsNullOrEmpty(item.ConfirmPassword))
            {
                validationResult.AddError(nameof(item.ConfirmPassword), "Re-type password");
            }
            else if (!string.IsNullOrEmpty(item.Password) && !item.ConfirmPassword.Equals(item.Password))
            {
                validationResult.AddError(nameof(item.ConfirmPassword), "Passwords don’t match");
            }


            return(Task.FromResult(validationResult));
        }
Exemple #26
0
        public Task <ValidationResult> Validate(PausePaymentsCommand item)
        {
            var result = new ValidationResult();

            if (item.ULN == default)
            {
                result.AddError("ULN", "Is not set");
            }

            if (item.AccountLegalEntityId == default)
            {
                result.AddError("AccountLegalEntityId", "Is not set");
            }

            if (item.ServiceRequestId == default)
            {
                result.AddError("ServiceRequestId", "Is not set");
            }

            if (item.DateServiceRequestTaskCreated == default)
            {
                result.AddError("DateServiceRequestTaskCreated", "Is not set");
            }

            if (string.IsNullOrWhiteSpace(item.DecisionReferenceNumber))
            {
                result.AddError("DecisionReferenceNumber", "Is not set");
            }

            if (item.Action == default)
            {
                result.AddError("Action", "Is not set (it must be Pause or Resume)");
            }

            return(Task.FromResult(result));
        }
Exemple #27
0
        /// <summary>
        /// Validate file
        /// </summary>
        /// <param name="filePath">Path to file</param>
        /// <returns>Result of validation, has state and messages <see cref="ValidationResult"/></returns>
        public ValidationResult Validate(string filePath)
        {
            var fileName = filePath.Split('\\').Last();

            CrozzleLogger.InitLog(fileName, false);

            Reset();
            var result = new ValidationResult();

            try
            {
                LoadFile(filePath);
            }
            catch (Exception ex)
            {
                result.AddError(ex.Message);
                return(result);
            }

            var maxRows    = 0;
            var maxColumns = 0;

            foreach (var @string in file)
            {
                if (!_headerIsSet)
                {
                    //6 values in string
                    var header = @string.Split(',');
                    var headerDataCountIsOk = header.Length == CROZZLE_HEADER_LENGTH;
                    if (!headerDataCountIsOk)
                    {
                        var message = string.Format(NOT_CORRECT_FORMAT_MSG, "Header(first row)");
                        CrozzleLogger.Log(message);
                        result.AddCriticalError(message);
                        _headerIsSet = true;
                        continue;
                    }

                    //EASY, MEDIUM or HARD
                    var difficulty     = header[0];
                    var difficultyIsOk = difficulty.Equals(EASY_DIFFICULTY_PATTERN) || difficulty.Equals(MEDIUM_DIFFICULTY_PATTERN) ||
                                         difficulty.Equals(HARD_DIFFICULTY_PATTERN);
                    if (!difficultyIsOk)
                    {
                        var message = string.Format(DIFFICULTY_IS_INCORRECT_MSG, EASY_DIFFICULTY_PATTERN, MEDIUM_DIFFICULTY_PATTERN,
                                                    HARD_DIFFICULTY_PATTERN, difficulty);
                        CrozzleLogger.Log(message);
                        result.AddCriticalError(message);
                    }

                    //for all numberics check
                    int tmp;


                    //numerics
                    //number of words
                    var numberOfWords     = header[1];
                    var numberOfWordsIsOk = int.TryParse(numberOfWords, out tmp) && (tmp >= NUMBER_OF_WORDS_MIN || tmp <= NUMBER_OF_WORDS_MAX);
                    if (!numberOfWordsIsOk)
                    {
                        var message = string.Format(NUMBER_IS_INCORRECT_MSG, "words", $"[{NUMBER_OF_WORDS_MIN}..{NUMBER_OF_WORDS_MAX}]", numberOfWords);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    //number of rows
                    var numberOfRows     = header[2];
                    var numberOfRowsIsOk = int.TryParse(numberOfRows, out tmp) && (tmp >= NUMBER_OF_ROWS_MIN || tmp <= NUMBER_OF_ROWS_MAX);
                    maxRows = tmp;
                    if (!numberOfRowsIsOk)
                    {
                        var message = string.Format(NUMBER_IS_INCORRECT_MSG, "rows", $"[{NUMBER_OF_ROWS_MIN}..{NUMBER_OF_ROWS_MAX}]", numberOfRows);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    //number of columns
                    var numberOfColumns     = header[3];
                    var numberOfColumnsIsOk = int.TryParse(numberOfColumns, out tmp) && (tmp >= NUMBER_OF_COLLUMNS_MIN || tmp <= NUMBER_OF_COLLUMNS_MAX);
                    maxColumns = tmp;
                    if (!numberOfColumnsIsOk)
                    {
                        var message = string.Format(NUMBER_IS_INCORRECT_MSG, "columns", $"[{NUMBER_OF_COLLUMNS_MIN}..${NUMBER_OF_COLLUMNS_MAX}]", numberOfColumns);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    //number of horizontal words
                    var numberOfHorizontalWords     = header[4];
                    var numberOfHorizontalWordsIsOk = int.TryParse(numberOfHorizontalWords, out tmp) && tmp > ZERO;
                    if (!numberOfHorizontalWordsIsOk)
                    {
                        var message = string.Format(NUMBER_IS_INCORRECT_MSG2, "horizontal words", numberOfHorizontalWords);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }


                    //number of vertical words
                    var numberOfVerticalWords     = header[5];
                    var numberOfVerticalWordsIsOk = int.TryParse(numberOfVerticalWords, out tmp) && tmp > ZERO;
                    if (!numberOfVerticalWordsIsOk)
                    {
                        var message = string.Format(NUMBER_IS_INCORRECT_MSG2, "vertical words", numberOfVerticalWords);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    _headerIsSet = true;
                    continue;
                }


                if (!_wordsDictionaryIsSet)
                {
                    var wordsList = @string.Split(',');

                    foreach (var word in wordsList)
                    {
                        if (!_words.ContainsKey(word))
                        {
                            _words.Add(word, 0);
                        }
                        _words[word]++;
                    }

                    var allWordsAreUnique = !_words.Any(word => word.Value > 1);
                    if (!allWordsAreUnique)
                    {
                        var notUniqueWordsList = string.Join(",", _words.Where(word => word.Value > 1)
                                                             .Select(word => word.Key));
                        var message = string.Format(NOT_UNIQUE_WORDS_MSG, notUniqueWordsList);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    _wordsDictionaryIsSet = true;
                    continue;
                }

                //check words
                {
                    int tmp;
                    _index++;

                    var wordPreferences     = @string.Split(',');
                    var wordPreferencesIsOk = wordPreferences.Length == ARGUMENT_NUMBER_COUNT;
                    if (!wordPreferencesIsOk)
                    {
                        var message = string.Format(NOT_CORRECT_DATA_MSG, $"one of words preference, row number - {_index}", ARGUMENT_NUMBER_COUNT, wordPreferences.Length);
                        CrozzleLogger.Log(message);
                        result.AddCriticalError(message);
                        continue;
                    }

                    var orientation     = wordPreferences[0];
                    var orientationIsOk = orientation.Equals(HORIZONTAL_ORIENTATION_PATTERN) || orientation.Equals(VERTICAL_ORIENTATION_PATTERN);
                    if (!orientationIsOk)
                    {
                        var message = string.Format(NOT_CORRECT_DATA_MSG, $"orientation preferences, row number - {_index}",
                                                    $"{HORIZONTAL_ORIENTATION_PATTERN} or {VERTICAL_ORIENTATION_PATTERN}", orientation);
                        CrozzleLogger.Log(message);
                        result.AddCriticalError(message);
                    }

                    var rowIndex     = wordPreferences[1];
                    var rowIndexIsOk = int.TryParse(rowIndex, out tmp);
                    var rowInt       = tmp;
                    if (!rowIndexIsOk)
                    {
                        var message = string.Format(NOT_CORRECT_DATA_MSG, $"rows index preferences, row number - {_index}", "integer value", rowIndex);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    if (rowInt > maxRows)
                    {
                        var message = string.Format($"Incorrect data in crozzle preferences, max rows count is {maxRows}, but word index was - {rowInt}");
                        CrozzleLogger.Log(message);
                        result.AddCriticalError(message);
                    }

                    var columnIndex     = wordPreferences[2];
                    var columnIndexIsOk = int.TryParse(columnIndex, out tmp);
                    var columnInt       = tmp;
                    if (!columnIndexIsOk)
                    {
                        var message = string.Format(NOT_CORRECT_DATA_MSG, $"column index preferences, row number - {_index}", "integer value",
                                                    columnIndex);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    if (columnInt > maxColumns)
                    {
                        var message =
                            string.Format($"Incorrect data in crozzle preferences, max columns count is {maxColumns}, but word column index was - {columnInt}");
                        CrozzleLogger.Log(message);
                        result.AddCriticalError(message);
                    }

                    var actualWord     = wordPreferences[3];
                    var regex          = new Regex(WORD_REGEX_PATTERN);
                    var actualWordIsOk = regex.IsMatch(actualWord) && _words.ContainsKey(actualWord);
                    if (!actualWordIsOk)
                    {
                        var message = string.Format(NOT_CORRECT_DATA_MSG, $"words to view, word is not ok, row number - {_index}",
                                                    "word, that contains in dictionary", actualWord);
                        CrozzleLogger.Log(message);
                        result.AddError(message);
                    }

                    if (!_inseredWords.ContainsKey(actualWord))
                    {
                        _inseredWords.Add(actualWord, ZERO);
                    }
                    _inseredWords[actualWord]++;
                }
            }

            if (_inseredWords.Any(word => word.Value > 1))
            {
                var notUniqueWordsList = string.Join(",", _inseredWords.Where(word => word.Value > ISUNIQUE).Select(word => word.Key));
                var message            = string.Format(MULTIPLE_INSERTED_WORDS_MSG, notUniqueWordsList);
                CrozzleLogger.Log(message);
                result.AddError(message);
            }

            CrozzleLogger.EndLog(fileName, false, result.IsValid);

            return(result);
        }
        public void AddErrorRequiresValidationError()
        {
            var result = new ValidationResult <StringTestSubject>(new StringTestSubject());

            result.AddError(null);
        }
        internal IValidationResult SettingProfile(SettingProfile settingProfile)
        {
            IValidationResult validationResult = new ValidationResult();

            var existingSettingProfile = this.doctrineShipsRepository.GetSettingProfileReadOnly(settingProfile.SettingProfileId);

            // Does the setting profile exist in the database?
            if (existingSettingProfile == null)
            {
                validationResult.AddError("SettingProfile.Null", "The setting profile being modified does not exist in the database.");
            }
            else
            {
                // Does the setting profile being modified belong to the requesting account?
                if (existingSettingProfile.AccountId != settingProfile.AccountId)
                {
                    validationResult.AddError("SettingProfile.Permission", "The setting profile being modified does not belong to the requesting account.");
                }
            }

            // Null checks.
            if (settingProfile.TwitterHandle == null)
            {
                validationResult.AddError("TwitterHandle.Null", "TwitterHandle cannot be null.");
            }

            // Regex checks.
            if (settingProfile.TwitterHandle != null)
            {
                if (!Regex.Match(settingProfile.TwitterHandle, "^@(\\w){1,15}$").Success)
                {
                    validationResult.AddError("TwitterHandle.Format", "Invalid twitter handle.");
                }
            }

            // Range checks.
            if (settingProfile.BrokerPercentage < 0 || settingProfile.BrokerPercentage > 100)
            {
                validationResult.AddError("BrokerPercentage.Range", "BrokerPercentage is outside of expected ranges.");
            }

            if (settingProfile.SalesTaxPercentage < 0 || settingProfile.SalesTaxPercentage > 100)
            {
                validationResult.AddError("SalesTaxPercentage.Range", "SalesTaxPercentage is outside of expected ranges.");
            }

            if (settingProfile.ContractMarkupPercentage < 0 || settingProfile.ContractMarkupPercentage > 100)
            {
                validationResult.AddError("ContractMarkupPercentage.Range", "ContractMarkupPercentage is outside of expected ranges.");
            }

            if (settingProfile.ContractBrokerFee < 0 || settingProfile.ContractBrokerFee > double.MaxValue)
            {
                validationResult.AddError("ContractBrokerFee.Range", "ContractBrokerFee is outside of expected ranges.");
            }

            if (settingProfile.ShippingCostPerM3 < 0 || settingProfile.ShippingCostPerM3 > double.MaxValue)
            {
                validationResult.AddError("ShippingCostPerM3.Range", "ShippingCostPerM3 is outside of expected ranges.");
            }

            if (settingProfile.BuyStationId < 0 || settingProfile.BuyStationId > int.MaxValue)
            {
                validationResult.AddError("BuyStationId.Range", "BuyStationId is outside of expected ranges.");
            }

            if (settingProfile.SellStationId < 0 || settingProfile.SellStationId > int.MaxValue)
            {
                validationResult.AddError("SellStationId.Range", "SellStationId is outside of expected ranges.");
            }

            if (settingProfile.AlertThreshold < 0 || settingProfile.AlertThreshold > int.MaxValue)
            {
                validationResult.AddError("AlertThreshold.Range", "AlertThreshold is outside of expected ranges.");
            }

            return validationResult;
        }
Exemple #30
0
        public override ValidationResult Validate(UserViewModel viewModel)
        {
            var validationResult = new ValidationResult <UserViewModel>();

            if (string.IsNullOrWhiteSpace(viewModel.Firstname))
            {
                validationResult.AddError(m => m.Firstname,
                                          translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:FirstnameEmpty"));
            }

            if (string.IsNullOrWhiteSpace(viewModel.Lastname))
            {
                validationResult.AddError(m => m.Lastname,
                                          translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:LastnameEmpty"));
            }

            if (viewModel.Id == default(int))
            {
                if (string.IsNullOrWhiteSpace(viewModel.Email))
                {
                    validationResult.AddError(m => m.Email,
                                              translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:EmailEmpty"));
                }

                var existingUser = userProvider.GetUserByEmail(viewModel.Email);

                if (!existingUser.IsNullOrDefault())
                {
                    validationResult.AddError(m => m.Email,
                                              translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:EmailAlreadyExists"));
                }

                return(validationResult);
            }

            var editedUser = userProvider.GetUserById(viewModel.Id);

            if (editedUser.IsNullOrDefault())
            {
                validationResult.AddError(m => m.Email,
                                          translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:UserNotFound"));

                return(validationResult);
            }

            if (Actions.Contains(Permissions.GetActionKey(Module.Dashboard, Type.User, Action.Edit)))
            {
                if (string.IsNullOrWhiteSpace(viewModel.Email))
                {
                    validationResult.AddError(m => m.Email,
                                              translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:EmailEmpty"));
                }
                else if (!ValidEmail(viewModel.Email))
                {
                    validationResult.AddError(m => m.Email,
                                              translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:EmailNotValid"));
                }
                else
                {
                    var existingUser = userProvider.GetUserByEmail(viewModel.Email);

                    if (!existingUser.IsNullOrDefault() && existingUser.Id != editedUser.Id)
                    {
                        validationResult.AddError(m => m.Email,
                                                  translationManager.GetTranslationLabel(LanguageId, "Dashboard:User:EmailAlreadyExists"));
                    }
                }
            }
            else
            {
                viewModel.Email = editedUser.Email;
            }

            return(validationResult);
        }
Exemple #31
0
        public ValidationResult Validate(CreateCommitmentCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var result = new ValidationResult();

            if (command.Commitment == null)
            {
                result.AddError(nameof(command.Commitment), $"{nameof(command.Commitment)} must have a value.");
                return(result);
            }

            if (command.Commitment.EmployerAccountId <= 0)
            {
                result.AddError(nameof(command.Commitment.EmployerAccountId), $"{nameof(command.Commitment.EmployerAccountId)} has an invalid value.");
            }

            if (string.IsNullOrWhiteSpace(command.Commitment.LegalEntityId))
            {
                result.AddError(nameof(command.Commitment.LegalEntityId), $"{nameof(command.Commitment.LegalEntityId)} has an invalid value.");
            }

            if (string.IsNullOrWhiteSpace(command.Commitment.LegalEntityName))
            {
                result.AddError(nameof(command.Commitment.LegalEntityName), $"{nameof(command.Commitment.LegalEntityName)} must have a value.");
            }

            if (command.Commitment.ProviderId != 0 || !string.IsNullOrWhiteSpace(command.Commitment.ProviderName))
            {
                if (command.Commitment.ProviderId <= 0)
                {
                    result.AddError(nameof(command.Commitment.ProviderId), $"{nameof(command.Commitment.ProviderId)} has an invalid value.");
                }

                if (string.IsNullOrWhiteSpace(command.Commitment.ProviderName))
                {
                    result.AddError(nameof(command.Commitment.ProviderName), $"{nameof(command.Commitment.ProviderName)} must have a value.");
                }
            }

            if (command.Commitment.EmployerLastUpdateInfo == null)
            {
                result.AddError(nameof(command.Commitment.EmployerLastUpdateInfo), $"{nameof(command.Commitment.EmployerLastUpdateInfo)} must have a value.");
                return(result);
            }

            if (string.IsNullOrWhiteSpace(command.Commitment.EmployerLastUpdateInfo.Name))
            {
                result.AddError(nameof(command.Commitment.EmployerLastUpdateInfo.Name), $"{nameof(command.Commitment.EmployerLastUpdateInfo.Name)} must have a value.");
            }

            if (string.IsNullOrWhiteSpace(command.Commitment.EmployerLastUpdateInfo.EmailAddress))
            {
                result.AddError(nameof(command.Commitment.EmployerLastUpdateInfo.EmailAddress), $"{nameof(command.Commitment.EmployerLastUpdateInfo.EmailAddress)} must have a value.");
            }

            if (command.UserId == null)
            {
                result.AddError(nameof(command.UserId), $"{nameof(command.UserId)} must have a value.");
            }

            return(result);
        }
Exemple #32
0
 public void AddError(string errorText)
 {
     ValidationResult.AddError(errorText);
 }
        /// <summary>
        /// Проверка файла с подписью на валидность подписи
        /// </summary>
        /// <returns>Сообщения (или ошибки) о проверки подписи</returns>
        public ValidationResult Verify()
        {
            var result = new ValidationResult();

            if (this.Signature == null)
            {
                result.AddError("Отсутствует файл с подписью!");
                return result;
            }

            //Создаем пакет с подписью для проверки самой подписи
            SignedCms cms = null;

            if (this.Detached)
            {//отсоединенная подпись

                //создаем контейнер с оригинальными данными, подпись которых будет проверяться
                ContentInfo content = new ContentInfo(this.Original);

                //формируем пакет с оригинальными данными и параметрами подписи
                cms = new SignedCms(content, true);
            }
            else
            {// присоединенная подпись

                //формируем пустой пакет с данными
                //так как в случае присоединенной подписи
                //данные содержатся в самом подписанном файле
                cms = new SignedCms();
            }

            try
            {
                //декодируем файл, содержащий подпись
                //если вылетает ошибка - значит подпись не верна!!!
                cms.Decode(this.Signature);

                //возможно, информация о подписаниях отсутствует
                if (cms.SignerInfos.Count <= 0)
                {
                    result.AddError("Нет информации о подписях (возможно файл не подписан)");
                    return result;
                }

                result.AddInfo("Электронная Подпись Вернa.");
                result.AddNewLine();
                result.Add("Файл подписан следующим(и) сертификатом(и):");

                foreach (SignerInfo si in cms.SignerInfos)
                {
                    var certificate = new Certificate(si.Certificate);
                    if (_certificate == null)
                        _certificate = certificate;

                    result.AddNewLine();
                    result.Add(certificate.SerialNumber + " [" + certificate.Thumbprint + "]");
                    result.Add(certificate.SubjectCommonName);

                    //дергаем время подписания документа текущей подписью
                    for (int i = 0; i < si.SignedAttributes.Count; i++)
                    {
                        if (si.SignedAttributes[i].Oid.Value == "1.2.840.113549.1.9.5") // Oid время подписания
                        {
                            Pkcs9SigningTime pkcs9_time = new Pkcs9SigningTime(si.SignedAttributes[i].Values[0].RawData);
                            result.Add("Дата и Время подписания:  " + pkcs9_time.SigningTime.ToString());
                            break;
                        }
                    }
                }
            }
            catch
            {
                result.AddError("Подпись НЕ верна!");
            }

            return result;
        }
        public async Task <ValidationResult> ValidateAsync(CacheReservationEmployerCommand command)
        {
            var result = new ValidationResult();

            if (command.Id == Guid.Empty)
            {
                result.AddError(nameof(command.Id));
            }

            if (command.AccountId == default(long))
            {
                result.AddError(nameof(command.AccountId));
            }
            else
            {
                var accountFundingRulesApiResponse = await _rulesService.GetAccountFundingRules(command.AccountId);

                if (accountFundingRulesApiResponse.GlobalRules.Any(c => c != null && c.RuleType == GlobalRuleType.ReservationLimit) &&
                    accountFundingRulesApiResponse.GlobalRules.Count(c => c.RuleType == GlobalRuleType.ReservationLimit) > 0)
                {
                    result.FailedRuleValidation = true;
                }

                var globalRulesApiResponse = await _rulesService.GetFundingRules();

                if (globalRulesApiResponse.GlobalRules != null && globalRulesApiResponse.GlobalRules.Any(c => c != null && c.RuleType == GlobalRuleType.FundingPaused) &&
                    globalRulesApiResponse.GlobalRules.Count(c => c.RuleType == GlobalRuleType.FundingPaused) > 0)
                {
                    result.FailedGlobalRuleValidation = true;
                }

                // eoi
                var queryResult = await _mediator.Send(new GetLegalEntitiesQuery
                {
                    AccountId = command.AccountId
                });

                if (queryResult.AccountLegalEntities.Any(entity =>
                                                         !entity.IsLevy &&
                                                         entity.AgreementType != AgreementType.NonLevyExpressionOfInterest))
                {
                    result.FailedEoiCheck = true;
                    return(result);
                }
            }

            if (command.AccountLegalEntityId == default(long))
            {
                result.AddError(nameof(command.AccountLegalEntityId));
            }

            if (string.IsNullOrWhiteSpace(command.AccountLegalEntityName))
            {
                result.AddError(nameof(command.AccountLegalEntityName));
            }

            if (string.IsNullOrWhiteSpace(command.AccountLegalEntityPublicHashedId))
            {
                result.AddError(nameof(command.AccountLegalEntityPublicHashedId));
            }

            if (command.UkPrn.HasValue && !command.IsEmptyCohortFromSelect)
            {
                var accounts = await _mediator.Send(
                    new GetTrustedEmployersQuery { UkPrn = command.UkPrn.Value });

                var matchedAccount = accounts?.Employers?.SingleOrDefault(employer =>
                                                                          employer.AccountLegalEntityPublicHashedId == command.AccountLegalEntityPublicHashedId);

                result.FailedAuthorisationValidation = matchedAccount == null;
            }

            return(result);
        }
        internal IValidationResult NotificationRecipient(NotificationRecipient notificationRecipient)
        {
            IValidationResult validationResult = new ValidationResult();

            // Null checks.
            if (notificationRecipient.TwitterHandle == null)
            {
                validationResult.AddError("TwitterHandle.Null", "TwitterHandle cannot be null.");
            }

            if (notificationRecipient.Description == null || notificationRecipient.Description == string.Empty)
            {
                validationResult.AddError("Description.Null", "Description cannot be null or an empty string.");
            }

            // Regex checks.
            if (notificationRecipient.TwitterHandle != null)
            {
                if (!Regex.Match(notificationRecipient.TwitterHandle, "^@(\\w){1,15}$").Success)
                {
                    validationResult.AddError("TwitterHandle.Format", "Invalid twitter handle.");
                }
            }

            // Range checks.
            if (notificationRecipient.AlertIntervalHours < 1 || notificationRecipient.AlertIntervalHours > 168)
            {
                validationResult.AddError("AlertIntervalHours.Range", "AlertIntervalHours is outside of expected ranges. AlertIntervalHours should be between 1 and 168 hours (one week).");
            }

            return validationResult;
        }
Exemple #36
0
        public Task <ValidationResult> ValidateAsync(CreateCachedCourseDemandCommand item)
        {
            var validationResult = new ValidationResult();

            if (item.TrainingCourseId == 0)
            {
                validationResult.AddError(nameof(item.TrainingCourseId));
            }

            if (string.IsNullOrEmpty(item.Location))
            {
                validationResult.AddError(nameof(item.Location), "Enter a town, city or postcode");
            }

            if (!item.NumberOfApprenticesKnown.HasValue)
            {
                validationResult.AddError(nameof(item.NumberOfApprenticesKnown), "Select yes if you know how many apprentices will take this apprenticeship training");
            }
            if (item.NumberOfApprenticesKnown != null && item.NumberOfApprenticesKnown.Value)
            {
                var tryConvert = int.TryParse(item.NumberOfApprentices, out var numberOfApprentices);

                if (!tryConvert && numberOfApprentices == 0 && string.IsNullOrEmpty(item.NumberOfApprentices))
                {
                    validationResult.AddError(nameof(item.NumberOfApprentices), "Enter the number of apprentices");
                }
                if (!tryConvert && numberOfApprentices == 0 && !string.IsNullOrEmpty(item.NumberOfApprentices))
                {
                    validationResult.AddError(nameof(item.NumberOfApprentices), "Number of apprentices must be 9999 or less");
                }
                if (tryConvert && numberOfApprentices == 0)
                {
                    validationResult.AddError(nameof(item.NumberOfApprentices), "Enter the number of apprentices");
                }
                if (tryConvert && numberOfApprentices < 0)
                {
                    validationResult.AddError(nameof(item.NumberOfApprentices), "Number of apprentices must be 1 or more");
                }
                if (tryConvert && numberOfApprentices > 9999)
                {
                    validationResult.AddError(nameof(item.NumberOfApprentices), "Number of apprentices must be 9999 or less");
                }
            }

            if (string.IsNullOrEmpty(item.OrganisationName))
            {
                validationResult.AddError(nameof(item.OrganisationName), "Enter the name of the organisation");
            }

            if (string.IsNullOrEmpty(item.ContactEmailAddress))
            {
                validationResult.AddError(nameof(item.ContactEmailAddress), "Enter an email address");
            }
            else
            {
                try
                {
                    var emailAddress = new MailAddress(item.ContactEmailAddress);
                    if (!emailAddress.Address.Equals(item.ContactEmailAddress, StringComparison.CurrentCultureIgnoreCase))
                    {
                        validationResult.AddError(nameof(item.ContactEmailAddress));
                    }
                }
                catch (FormatException)
                {
                    validationResult.AddError(nameof(item.ContactEmailAddress), "Enter an email address in the correct format, like [email protected]");
                }
            }

            return(Task.FromResult(validationResult));
        }
Exemple #37
0
        public ValidationResult SyncItineraries()
        {
            var validation = new ValidationResult();

            try
            {
                //Get lines
                var lines = _lineService.GetAllLines().ToList();

                var itinerariesToCreate = new List <Itinerary>();

                //Analyse Objects
                foreach (var line in lines)
                {
                    var itineraries = _datarioRepository.GetItineraryInformation(line.LineId).ToList();

                    var calculatedItineraries = new List <Itinerary>();

                    var goingItineraries     = itineraries.Where(i => i.Returning == false).OrderBy(i => i.Sequence).ToList();
                    var returningItineraries = itineraries.Where(i => i.Returning).OrderBy(i => i.Sequence).ToList();

                    for (var i = 0; i < goingItineraries.Count - 1; i++)
                    {
                        var thisItinerary = goingItineraries[i];
                        var nextItinerary = goingItineraries[i + 1];

                        var distanceBetween = GpsHelper.DistanceBetweenCoordenates(thisItinerary.Latitude,
                                                                                   thisItinerary.Longitude, nextItinerary.Latitude, nextItinerary.Longitude);

                        thisItinerary.DistanceToNext = distanceBetween;

                        calculatedItineraries.Add(thisItinerary);
                    }

                    for (var i = 0; i < returningItineraries.Count - 1; i++)
                    {
                        var thisItinerary = returningItineraries[i];
                        var nextItinerary = returningItineraries[i + 1];

                        var distanceBetween = GpsHelper.DistanceBetweenCoordenates(thisItinerary.Latitude,
                                                                                   thisItinerary.Longitude, nextItinerary.Latitude, nextItinerary.Longitude);

                        thisItinerary.DistanceToNext = distanceBetween;

                        calculatedItineraries.Add(thisItinerary);
                    }

                    itinerariesToCreate.AddRange(calculatedItineraries);
                }

                if (itinerariesToCreate.Any())
                {
                    _itineraryService.RemoveAllItineraries();
                    _itineraryService.CreateItineraries(itinerariesToCreate);
                }
            }
            catch (Exception e)
            {
                validation.AddError(new ValidationError(e.Message));
            }

            return(validation);
        }
        public ValidationResult ValidateEditCarServiceDto(EditCarServiceDto dto)
        {
            var validationResult = new ValidationResult("Редактирование автосервиса");

            if (string.IsNullOrEmpty(dto.Name))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceNameIsEmpty);
            }

            if (string.IsNullOrEmpty(dto.Address))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceAddressIsEmpty);
            }

            if (IsInvalidEmail(dto.Email))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceContactEmailIsInvalid);
            }

            if (dto.Phones == null || !dto.Phones.Any())
            {
                validationResult.AddError(ValidationErrorResources.CarServicePhonesIsEmpty);
            }
            if (dto.Phones != null)
            {
                foreach (var phone in dto.Phones)
                {
                    if (IsInvalidPhoneNumber(phone))
                    {
                        validationResult.AddError(string.Format(ValidationErrorResources.CarServicePhoneIsIncorrect, phone));
                    }
                }
            }

            if (string.IsNullOrEmpty(dto.ManagerName))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceManagerNameIsEmpty);
            }

            var regex = new Regex("^(http|https)://");

            if (string.IsNullOrEmpty(dto.Site) || !regex.IsMatch(dto.Site))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceSiteIsIncorrect);
            }

            if (dto.Logo != null && !IsImage(dto.Logo.Name))
            {
                validationResult.AddError(string.Format(ValidationErrorResources.InvalidFileExtension, dto.Logo.Name));
            }

            if (dto.Photos != null && dto.Photos.Any())
            {
                if (dto.Photos.Count > 5)
                {
                    validationResult.AddError(ValidationErrorResources.PhotosToMuch);
                }
                foreach (var photo in dto.Photos)
                {
                    if (!IsImage(photo.Name))
                    {
                        validationResult.AddError(string.Format(ValidationErrorResources.InvalidFileExtension, photo.Name));
                    }
                }
            }

            return(validationResult);
        }
        public ValidationResult ValidateRegistrationCarServiceDto(RegistrationCarServiceDto dto)
        {
            if (dto == null)
            {
                throw new ArgumentNullException(ArgumentExceptionResources.RegistrationDtoNotFound);
            }
            var validationResult = new ValidationResult("Регистрация автосервиса");

            ValidateRegistartionBaseDto(dto, validationResult);

            if (string.IsNullOrEmpty(dto.Name))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceNameIsEmpty);
            }

            var city = _unitOfWork.Repository <ICityRepository>().Get(dto.CityId);

            if (city == null)
            {
                validationResult.AddError(ValidationErrorResources.CityNotFound);
            }

            if (string.IsNullOrEmpty(dto.Address))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceAddressIsEmpty);
            }

            if (IsInvalidEmail(dto.Email))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceContactEmailIsInvalid);
            }

            if (dto.Phones == null || !dto.Phones.Any())
            {
                validationResult.AddError(ValidationErrorResources.CarServicePhonesIsEmpty);
            }
            if (dto.Phones != null)
            {
                foreach (var phone in dto.Phones)
                {
                    if (IsInvalidPhoneNumber(phone))
                    {
                        validationResult.AddError(string.Format(ValidationErrorResources.CarServicePhoneIsIncorrect, phone));
                    }
                }
            }

            if (string.IsNullOrEmpty(dto.ManagerName))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceManagerNameIsEmpty);
            }

            var regex = new Regex("^(http|https)://");

            if (string.IsNullOrEmpty(dto.Site) || !regex.IsMatch(dto.Site))
            {
                validationResult.AddError(ValidationErrorResources.CarServiceSiteIsIncorrect);
            }

            if (dto.WorkTypes != null && dto.WorkTypes.Any())
            {
                var repository = _unitOfWork.Repository <IWorkTypeRepository>();
                foreach (var workType in dto.WorkTypes)
                {
                    var type = repository.Get(workType);
                    if (type == null)
                    {
                        validationResult.AddError(string.Format(ValidationErrorResources.WorkTypeNotFound, workType));
                    }
                }
            }
            else
            {
                validationResult.AddError(ValidationErrorResources.WorkTypeRequired);
            }

            if (dto.CarTags != null && dto.CarTags.Any())
            {
                var repository = _unitOfWork.Repository <ICarMarksRepository>();
                foreach (var carTagId in dto.CarTags)
                {
                    var mark = repository.Get(carTagId);
                    if (mark == null)
                    {
                        validationResult.AddError(string.Format(ValidationErrorResources.CarMarkNotFound, carTagId));
                    }
                }
            }

            if (dto.Logo != null && !IsImage(dto.Logo.Name))
            {
                validationResult.AddError(string.Format(ValidationErrorResources.InvalidFileExtension, dto.Logo.Name));
            }

            if (dto.Photos != null && dto.Photos.Any())
            {
                if (dto.Photos.Count > 5)
                {
                    validationResult.AddError(ValidationErrorResources.PhotosToMuch);
                }
                foreach (var photo in dto.Photos)
                {
                    if (!IsImage(photo.Name))
                    {
                        validationResult.AddError(string.Format(ValidationErrorResources.InvalidFileExtension, photo.Name));
                    }
                }
            }

            return(validationResult);
        }
        /// <summary>
        /// Evaluates the rule for the given request.  The <b>RegexRule</b> applies its
        /// regular expression pattern to its specified field in the given request.
        /// </summary>
        /// <param name="request">The <b>MvcRequest</b> to evaluate the rule for.</param>
        /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the
        ///			rule and any validation errors that occurred.</returns>
        public override ValidationResult Evaluate(
            MvcRequest request)
        {
            ValidationResult result = new ValidationResult { Passed = true };

            if (request.Files.Count == 0 || request.Files[Field] == null) {
                result.Passed = false;
                //result.AddError(Field, ErrorId);
            } else {
                //  get the uploaded file reference
                MvcPostedFile theFile = request.Files[Field];

                if (this.FileType != null) {
                    result.Passed = false;
                    //  get the list of acceptable types
                    string[] types = this.FileType.Split(',');
                    //  get the extension of the file
                    string ext = this.GetExtension(theFile.Name).ToLower();

                    //  see if the file extension is in the acceptable list
                    foreach (string t in types) {
                        if (ext == t.ToLower()) {
                            result.Passed = true;
                            break;
                        }
                    }
                }

                //  if a file size limit is specified, check the size
            // TODO: should we check result.Passed and not do this if we've already failed??
                if (this.fileSize.HasValue) {
                    if (theFile.Length > this.fileSize) {
                        result.Passed = false;
                    }
                }
            }
            //  if the type check failed and an error ID was specified, add the error
            if (!result.Passed && (ErrorId > 0)) {
                result.AddError(Field, ErrorId);
            }

            return result;
        }
Exemple #41
0
        public ValidationResult TryUpdateModel(NameValueCollection newValuesDictionary = null, object model = null)
        {
            if (newValuesDictionary == null)
                newValuesDictionary = System.Web.HttpContext.Current.Request.Form;

            if (model == null) model = this.Model; else this.Model = model;

            if (Fields.Count() == 0)
            {
                AutoPopulateFormFields();
            }

            var validationResult = new ValidationResult();

            try
            {
                foreach (var varFields in Fields.Where(f => f.Type != InputType.html))
                {
                    var newValueKey = varFields.FieldName;
                    var newValueString = "";
                    if (newValuesDictionary.AllKeys.Contains(newValueKey))
                    {
                        newValueString = newValuesDictionary[newValueKey];
                    }

                    if (ModelDictionary.Keys.Contains(newValueKey))
                    {

                        System.Type updateType;

                        object newTypedValue;

                        if (model.GetType() == typeof(ExpandoObject))
                        {
                            if (ModelDictionary[newValueKey] != null)
                                updateType = ModelDictionary[newValueKey].GetType();
                            else
                                updateType = typeof(String);
                        }
                        else
                        {
                            updateType = model.GetType().GetProperty(newValueKey).PropertyType;
                        }

                        if (updateType == typeof(Int32))
                        {
                            Int32 setValue = 0;
                            Int32.TryParse(newValueString, out setValue);
                            newTypedValue = setValue;
                        }
                        else if (updateType == typeof(Int32?))
                        {
                            Int32 setValue = 0;
                            if (Int32.TryParse(newValueString, out setValue))
                            {
                                newTypedValue = setValue;
                            }
                            else
                            {
                                newTypedValue = null;
                            }
                        }
                        else if (updateType == typeof(Int64))
                        {
                            Int64 setValue = 0;
                            Int64.TryParse(newValueString, out setValue);
                            newTypedValue = setValue;
                        }
                        else if (updateType == typeof(Int64?))
                        {
                            Int64 setValue = 0;
                            if (Int64.TryParse(newValueString, out setValue))
                            {
                                newTypedValue = setValue;
                            }
                            else
                            {
                                newTypedValue = null;
                            }
                        }
                        else if (updateType == typeof(Single))
                        {
                            Single setValue = 0;
                            Single.TryParse(newValueString, out setValue);
                            newTypedValue = setValue;
                        }
                        else if (updateType == typeof(Single?))
                        {
                            Single setValue = 0;
                            if (Single.TryParse(newValueString, out setValue))
                            {
                                newTypedValue = setValue;
                            }
                            else
                            {
                                newTypedValue = null;
                            }
                        }
                        else if (updateType == typeof(Double))
                        {
                            Double setValue = 0;
                            Double.TryParse(newValueString, out setValue);
                            newTypedValue = setValue;
                        }
                        else if (updateType == typeof(Double?))
                        {
                            Double setValue = 0;
                            if (Double.TryParse(newValueString, out setValue))
                            {
                                newTypedValue = setValue;
                            }
                            else
                            {
                                newTypedValue = null;
                            }
                        }
                        else if (updateType == typeof(Decimal))
                        {
                            Decimal setValue = 0;
                            Decimal.TryParse(newValueString, out setValue);
                            newTypedValue = setValue;
                        }
                        else if (updateType == typeof(Decimal?))
                        {
                            Decimal setValue = 0;
                            if (Decimal.TryParse(newValueString, out setValue))
                            {
                                newTypedValue = setValue;
                            }
                            else
                            {
                                newTypedValue = null;
                            }
                        }
                        else if (updateType == typeof(Boolean))
                        {
                            Boolean setValue = (newValueString.ToString() != "");
                            newTypedValue = setValue;
                        }
                        else if (updateType == typeof(String))
                        {
                            newTypedValue = newValueString;
                        }
                        else if (updateType == typeof(DateTime?))
                        {
                            DateTime setValue;
                            if (DateTime.TryParse(newValueString, out setValue))
                            {
                                newTypedValue = setValue;
                            }
                            else
                            {
                                newTypedValue = null;
                            }
                        }
                        else if (updateType == typeof(DateTime))
                        {
                            DateTime setValue = DateTime.MinValue;
                            DateTime.TryParse(newValueString, out setValue);
                            newTypedValue = setValue;
                        }
                        else
                        {
                            newTypedValue = null;
                            new InvalidCastException("this type is not handled");
                        }

                        if (model.GetType() == typeof(ExpandoObject))
                        {
                            ((IDictionary<string, object>)model)[newValueKey] = newTypedValue;
                        }
                        else
                        {
                            var p = model.GetType().GetProperty(newValueKey);
                            p.SetValue(model, newTypedValue, null);
                        }
                    }
                }
                this.Model = model;
            }
            catch (Exception ex)
            {
                validationResult.AddError("", System.Web.HttpUtility.HtmlEncode(ex.Message), "");
                validationResult.IsValid = false;
            }
            this.validationResult = validationResult;

            if (!validationResult.IsValid)
                return validationResult;
            else
                return Validate(model, validationResult);
        }
Exemple #42
0
 public static ValidationResult AddError(this ValidationResult result, Exception exception)
 {
     return(result.AddError(exception.GetFullMessage()));
 }
        /// <summary>
        /// Проверка сертификата на квалифицированность
        /// </summary>
        /// <returns>Список сообщений/ошибок о квалифицированности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            bool isQualified = true;

            result.Add("Проверка квалифицированного сертификатов:");
            result.AddNewLine();

            string subjectCommonName = certificate.SubjectCommonName;

            if (subjectCommonName == "")
            {
                result.AddError("  Не задано наименование (CN) Субъекта");
                isQualified = false;
            }

            if (certificate.Organization == "")
            {
                result.AddError("  Не задана организация (O) Субъекта");
                isQualified = false;
            }

            if (certificate.Locality == "")
            {
                result.AddError("  Не задана расположение (L) Субъекта");
                isQualified = false;
            }

            if (certificate.Email == "")
            {
                result.AddError("  Не задан e-mail (E) Субъекта");
                isQualified = false;
            }

            if (certificate.INN.Trim().Length != 12)
            {
                result.AddError("  ИНН Субъекта должен состоять из 12 знаков");
                isQualified = false;
            }

            if (String.IsNullOrEmpty(certificate.OGRN))
            {
                result.AddError("  Не задан ОГРН Субъекта");
                isQualified = false;
            }

            int CN_fio = 0;
            int CN_org = 0;

            string[] splits = subjectCommonName.Split(new string[1] { " " }, StringSplitOptions.RemoveEmptyEntries);

            if (splits.Length == 3)
            {
                CN_fio += 3;

                if (splits[2].EndsWith("вич") || splits[2].EndsWith("вна"))
                    CN_fio += 1;
            }
            else CN_org += 2;

            if (subjectCommonName.Contains("\""))
                CN_org += 3;
            else CN_fio += 1;

            if (subjectCommonName.ToLower().Contains("ооо") || subjectCommonName.ToLower().Contains("зао") || subjectCommonName.ToLower().Contains("оао") || subjectCommonName.ToLower().Contains("пао") || subjectCommonName.ToLower().StartsWith("ип"))
                CN_org += 2;

            if (CN_fio > CN_org && String.IsNullOrEmpty(certificate.SNILS))
            {
                result.AddError("  Не задан СНИЛС Субъекта");
                isQualified = false;
            }

            result.Add(isQualified, "Результат проверки квалифицированного сертификата", isQualified ? "Сертификат является Квалифицированным" : "Сертификат НЕ является Квалифицированным");

            return result;
        }
        public override async Task <ValidationResult> ValidateAsync(ValidateCartContextArgs entity, ValidationMode validationMode)
        {
            var result = new ValidationResult();
            var order  = entity.Cart.Order;

            if (order.Rows.Count > 0)
            {
                var personId  = order.CustomerInfo?.PersonSystemId ?? _securityContextService.GetIdentityUserSystemId() ?? Guid.Empty;
                var countryId = _countryService.Get(order.CountryCode)?.SystemId;

                var updatedItems              = new List <AddOrUpdateCartItemArgs>();
                var outOfStocksProducts       = new List <string>();
                var notEnoughInStocksProducts = new List <string>();
                foreach (var row in order.Rows.Where(x => x.OrderRowType == OrderRowType.Product))
                {
                    var variant = _variantService.Get(row.ArticleNumber);
                    if (variant != null)
                    {
                        _stockStatusCalculator.GetStockStatuses(new StockStatusCalculatorArgs
                        {
                            UserSystemId    = personId,
                            CountrySystemId = countryId
                        }, new StockStatusCalculatorItemArgs
                        {
                            VariantSystemId = variant.SystemId,
                            Quantity        = row.Quantity
                        }).TryGetValue(variant.SystemId, out var stockStatus);

                        var existingStocks = stockStatus?.InStockQuantity.GetValueOrDefault();
                        //If stock status is not returned or the actual stock level is zero or below.
                        if (stockStatus == null || existingStocks <= decimal.Zero)
                        {
                            //Remove the order row from the shopping cart.
                            updatedItems.Add(new AddOrUpdateCartItemArgs
                            {
                                ArticleNumber    = row.ArticleNumber,
                                Quantity         = 0,
                                ConstantQuantity = true,
                            });
                            outOfStocksProducts.Add(variant.Localizations[CultureInfo.CurrentCulture].Name ?? variant.Id);
                        }
                        else
                        {
                            if (row.Quantity > existingStocks)
                            {
                                //Update the order row with available amount in stock.
                                updatedItems.Add(new AddOrUpdateCartItemArgs
                                {
                                    ArticleNumber    = row.ArticleNumber,
                                    Quantity         = existingStocks.Value,
                                    ConstantQuantity = true,
                                });
                                notEnoughInStocksProducts.Add(variant.Localizations[CultureInfo.CurrentCulture].Name ?? variant.Id);
                            }
                        }
                    }
                }

                if (updatedItems.Count > 0)
                {
                    foreach (var item in updatedItems)
                    {
                        await _cartContextAccessor.CartContext.AddOrUpdateItemAsync(item);
                    }
                    await _cartContextAccessor.CartContext.CalculatePaymentsAsync();
                }

                if (outOfStocksProducts.Count > 0 || notEnoughInStocksProducts.Count > 0)
                {
                    var sb = new StringBuilder();
                    if (outOfStocksProducts.Count > 0)
                    {
                        outOfStocksProducts.ForEach(x => sb.AppendFormat("sales.validation.product.outofstock".AsWebsiteText(), x));
                    }
                    if (notEnoughInStocksProducts.Count > 0)
                    {
                        notEnoughInStocksProducts.ForEach(x => sb.AppendFormat("sales.validation.product.notenoughinstock".AsWebsiteText(), x));
                    }
                    result.AddError("Cart", sb.ToString());
                }
            }

            return(result);
        }
 public void SeriesCanChangeType(string seriesLabel, SeriesType?seriesType, ValidationResult result)
 {
     result.AddError($"Series \"{seriesLabel}\"'s type cannot be changed");
 }
Exemple #46
0
        /// <summary>
        /// <para>Adds a sales agent from an api key and account id.</para>
        /// </summary>
        /// <param name="apiId">A valid eve api id (keyID).</param>
        /// <param name="apiKey">A valid eve api key (vCode).</param>
        /// <param name="accountId">The id of the account for which a sales agent should be added.</param>
        /// <returns>Returns a validation result object.</returns>
        internal IValidationResult AddSalesAgent(int apiId, string apiKey, int accountId)
        {
            IValidationResult validationResult = new ValidationResult();

            // Check the remaining sales agent licences for the account.
            if (this.GetRemainingSalesAgentLicences(accountId) <= 0)
            {
                validationResult.AddError("SalesAgent.Licences", "You have exceeded the number of sales agent licences available with your account subscription plan.");
            }
            else
            {
                // Fetch details about the Api Key from Eve Data.
                IEveDataApiKey apiKeyInfo = this.eveDataSource.GetApiKeyInfo(apiId, apiKey);

                if (apiKeyInfo != null)
                {
                    // Validate the api key.
                    validationResult = this.doctrineShipsValidation.ApiKey(apiKeyInfo);
                    if (validationResult.IsValid == true)
                    {
                        // Use the api key info to populate a new sales agent object.
                        SalesAgent newSalesAgent = new SalesAgent();

                        // If this is a character or account key use the character details, if a corp key use the corp details.
                        if (apiKeyInfo.Type == EveDataApiKeyType.Character || apiKeyInfo.Type == EveDataApiKeyType.Account)
                        {
                            // If this is an account key, the first character in the list will be used.
                            newSalesAgent.SalesAgentId = apiKeyInfo.Characters.FirstOrDefault().CharacterId;
                            newSalesAgent.Name         = apiKeyInfo.Characters.FirstOrDefault().CharacterName;
                            newSalesAgent.ImageUrl     = eveDataSource.GetCharacterPortraitUrl(newSalesAgent.SalesAgentId);
                            newSalesAgent.IsCorp       = false;
                        }
                        else if (apiKeyInfo.Type == EveDataApiKeyType.Corporation)
                        {
                            newSalesAgent.SalesAgentId = apiKeyInfo.Characters.FirstOrDefault().CorporationId;
                            newSalesAgent.Name         = apiKeyInfo.Characters.FirstOrDefault().CorporationName;
                            newSalesAgent.ImageUrl     = eveDataSource.GetCorporationLogoUrl(newSalesAgent.SalesAgentId);
                            newSalesAgent.IsCorp       = true;
                        }

                        // Populate the remaining properties.
                        newSalesAgent.AccountId           = accountId;
                        newSalesAgent.ApiId               = apiId;
                        newSalesAgent.ApiKey              = apiKey;
                        newSalesAgent.IsActive            = true;
                        newSalesAgent.LastForce           = DateTime.UtcNow;
                        newSalesAgent.LastContractRefresh = DateTime.UtcNow;

                        // Validate the new sales agent.
                        validationResult = this.doctrineShipsValidation.SalesAgent(newSalesAgent);
                        if (validationResult.IsValid == true)
                        {
                            // Add the new sales agent and log the event.
                            this.doctrineShipsRepository.CreateSalesAgent(newSalesAgent);
                            this.doctrineShipsRepository.Save();
                            logger.LogMessage("Sales Agent '" + newSalesAgent.Name + "' Successfully Added For Account Id: " + newSalesAgent.AccountId, 2, "Message", MethodBase.GetCurrentMethod().Name);
                        }
                    }
                }
                else
                {
                    validationResult.AddError("ApiKey.Valid", "An invalid api key was entered or the eve api is currently unavailable.");
                }
            }

            return(validationResult);
        }
        internal IValidationResult SubscriptionPlan(SubscriptionPlan subscriptionPlan)
        {
            IValidationResult validationResult = new ValidationResult();

            // Null checks.
            if (subscriptionPlan.Name == null)
            {
                validationResult.AddError("Name.Null", "Name cannot be null.");
            }

            if (subscriptionPlan.Description == null)
            {
                validationResult.AddError("Description.Null", "Description cannot be null.");
            }

            // Range checks.
            if (subscriptionPlan.SalesAgentLimit < 1 || subscriptionPlan.SalesAgentLimit > 500)
            {
                validationResult.AddError("SalesAgentLimit.Range", "SalesAgentLimit is outside of expected ranges. SalesAgentLimit should be between 1 and 500.");
            }

            if (subscriptionPlan.PricePerMonth < 0 || subscriptionPlan.PricePerMonth > long.MaxValue)
            {
                validationResult.AddError("PricePerMonth.Range", "PricePerMonth can not be less than 0. Also, the upper limit cannot exceed the max value of the long data type.");
            }

            return validationResult;
        }
        /// <summary>
        /// Deletes an account and all access codes, ship fits, sales agents and their contracts.
        /// </summary>
        /// <param name="accountId">The account Id being deleted.</param>
        /// <returns>Returns a validation result object.</returns>
        public IValidationResult DeleteAccount(int accountId)
        {
            IValidationResult validationResult = new ValidationResult();

            // Delete all account ship fits, components and related contracts.
            var accountShipFits = ShipFitManager.GetShipFitList(accountId);

            foreach (var shipFit in accountShipFits)
            {
                if (ShipFitManager.DeleteShipFit(accountId, shipFit.ShipFitId) == false)
                {
                    validationResult.AddError(shipFit.ShipFitId.ToString(), "Error while deleting ship fit: " + shipFit.ShipFitId.ToString());
                }
            }

            // Delete all account sales agents.
            var accountSalesAgents = SalesAgentManager.GetSalesAgents(accountId);

            foreach (var salesAgent in accountSalesAgents)
            {
                if (SalesAgentManager.DeleteSalesAgent(accountId, salesAgent.SalesAgentId) == false)
                {
                    validationResult.AddError(salesAgent.SalesAgentId.ToString(), "Error while deleting sales agent: " + salesAgent.SalesAgentId.ToString());
                }
            }

            // Delete all account doctrines.
            var accountDoctrines = ShipFitManager.GetDoctrineList(accountId);

            foreach (var doctrine in accountDoctrines)
            {
                if (ShipFitManager.DeleteDoctrine(accountId, doctrine.DoctrineId) == false)
                {
                    validationResult.AddError(doctrine.DoctrineId.ToString(), "Error while deleting doctrine: " + doctrine.DoctrineId.ToString());
                }
            }

            // Delete all account access codes.
            var accountAccessCodes = AccountManager.GetAccessCodes(accountId);

            foreach (var accessCode in accountAccessCodes)
            {
                if (AccountManager.DeleteAccessCode(accountId, accessCode.AccessCodeId) == false)
                {
                    validationResult.AddError(accessCode.AccessCodeId.ToString(), "Error while deleting access code: " + accessCode.AccessCodeId.ToString());
                }
            }

            // Delete all notification recipients.
            var accountNotificationRecipients = AccountManager.GetNotificationRecipients(accountId);

            foreach (var notificationRecipient in accountNotificationRecipients)
            {
                if (AccountManager.DeleteNotificationRecipient(accountId, notificationRecipient.NotificationRecipientId) == false)
                {
                    validationResult.AddError(notificationRecipient.NotificationRecipientId.ToString(), "Error while deleting notification recipient: " + notificationRecipient.NotificationRecipientId.ToString());
                }
            }

            // Delete the account.
            if (AccountManager.DeleteAccount(accountId) == false)
            {
                validationResult.AddError(accountId.ToString(), "Error while deleting account: " + accountId.ToString());
            }

            try
            {
                // Delete the account setting profile.
                var settingProfile = this.GetAccountSettingProfile(accountId);
                if (AccountManager.DeleteSettingProfile(accountId, settingProfile.SettingProfileId) == false)
                {
                    validationResult.AddError(settingProfile.SettingProfileId.ToString(), "Error while deleting setting profile: " + settingProfile.SettingProfileId.ToString());
                }
            }
            catch (System.ArgumentException e)
            {
                // The setting profile did not exist. Add an error to the validation result object.
                validationResult.AddError("SettingProfile.Exists" + accountId.ToString(), "The setting profile did not exist for account id: " + accountId.ToString());
            }
            catch (Exception)
            {
                throw;
            }

            return(validationResult);
        }
        public async Task <ValidationResult> ValidateAsync(RemoveLegalEntityCommand item)
        {
            var validationResult = new ValidationResult();

            if (string.IsNullOrEmpty(item.HashedAccountId))
            {
                validationResult.AddError(nameof(item.HashedAccountId));
            }
            if (string.IsNullOrEmpty(item.UserId))
            {
                validationResult.AddError(nameof(item.UserId));
            }
            if (string.IsNullOrEmpty(item.HashedLegalAgreementId))
            {
                validationResult.AddError(nameof(item.HashedLegalAgreementId));
            }

            if (!validationResult.IsValid())
            {
                return(validationResult);
            }

            var member = await _membershipRepository.GetCaller(item.HashedAccountId, item.UserId);

            if (member == null || !member.Role.Equals(Role.Owner))
            {
                validationResult.IsUnauthorized = true;
                return(validationResult);
            }

            var accountId     = _hashingService.DecodeValue(item.HashedAccountId);
            var legalEntities = await _employerAgreementRepository.GetLegalEntitiesLinkedToAccount(accountId, false);

            if (legalEntities != null && legalEntities.Count == 1)
            {
                validationResult.AddError(nameof(item.HashedLegalAgreementId), "There must be at least one legal entity on the account");
                return(validationResult);
            }

            var agreementId = _hashingService.DecodeValue(item.HashedLegalAgreementId);
            var agreement   = await _employerAgreementRepository.GetEmployerAgreement(agreementId);

            if (agreement.Status == EmployerAgreementStatus.Signed)
            {
                var commitments = await _employerCommitmentApi.GetEmployerAccountSummary(accountId);

                var returnValue = commitments.FirstOrDefault(c =>
                                                             !string.IsNullOrEmpty(c.LegalEntityIdentifier) &&
                                                             c.LegalEntityIdentifier.Equals(agreement.LegalEntityCode) &&
                                                             c.LegalEntityOrganisationType == agreement.LegalEntitySource);

                if (returnValue != null && (returnValue.ActiveCount + returnValue.PausedCount + returnValue.PendingApprovalCount) != 0)
                {
                    validationResult.AddError(nameof(item.HashedLegalAgreementId), "Agreement has already been signed and has active commitments");
                    return(validationResult);
                }
            }

            if (agreement.AccountId != accountId)
            {
                validationResult.IsUnauthorized = true;
                return(validationResult);
            }

            return(validationResult);
        }
        internal IValidationResult SettingProfile(SettingProfile settingProfile)
        {
            IValidationResult validationResult = new ValidationResult();

            var existingSettingProfile = this.doctrineShipsRepository.GetSettingProfileReadOnly(settingProfile.SettingProfileId);

            // Does the setting profile exist in the database?
            if (existingSettingProfile == null)
            {
                validationResult.AddError("SettingProfile.Null", "The setting profile being modified does not exist in the database.");
            }
            else
            {
                // Does the setting profile being modified belong to the requesting account?
                if (existingSettingProfile.AccountId != settingProfile.AccountId)
                {
                    validationResult.AddError("SettingProfile.Permission", "The setting profile being modified does not belong to the requesting account.");
                }
            }

            // Null checks.
            if (settingProfile.TwitterHandle == null)
            {
                validationResult.AddError("TwitterHandle.Null", "TwitterHandle cannot be null.");
            }

            // Regex checks.
            if (settingProfile.TwitterHandle != null)
            {
                if (!Regex.Match(settingProfile.TwitterHandle, "^@(\\w){1,15}$").Success)
                {
                    validationResult.AddError("TwitterHandle.Format", "Invalid twitter handle.");
                }
            }

            // Range checks.
            if (settingProfile.BrokerPercentage < 0 || settingProfile.BrokerPercentage > 100)
            {
                validationResult.AddError("BrokerPercentage.Range", "BrokerPercentage is outside of expected ranges.");
            }

            if (settingProfile.SalesTaxPercentage < 0 || settingProfile.SalesTaxPercentage > 100)
            {
                validationResult.AddError("SalesTaxPercentage.Range", "SalesTaxPercentage is outside of expected ranges.");
            }

            if (settingProfile.ContractMarkupPercentage < 0 || settingProfile.ContractMarkupPercentage > 100)
            {
                validationResult.AddError("ContractMarkupPercentage.Range", "ContractMarkupPercentage is outside of expected ranges.");
            }

            if (settingProfile.ContractBrokerFee < 0 || settingProfile.ContractBrokerFee > double.MaxValue)
            {
                validationResult.AddError("ContractBrokerFee.Range", "ContractBrokerFee is outside of expected ranges.");
            }

            if (settingProfile.ShippingCostPerM3 < 0 || settingProfile.ShippingCostPerM3 > double.MaxValue)
            {
                validationResult.AddError("ShippingCostPerM3.Range", "ShippingCostPerM3 is outside of expected ranges.");
            }

            if (settingProfile.BuyStationId < 0 || settingProfile.BuyStationId > int.MaxValue)
            {
                validationResult.AddError("BuyStationId.Range", "BuyStationId is outside of expected ranges.");
            }

            if (settingProfile.SellStationId < 0 || settingProfile.SellStationId > int.MaxValue)
            {
                validationResult.AddError("SellStationId.Range", "SellStationId is outside of expected ranges.");
            }

            if (settingProfile.AlertThreshold < 0 || settingProfile.AlertThreshold > int.MaxValue)
            {
                validationResult.AddError("AlertThreshold.Range", "AlertThreshold is outside of expected ranges.");
            }

            return(validationResult);
        }
Exemple #51
0
 public static ValidationResult AddError(this ValidationResult validationResult, string errorMessage)
 {
     return(validationResult.AddError(string.Empty, errorMessage));
 }
Exemple #52
0
        public Task <ValidationResult> Validate(CreateIncentiveCommand item)
        {
            var result = new ValidationResult();

            if (item.AccountId == default)
            {
                result.AddError("AccountId", "Is not set");
            }

            if (item.AccountLegalEntityId == default)
            {
                result.AddError("AccountLegalEntityId", "Is not set");
            }

            if (item.ApprenticeshipId == default)
            {
                result.AddError("ApprenticeshipId", "Is not set");
            }

            if (item.DateOfBirth == default)
            {
                result.AddError("DateOfBirth", "Is not set");
            }

            if (item.FirstName == default)
            {
                result.AddError("FirstName", "Is not set");
            }

            if (item.IncentiveApplicationApprenticeshipId == default)
            {
                result.AddError("IncentiveApplicationApprenticeshipId", "Is not set");
            }

            if (item.LastName == default)
            {
                result.AddError("LastName", "Is not set");
            }

            if (item.PlannedStartDate == default)
            {
                result.AddError("PlannedStartDate", "Is not set");
            }

            if (!item.UKPRN.HasValue || item.UKPRN.Value == default)
            {
                result.AddError("UKPRN", "Is not set");
            }

            if (item.Uln == default)
            {
                result.AddError("Uln", "Is not set");
            }

            if (item.SubmittedDate == default)
            {
                result.AddError("SubmittedDate", "Is not set");
            }

            if (item.SubmittedByEmail == default)
            {
                result.AddError("SubmittedByEmail", "Is not set");
            }

            if (item.CourseName == default)
            {
                result.AddError("CourseName", "Is not set");
            }

            return(Task.FromResult(result));
        }
        /// <summary>
        /// Evaluates the rule for the given request.  The <b>FieldCompareRule</b> determines
        /// if the specified fields in the given request all have the same value.
        /// </summary>
        /// <param name="request">The <b>FPRequest</b> to evaluate the rule for.</param>
        /// <returns>A <b>ValidationResult</b> indicating the result of evaluating the
        ///			rule and any validation errors that occurred.</returns>
        public override ValidationResult Evaluate(
            MvcRequest request)
        {
            ValidationResult result = new ValidationResult {
                                                           	Passed = true
                                                           };

            //  default to true

            //  compare each subsequent field value against the first --
            //  if a mis-match is found, set the result to false, and add the error message
            string val1 = request[this.fields[0]];
            for (int k = 1; k < this.fields.Length; k++) {
                var field = this.fields[k].EvaluatePropertyValue();
                if (((val1 == null) && (request[field] != null))
                    ||
                    !val1.Equals(request[field],
                                 this.CaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase)) {
                    result.Passed = false;
                    result.AddError(field, ErrorId);
                    break;
                }
            }

            return result;
        }