/// <summary>
        /// Validate the query parameters if there are any.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        public override bool Validate(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            bool valid = ValidateInternal(validationEvent);

            if (!valid)
            {
                return(valid);
            }

            // Has paremeters?
            NamedQuery query = (NamedQuery)target;

            if (string.IsNullOrEmpty(query.Parameters))
            {
                return(true);
            }

            IList <NamedQueryParam>   queryParams = NamedQueryParamsParser.ParseParams(query.Parameters);
            NamedQueryParamsValidator validator   = new NamedQueryParamsValidator(queryParams);
            bool isValid = validator.Validate(results).IsValid;

            return(isValid);
        }
        /// <summary>
        /// Validate the target object( text ).
        /// </summary>
        /// <param name="target"></param>
        /// <param name="results"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            string text = useTarget ? (string)target : _text;

            // Not required and email not supplied.
            if (!_isRequired && string.IsNullOrEmpty(text))
            {
                return(true);
            }

            int initialErrorCount = results.Count;

            bool isNullOrEmpty = string.IsNullOrEmpty(text);

            ValidationUtils.Validate(isNullOrEmpty, results, _key, _messageIfEmptyAndRequired, text);

            if (!isNullOrEmpty)
            {
                // Now check the format.
                Regex regex = new Regex(_regEx);

                if (!regex.IsMatch(text))
                {
                    results.Add(_key, _messageIfRegExFails, null);
                }
            }
            return(results.Count == initialErrorCount);
        }
        /// <summary>
        /// Validate that the size is valid.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            HtmlInputFile file = useTarget ? (HtmlInputFile)target : _file;

            // Validate.
            if (!ValidationUtils.Validate(file == null, results, string.Empty, _errorMessageNoFile, null))
            {
                return(false);
            }
            if (!ValidationUtils.Validate(file.PostedFile == null, results, string.Empty, _errorMessageNoFile, null))
            {
                return(false);
            }
            if (!ValidationUtils.Validate(file.PostedFile.ContentLength == 0, results, string.Empty, _errorMessageEmptyFileContent, null))
            {
                return(false);
            }

            int initialErrorCount = results.Count;

            if (_restrictSize)
            {
                int fileSizeInKiloBytes = file.PostedFile.ContentLength / 1000;

                if (fileSizeInKiloBytes > _restrictedFileSizeInKiloBytes)
                {
                    results.Add(string.Empty, "File exceeds " + _restrictedFileSizeInKiloBytes + "K.", null);
                }
            }
            return(results.Count == initialErrorCount);
        }
            public async Task ReturnsIncompleteIfAuditHasNoFailedOrSucceededEvents(ValidationEvent validationEvent)
            {
                // Arrange
                _validationAuditor
                .Setup(x => x.ReadAuditAsync(It.IsAny <Guid>(), It.IsAny <string>(), It.IsAny <string>()))
                .ReturnsAsync(new PackageValidationAudit
                {
                    Entries = new List <PackageValidationAuditEntry>
                    {
                        new PackageValidationAuditEntry
                        {
                            ValidatorName = ValidatorName,
                            EventId       = validationEvent,
                        },
                    },
                });

                // Act
                var actual = await _target.GetStatusAsync(_validationRequest.Object);

                // Assert
                Assert.Equal(ValidationStatus.Incomplete, actual);
                _validationAuditor.Verify(
                    x => x.ReadAuditAsync(It.IsAny <Guid>(), It.IsAny <string>(), It.IsAny <string>()),
                    Times.Once);
                _validationAuditor.Verify(
                    x => x.ReadAuditAsync(ValidationId, NormalizedPackageId, NormalizedPackageVersion),
                    Times.Once);
                _validationService.Verify(
                    x => x.StartValidationProcessAsync(It.IsAny <NuGetPackage>(), It.IsAny <string[]>(), It.IsAny <Guid>()),
                    Times.Never);
            }
Beispiel #5
0
        /// <summary>
        /// Do some basic validation. This is just a DUMMY validator
        /// to show how to incorporation the validator into the code generator.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            Address            address = validationEvent.Target as Address;
            IValidationResults errors  = validationEvent.Results;
            int initialErrorCount      = errors.Count;

            if (string.IsNullOrEmpty(address.City))
            {
                errors.Add("City is empty");
            }

            if (string.IsNullOrEmpty(address.State))
            {
                errors.Add("State is empty");
            }

            if (string.IsNullOrEmpty(address.Country))
            {
                errors.Add("Country is emtpy");
            }
            else if (address.Country.Trim().ToLower() != "usa")
            {
                errors.Add("Only supports 'usa' for now.");
            }


            return(initialErrorCount == errors.Count);
        }
        /// <summary>
        /// Validate all the params and collect all the errors.
        /// </summary>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            string message = string.Empty;
            bool   success = true;

            foreach (NamedQueryParam param in _namedQueryParams)
            {
                BoolMessage result = ValidateParam(param);
                if (!result.Success)
                {
                    success  = false;
                    message += Environment.NewLine + result.Message;
                }
            }

            // Don't create instance, return reaon-only singleton.
            if (success)
            {
                return(BoolMessage.True.Success);
            }

            return(new BoolMessage(false, message).Success);
        }
        public bool MakePayment(string paymentName, decimal amount, Account backupAccount = null)
        {
            if (amount <= 0)
            {
                ValidationEvent?.Invoke(this, "You try to Pay 0. Are you kidding ?");
                return(false);
            }
            // Ensures we have enough money
            if (Balance >= amount)
            {
                _transactions.Add($"Withdrew { string.Format("{0:C2}", amount) } for { paymentName }");
                Balance -= amount;
                TransactionApprovedEvent?.Invoke(this, paymentName);
                return(true);
            }
            else
            {
                // We don't have enough money so we check to see if we have a backup account
                if (backupAccount != null)
                {
                    // Checks to see if we have enough money in the backup account
                    if ((backupAccount.Balance + Balance) >= amount)
                    {
                        // We have enough backup funds so transfar the amount to this account
                        // and then complete the transaction.
                        decimal amountNeeded       = amount - Balance;
                        bool    overdraftSucceeded = backupAccount.MakePayment("Overdraft Protection", amountNeeded);

                        // This should always be true but we will check anyway
                        if (overdraftSucceeded == false)
                        {
                            ValidationEvent?.Invoke(this, "The overdraft failed so this transaction failed");
                            return(false);
                        }

                        AddDeposit("Overdraft Protection Deposit", amountNeeded);

                        _transactions.Add($"Withdrew { string.Format("{0:C2}", amount) } for { paymentName }");
                        Balance -= amount;
                        TransactionApprovedEvent?.Invoke(this, paymentName);
                        OverdraftEvent?.Invoke(this, new OverDraftEventArgs(amountNeeded, "Extra Info"));

                        return(true);
                    }
                    else
                    {
                        ValidationEvent?.Invoke(this, "Not enough backup funds to do anything");
                        return(false);
                    }
                }
                else
                {
                    ValidationEvent?.Invoke(this, "You don't have enough money in the backup account");
                    return(false);
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Implement this method.
        /// </summary>
        /// <param name="validationEvent">Validation event.</param>
        /// <returns>Validation result.</returns>
        protected virtual bool ValidateInternal(ValidationEvent validationEvent)
        {
            if (_validatorLamda != null)
            {
                return(_validatorLamda(validationEvent));
            }

            return(true);
        }
Beispiel #9
0
        /// <summary>
        /// Validate the category.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            int      initialErrorCount = results.Count;
            Category category          = useTarget ? (Category)target : _category;

            ValidationUtils.Validate(string.IsNullOrEmpty(category.Name), results, "Title", "Category title can not be empty");
            return(initialErrorCount == results.Count);
        }
Beispiel #10
0
            /// <summary>
            /// Do some custom validation on a user name(string).
            /// </summary>
            /// <param name="validationEvent"></param>
            /// <returns></returns>
            protected override bool ValidateInternal(ValidationEvent validationEvent)
            {
                int originalErrorCount = validationEvent.Results.Count;

                Meeting meeting = validationEvent.TargetT <Meeting>();

                if (string.IsNullOrEmpty(meeting.Title))
                {
                    validationEvent.Results.Add("Title must be specified.");
                }

                return(originalErrorCount == validationEvent.Results.Count);
            }
        /// <summary>
        /// Is valid - text doesn't contain any word that has
        /// more than maxChars specified.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            string text = useTarget ? (string)target : _text;

            if (string.IsNullOrEmpty(text))
            {
                return(true);
            }

            bool isSpacerNewLine = false;
            int  currentPosition = 0;
            int  ndxSpace        = StringHelpers.GetIndexOfSpacer(text, currentPosition, ref isSpacerNewLine);

            //Check if single very long word ( no spaces )
            if (ndxSpace < 0 && text.Length > _maxCharsInWord)
            {
                results.Add(_errorMessage + _maxCharsInWord + " chars.");
                return(false);
            }

            while ((currentPosition < text.Length && ndxSpace > 0))
            {
                //Lenght of word
                int wordLength = ndxSpace - (currentPosition + 1);
                if (wordLength > _maxCharsInWord)
                {
                    results.Add(_errorMessage + _maxCharsInWord + " chars.");
                    return(false);
                }
                currentPosition = ndxSpace;
                ndxSpace        = StringHelpers.GetIndexOfSpacer(text, (currentPosition + 1), ref isSpacerNewLine);
            }

            // Final check.. no space found but check complete length now.
            if (currentPosition < text.Length && ndxSpace < 0)
            {
                //Lenght of word
                int wordLength = (text.Length - 1) - currentPosition;
                if (wordLength > _maxCharsInWord)
                {
                    results.Add(_errorMessage + _maxCharsInWord + " chars.");
                    return(false);
                }
            }
            return(true);
        }
Beispiel #12
0
        /// <summary>
        /// Validation method for the entity.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            int initialErrorCount      = validationEvent.Results.Count;
            IValidationResults results = validationEvent.Results;
            ConfigItem         entity  = (ConfigItem)validationEvent.Target;

            Validation.IsStringLengthMatch(entity.App, true, false, true, -1, 50, results, "App");
            Validation.IsStringLengthMatch(entity.Name, true, false, true, -1, 50, results, "Name");
            Validation.IsStringLengthMatch(entity.Section, true, false, true, -1, 20, results, "Section");
            Validation.IsStringLengthMatch(entity.Key, false, false, true, -1, 20, results, "Key");
            Validation.IsStringLengthMatch(entity.Val, false, false, false, -1, -1, results, "Val");
            Validation.IsStringLengthMatch(entity.ValType, true, false, true, -1, 20, results, "ValType");

            return(initialErrorCount == validationEvent.Results.Count);
        }
            protected override bool ValidateInternal(ValidationEvent validationEvent)
            {
                Person p = validationEvent.Target as Person;

                if (string.IsNullOrEmpty(p.Name))
                {
                    validationEvent.Results.Add("Name is not supplied.");
                    return(false);
                }
                else if (p.Name.Length > ((PersonSettings)p.Settings).MaxLength)
                {
                    validationEvent.Results.Add("Name exceeds max lenght.");
                    return(false);
                }
                return(true);
            }
Beispiel #14
0
        /// <summary>
        /// Validates all the rules in the internal rule list.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            // Should this even be here?
            if (_validatorLamda != null)
            {
                return(_validatorLamda(validationEvent));
            }

            // Run the validations against all the rules.
            int initialErrorCount = validationEvent.Results.Count;

            foreach (var rule in _rules)
            {
                rule.Rule(validationEvent);
            }
            return(validationEvent.Results.Count == initialErrorCount);
        }
Beispiel #15
0
        /// <summary>
        /// Get the entity action from the validation event's context.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        public EntityAction GetEntityAction(ValidationEvent validationEvent)
        {
            EntityAction action = EntityAction.Create;

            if (validationEvent.Context == null)
            {
                IEntity entity = (IEntity)validationEvent.Target;
                if (entity.IsPersistant())
                {
                    action = EntityAction.Update;
                }
            }
            else if (validationEvent.Context is EntityAction)
            {
                action = (EntityAction)validationEvent.Context;
            }
            return(action);
        }
        /// <summary>
        /// Validation method for the entity.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="useTarget">if set to <c>true</c> [use target].</param>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            int        initialErrorCount = results.Count;
            NamedQuery entity            = (NamedQuery)target;

            Validation.IsStringLengthMatch(entity.Name, false, true, true, 1, 100, results, "Name");
            Validation.IsStringLengthMatch(entity.Description, true, false, true, -1, 200, results, "Description");
            Validation.IsStringLengthMatch(entity.Sql, false, true, true, 1, 500, results, "Sql");
            Validation.IsStringLengthMatch(entity.Parameters, true, false, true, -1, 250, results, "Parameters");
            Validation.IsNumericWithinRange(entity.OrderId, false, false, -1, -1, results, "OrderId");
            Validation.IsStringLengthMatch(entity.ItemType, true, false, true, -1, 50, results, "ItemType");
            Validation.IsStringLengthMatch(entity.Roles, true, false, true, -1, 50, results, "Roles");

            return(initialErrorCount == results.Count);
        }
Beispiel #17
0
        /// <summary>
        /// Validation method for the entity.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="useTarget">if set to <c>true</c> [use target].</param>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            int     initialErrorCount = results.Count;
            Account entity            = (Account)target;

            Validation.IsStringLengthMatch(entity.SecurityQuestion, true, true, true, 0, 100, results, "SecurityQuestion");
            Validation.IsStringLengthMatch(entity.SecurityAnswer, true, true, true, 0, 100, results, "SecurityAnswer");
            Validation.IsStringLengthMatch(entity.Comment, true, true, true, 0, 100, results, "Comment");
            Validation.IsStringLengthMatch(entity.LockOutReason, true, true, true, 0, 100, results, "LockOutReason");
            Validation.IsDateWithinRange(entity.LastLoginDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "LastLoginDate");
            Validation.IsDateWithinRange(entity.LastPasswordChangedDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "LastPasswordChangedDate");
            Validation.IsDateWithinRange(entity.LastPasswordResetDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "LastPasswordResetDate");
            Validation.IsDateWithinRange(entity.LastLockOutDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "LastLockOutDate");

            return(initialErrorCount == results.Count);
        }
Beispiel #18
0
        /// <summary>
        /// Validation method for the entity.
        /// </summary>
        /// <param name="validationEvent">The event containing the object to validate.</param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            int  initialErrorCount = results.Count;
            User entity            = (User)target;

            Validation.IsStringLengthMatch(entity.UserName, false, true, true, 3, 20, results, "UserName");
            Validation.IsStringLengthMatch(entity.UserNameLowered, false, true, true, 3, 20, results, "UserNameLowered");
            Validation.IsEmail(entity.Email, false, results, "Email");
            Validation.IsStringLengthMatch(entity.Email, false, true, true, 6, 50, results, "Email");
            Validation.IsStringLengthMatch(entity.Password, false, true, true, 5, 100, results, "Password");
            Validation.IsStringLengthMatch(entity.Roles, true, false, false, -1, 50, results, "Roles");
            Validation.IsStringLengthMatch(entity.MobilePhone, true, true, true, 10, 20, results, "MobilePhone");
            Validation.IsStringLengthMatch(entity.SecurityQuestion, true, false, true, -1, 150, results, "SecurityQuestion");
            Validation.IsStringLengthMatch(entity.SecurityAnswer, true, false, true, -1, 150, results, "SecurityAnswer");
            Validation.IsStringLengthMatch(entity.Comment, true, false, true, -1, 50, results, "Comment");
            Validation.IsStringLengthMatch(entity.LockOutReason, true, false, true, -1, 50, results, "LockOutReason");
            return(initialErrorCount == results.Count);
        }
Beispiel #19
0
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool   useTarget           = validationEvent.Target != null;
            string fileName            = useTarget ? (string)target : _fileName;

            int initialErrorCount = results.Count;

            // Check file name was provided.
            bool isNullOrEmpty = string.IsNullOrEmpty(fileName);

            if (!ValidationUtils.Validate(isNullOrEmpty, results, string.Empty, "File not provided.", null))
            {
                return(false);
            }

            // Check that the file has an extension.
            int ndxExtensionPeriod = fileName.LastIndexOf(".");

            if (!ValidationUtils.Validate(ndxExtensionPeriod < 0, results, string.Empty, _errorMessagePrefix, null))
            {
                return(false);
            }

            // Error could occurr with file name = test. (ok for now)
            // Check for .txt extension.
            string fileExtension = fileName.Substring(ndxExtensionPeriod + 1);

            fileExtension = fileExtension.Trim().ToLower();

            // Check if valid format.
            if (!IsValidFormat(fileExtension))
            {
                results.Add(string.Empty, _errorMessagePrefix, null);
            }

            return(results.Count == initialErrorCount);
        }
        /// <summary>
        /// Validate the rule against the data.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            // No need to validate location if online.
            if (_isOnline)
            {
                return(true);
            }

            // Clear out errors and keep track of initial error count.
            int initialErrorCount = results.Count;

            // Check for names instead of ids.
            CheckCountryStateNames();

            bool isCountryUSA = _countryId == LocationConstants.CountryId_USA;

            // Check fields, city, stateid, countryId, zip
            ValidationUtils.Validate(string.IsNullOrEmpty(_city), results, "City", "City is required.");
            ValidationUtils.Validate(string.IsNullOrEmpty(_zip), results, "Zip", "Zip code is invalid");
            ValidationUtils.Validate(_countryId <= 0, results, "Country", "Country is required.");
            ValidationUtils.Validate((isCountryUSA && _stateId <= 0), results, "State", "State is not selected");

            // Any errors ?
            if (results.Count > initialErrorCount)
            {
                return(false);
            }

            // Check Country - State combination.
            bool validStateCountryCombo = LocationHelper.IsValidStateCountryRelation(_stateLookup, _countryLookup, _stateId, _countryId);

            ValidationUtils.Validate(!validStateCountryCombo, results, string.Empty, "State and country not a valid combination.");

            // We found the city. Now compare that
            return(results.Count == initialErrorCount);
        }
        /// <summary>
        /// Validate the rule against the data.
        /// </summary>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;
            bool useTarget             = validationEvent.Target != null;

            string[] sentences         = useTarget ? (string[])target : _sentences;
            int      initialErrorCount = results.Count;

            foreach (string sentence in sentences)
            {
                if (!string.IsNullOrEmpty(sentence))
                {
                    string lowerKeyWords = sentence.ToLower();
                    if (ContainsAnySqlWords(sentence))
                    {
                        results.Add("Invalid search criteria in keywords.");
                    }
                }
            }
            return(initialErrorCount == results.Count);
        }
Beispiel #22
0
        /// <summary>
        /// Validation method for the entity.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="useTarget">if set to <c>true</c> [use target].</param>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            object             target  = validationEvent.Target;
            IValidationResults results = validationEvent.Results;

            int          initialErrorCount = results.Count;
            StatusUpdate entity            = (StatusUpdate)target;

            Validation.IsStringLengthMatch(entity.Computer, false, false, true, -1, 30, results, "Computer");
            Validation.IsStringLengthMatch(entity.ExecutionUser, false, true, true, 1, 30, results, "ExecutionUser");
            Validation.IsDateWithinRange(entity.BusinessDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "BusinessDate");
            Validation.IsStringLengthMatch(entity.BatchName, false, true, true, 1, 30, results, "BatchName");
            Validation.IsNumericWithinRange(entity.BatchId, false, false, -1, -1, results, "BatchId");
            Validation.IsDateWithinRange(entity.BatchTime, false, false, DateTime.MinValue, DateTime.MaxValue, results, "BatchTime");
            Validation.IsStringLengthMatch(entity.Task, false, true, true, 1, 50, results, "Task");
            Validation.IsStringLengthMatch(entity.Status, false, true, true, 1, 30, results, "Status");
            Validation.IsDateWithinRange(entity.StartTime, false, false, DateTime.MinValue, DateTime.MaxValue, results, "StartTime");
            Validation.IsDateWithinRange(entity.EndTime, false, false, DateTime.MinValue, DateTime.MaxValue, results, "EndTime");
            Validation.IsStringLengthMatch(entity.Ref, true, false, true, -1, 30, results, "Ref");
            Validation.IsStringLengthMatch(entity.Comment, true, false, true, -1, 150, results, "Comment");

            return(initialErrorCount == results.Count);
        }
Beispiel #23
0
        private ValidationStatus?GetValidationStatus(IValidationRequest request, ValidationEvent validationEvent)
        {
            switch (validationEvent)
            {
            case ValidationEvent.ValidatorException:
            case ValidationEvent.BeforeVirusScanRequest:
            case ValidationEvent.VirusScanRequestSent:
            case ValidationEvent.VirusScanRequestFailed:
                return(ValidationStatus.Incomplete);

            case ValidationEvent.PackageClean:
                return(ValidationStatus.Succeeded);

            case ValidationEvent.PackageNotClean:
            case ValidationEvent.NotCleanReason:
            case ValidationEvent.ScanFailed:
            case ValidationEvent.ScanFailureReason:
                _logger.LogError(
                    Error.VcsValidationFailureAuditFound,
                    "A failed audit result was found for {validationId} ({packageId} {packageVersion}): {validationEvent}.",
                    request.ValidationId,
                    request.PackageId,
                    request.PackageVersion,
                    validationEvent);
                return(ValidationStatus.Failed);

            default:
                _logger.LogError(
                    Error.VcsValidationUnexpectedAuditFound,
                    "An unexpected audit result was found for {validationId} ({packageId} {packageVersion}): {validationEvent}.",
                    request.ValidationId,
                    request.PackageId,
                    request.PackageVersion,
                    validationEvent);
                return(ValidationStatus.Failed);
            }
        }
            /// <summary>
            /// Do some custom validation on a user name(string).
            /// </summary>
            /// <param name="validationEvent"></param>
            /// <returns></returns>
            protected override bool ValidateInternal(ValidationEvent validationEvent)
            {
                string id = (string)validationEvent.Target;

                if (string.IsNullOrEmpty(id))
                {
                    validationEvent.Results.Add("Must supply a userid.");
                    return(false);
                }

                id = id.ToLower();
                if (id == "admin" || id == "administrator")
                {
                    validationEvent.Results.Add("Admin user name is reserved, you can not use it.");
                    return(false);
                }

                if (id.Length < 2 || id.Length > 15)
                {
                    validationEvent.Results.Add("Must be between 2 >= username <= 15.");
                    return(false);
                }
                return(true);
            }
Beispiel #25
0
        /// <summary>
        /// Validation method for the entity.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="useTarget">if set to <c>true</c> [use target].</param>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            var val = new Validator((valEvent) =>
            {
                int initialErrorCount      = validationEvent.Results.Count;
                IValidationResults results = validationEvent.Results;
                Event entity = (Event)validationEvent.Target;
                Validation.IsStringLengthMatch(entity.Title, false, true, true, 10, 150, results, "Title");
                Validation.IsStringLengthMatch(entity.Summary, false, false, true, -1, 200, results, "Summary");
                Validation.IsStringLengthMatch(entity.Description, false, false, false, -1, -1, results, "Description");
                Validation.IsDateWithinRange(entity.StartDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "StartDate");
                Validation.IsDateWithinRange(entity.EndDate, false, false, DateTime.MinValue, DateTime.MaxValue, results, "EndDate");
                Validation.IsNumericWithinRange(entity.StartTime, false, false, -1, -1, results, "StartTime");
                Validation.IsNumericWithinRange(entity.EndTime, false, false, -1, -1, results, "EndTime");
                Validation.IsStringRegExMatch(entity.Email, false, RegexPatterns.Email, results, "Email");
                Validation.IsStringRegExMatch(entity.Phone, false, RegexPatterns.PhoneUS, results, "Phone");
                Validation.IsStringRegExMatch(entity.Url, false, RegexPatterns.Url, results, "Url");
                Validation.IsStringLengthMatch(entity.Keywords, true, false, true, -1, 100, results, "Keywords");

                return(initialErrorCount == validationEvent.Results.Count);
            });

            return(val.IsValid);
        }
Beispiel #26
0
 /// <summary>
 /// This Method will call the ValidateInternal method of this validator.
 /// </summary>
 /// <remarks>
 /// The reason that the ValidateInternal method is NOT called directly by the
 /// other Validate methods is because the CodeGenerator generates the Validation
 /// code inside of the ValidateInternal method.
 /// If a client wants to override the validation while sill leveraging the autogenerated
 /// validation code, it can be done by overrideing this method and calling the
 /// ValidateInternal method.
 /// This allows a lot of flexibility for codegeneration.
 /// </remarks>
 /// <param name="target"></param>
 /// <param name="useTarget"></param>
 /// <param name="results"></param>
 /// <returns></returns>
 public virtual bool Validate(ValidationEvent validationEvent)
 {
     return ValidateInternal(validationEvent);
 }
 /// <summary>
 /// Nothing in the base class.
 /// </summary>
 /// <param name="validationEvent"></param>
 /// <returns></returns>
 protected override bool ValidateInternal(ValidationEvent validationEvent)
 {
     return(true);
 }
Beispiel #28
0
 protected void WriteAuditEntry(List <PackageValidationAuditEntry> auditEntries, string message, ValidationEvent validationEvent)
 {
     auditEntries.Add(new PackageValidationAuditEntry
     {
         Timestamp     = DateTimeOffset.UtcNow,
         ValidatorName = Name,
         Message       = message,
         EventId       = validationEvent,
     });
 }
Beispiel #29
0
 public void InvokeValidationEvent()
 {
     ValidationEvent.Invoke();
 }
Beispiel #30
0
 /// <summary>
 /// This Method will call the ValidateInternal method of this validator.
 /// </summary>
 /// <remarks>
 /// The reason that the ValidateInternal method is NOT called directly by the
 /// other Validate methods is because the CodeGenerator generates the Validation
 /// code inside of the ValidateInternal method.
 /// If a client wants to override the validation while sill leveraging the autogenerated
 /// validation code, it can be done by overrideing this method and calling the
 /// ValidateInternal method.
 /// This allows a lot of flexibility for codegeneration.
 /// </remarks>
 /// <param name="validationEvent">Validation event.</param>
 /// <returns>Validation result.</returns>
 public virtual bool Validate(ValidationEvent validationEvent)
 {
     return(ValidateInternal(validationEvent));
 }
Beispiel #31
0
        /// <summary>
        /// Implement this method.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected virtual bool ValidateInternal(ValidationEvent validationEvent)
        {
            if (_validatorLamda != null)
                return _validatorLamda(validationEvent);

            return true;
        }
        /// <summary>
        /// Validates all the rules in the internal rule list.
        /// </summary>
        /// <param name="validationEvent"></param>
        /// <returns></returns>
        protected override bool ValidateInternal(ValidationEvent validationEvent)
        {
            // Should this even be here?
            if (_validatorLamda != null)
                return _validatorLamda(validationEvent);

            // Run the validations against all the rules.
            int initialErrorCount = validationEvent.Results.Count;
            foreach (var rule in _rules)
            {
                rule.Rule(validationEvent);
            }
            return validationEvent.Results.Count == initialErrorCount;
        }
Beispiel #33
0
 /// <summary>
 /// Implement this method.
 /// </summary>
 /// <param name="validationEvent"></param>
 /// <returns></returns>
 protected abstract bool ValidateInternal(ValidationEvent validationEvent);