Esempio n. 1
0
 public void Ctor_ValidationResult_ReturnsClone()
 {
     ValidationResult validationResult = new ValidationResult("ErrorMessage", new string[] { "Member1", "Member2" });
     ValidationResultSubClass createdValidationResult = new ValidationResultSubClass(validationResult);
     Assert.Equal(validationResult.ErrorMessage, createdValidationResult.ErrorMessage);
     Assert.Equal(validationResult.MemberNames, createdValidationResult.MemberNames);
 }
        public IValidationResult Run(MappingSet set)
        {
            ValidationResult result = new ValidationResult(this);

            if (set.EntitySet == null)
            {
                result.Issues.Add(new ValidationIssue("No Entities are present in the Entity Model", set, ValidationErrorLevel.Warning));
                return result;
            }
            if (set.EntitySet.IsEmpty)
            {
                result.Issues.Add(new ValidationIssue("No Entities are present in the Entity Model", set.EntitySet, ValidationErrorLevel.Warning));
                return result;
            }
            var inheritedEntities = set.EntitySet.Entities.Where(e => e.Parent != null);

            //foreach (var childEntity in inheritedEntities)
            //{
            //    var parent = childEntity.Parent;

            //    foreach (Property property in parent.Key.Properties.Distinct(p => p.Name))
            //        if (childEntity.ConcreteProperties.Any(p => p.Name == property.Name) == false && EntityImpl.DetermineInheritanceTypeWithParent(childEntity) != EntityImpl.InheritanceType.TablePerClassHierarchy)
            //            result.Issues.Add(new ValidationIssue(string.Format("Key Property {0} is missing from child Entity named {1}", property.Name, childEntity.Name), childEntity, ValidationErrorLevel.Error));
            //}
            return result;
        }
        public IValidationResult[] Validate()
        {
            ValidationResult result = new ValidationResult("inlineBinaryContent");

            result.Passed = true;
            if (iCalendar != null)
            {                
                foreach (UniqueComponent uc in iCalendar.UniqueComponents)
                {
                    if (uc.Attach != null)
                    {
                        foreach (Binary b in uc.Attach)
                        {
                            // Inline binary content (i.e. BASE64-encoded attachments) are not
                            // recommended, and should only be used when absolutely necessary.
                            if (string.Equals(b.Encoding, "BASE64", StringComparison.InvariantCultureIgnoreCase))
                            {
                                result.Passed = false;
                                result.Errors = new IValidationError[]
                                { 
                                    new ValidationErrorWithLookup("inlineBinaryContentError", ValidationErrorType.Warning, false)
                                };
                            }
                        }

                        if (result.Passed != null)
                            break;
                    }                    
                }
            }

            return new IValidationResult[] { result };
        }
Esempio n. 4
0
 public static void Can_construct_get_and_set_ErrorMessage()
 {
     var validationResult = new ValidationResult("SomeErrorMessage");
     Assert.Equal("SomeErrorMessage", validationResult.ErrorMessage);
     validationResult.ErrorMessage = "SomeOtherErrorMessage";
     Assert.Equal("SomeOtherErrorMessage", validationResult.ErrorMessage);
 }
        public IValidationResult Run(MappingSet set)
        {
            IValidationResult result = new ValidationResult(this);

            DatabaseProcessor proc = new DatabaseProcessor();
            var mergeResults = proc.MergeDatabases(_realDatabase, set.Database);

            if (mergeResults.AnyChanges)
            {
                foreach (TableAdditionOperation tableOp in mergeResults.TableOperations.OfType<TableAdditionOperation>())
                {
                    // Additions show things that are in the generated database schema and not in the real one.
                    result.Issues.Add(new ValidationIssue("Table exists in your NHibernate mapping files but not in your database",
                                                          tableOp.Object, ValidationErrorLevel.Warning));
                }

                foreach (ColumnAdditionOperation columnOp in mergeResults.ColumnOperations.OfType<ColumnAdditionOperation>())
                {
                    result.Issues.Add(new ValidationIssue("Column exists in your NHibernate mapping files but not in your database",
                                                          columnOp.Object, ValidationErrorLevel.Warning));
                }
            }

            return result;
        }
Esempio n. 6
0
        public void ValidationResult_HasValid_Defaults()
        {
            var result = new ValidationResult();

            Assert.IsTrue(result.IsSuccessful);
            Assert.IsNotNull(result.Failures);
        }
        public void ValidationResult_Ctors() {
            ValidationResult result = new ValidationResult(null);
            Assert.IsNull(result.ErrorMessage);
            Assert.IsTrue(!result.MemberNames.Any());

            result = new ValidationResult(string.Empty);
            Assert.AreEqual(string.Empty, result.ErrorMessage);
            Assert.IsTrue(!result.MemberNames.Any());

            result = new ValidationResult("stuff");
            Assert.AreEqual("stuff", result.ErrorMessage);
            Assert.IsTrue(!result.MemberNames.Any());

            result = new ValidationResult("stuff", new string[] { "m1", "m2" });
            Assert.AreEqual("stuff", result.ErrorMessage);
            IEnumerable<string> memberNames = result.MemberNames;
            Assert.AreEqual(2, memberNames.Count());
            Assert.IsTrue(memberNames.Contains("m1"));
            Assert.IsTrue(memberNames.Contains("m2"));

#if !SILVERLIGHT
            ValidationResult original = new ValidationResult("error", new string[] { "a", "b" });
            result = new DerivedValidationResult(original);
            Assert.AreEqual("error", result.ErrorMessage);
            CollectionAssert.AreEquivalent(new string[] { "a", "b" }, result.MemberNames.ToList());

            ExceptionHelper.ExpectArgumentNullException(delegate() {
                new DerivedValidationResult(null);
            }, "validationResult");
#endif
        }
        /// <summary>
        /// Determines whether the collection contains an equivalent ValidationResult
        /// </summary>
        /// <param name="collection">ValidationResults to search through</param>
        /// <param name="target">ValidationResult to search for</param>
        /// <returns></returns>
        public static bool ContainsEqualValidationResult(this ICollection<ValidationResult> collection, ValidationResult target)
        {
            foreach (ValidationResult oldValidationResult in collection)
            {
                if (oldValidationResult.ErrorMessage == target.ErrorMessage)
                {
                    bool movedOld = true;
                    bool movedTarget = true;
                    IEnumerator<string> oldEnumerator = oldValidationResult.MemberNames.GetEnumerator();
                    IEnumerator<string> targetEnumerator = target.MemberNames.GetEnumerator();
                    while (movedOld && movedTarget)
                    {
                        movedOld = oldEnumerator.MoveNext();
                        movedTarget = targetEnumerator.MoveNext();

                        if (!movedOld && !movedTarget)
                        {
                            return true;
                        }
                        if (movedOld != movedTarget || oldEnumerator.Current != targetEnumerator.Current)
                        {
                            break;
                        }
                    }
                }
            }
            return false;
        }
 /// <summary>
 /// Adds a new ValidationResult to the collection if an equivalent does not exist.
 /// </summary>
 /// <param name="collection">ValidationResults to search through</param>
 /// <param name="value">ValidationResult to add</param>
 public static void AddIfNew(this ICollection<ValidationResult> collection, ValidationResult value)
 {
     if (!collection.ContainsEqualValidationResult(value))
     {
         collection.Add(value);
     }
 }
 public ValidationResult Validate(IEnumerable<string> userAssemblies, params object[] options)
 {
   string arguments = this.BuildGendarmeCommandLineArguments(userAssemblies);
   ValidationResult validationResult = new ValidationResult()
   {
     Success = true,
     Rule = (IValidationRule) this,
     CompilerMessages = (IEnumerable<CompilerMessage>) null
   };
   try
   {
     validationResult.Success = GendarmeValidationRule.StartManagedProgram(this._gendarmeExePath, arguments, (CompilerOutputParserBase) new GendarmeOutputParser(), ref validationResult.CompilerMessages);
   }
   catch (Exception ex)
   {
     validationResult.Success = false;
     // ISSUE: explicit reference operation
     // ISSUE: explicit reference operation
     (^@validationResult).CompilerMessages = (IEnumerable<CompilerMessage>) new CompilerMessage[1]
     {
       new CompilerMessage()
       {
         file = "Exception",
         message = ex.Message,
         line = 0,
         column = 0,
         type = CompilerMessageType.Error
       }
     };
   }
   return validationResult;
 }
Esempio n. 11
0
        public void Passing_null_broken_rules_should_create_valid_instance()
        {
            var result = new ValidationResult(null);

            Assert.That(result.IsValid, Is.True);
            Assert.That(result.BrokenRules, Is.Empty);
        }
Esempio n. 12
0
        public ValidationResult Validate()
        {
            ValidationResult result = new ValidationResult();
            result.Success = true;
            result.ValidationMessage = null;

            if ( _args["h"] == null && _args["help"] == null )
            {
                string[] validSubtitleAbbrivations = new string[] { "str", "sv", "mdvd", "stl", "txt" };

                string subArg = (string)_args["sub"];
                if ( subArg != null && validSubtitleAbbrivations.Contains( subArg.ToUpper() ) )
                {
                    result.Success = false;
                    result.ValidationMessage = $"'{subArg}' is an unsupported subtitle format";
                }

                string framerateArg = (string)_args["fr"];
                if ( framerateArg != null &&
                     !framerateArg.Equals( "NTSC", StringComparison.OrdinalIgnoreCase ) &&
                     !framerateArg.Equals( "PAL", StringComparison.OrdinalIgnoreCase ) )
                {
                    double framerateParseResult;
                    if ( !Double.TryParse( framerateArg, out framerateParseResult ) )
                    {
                        result.Success = false;
                        result.ValidationMessage = $"'{framerateArg}' is not a supported frame rate";
                    }
                }

                string chapterArg = (string)_args["chp"];
                if ( chapterArg != null &&
                     !chapterArg.Equals( "ifo", StringComparison.OrdinalIgnoreCase ) &&
                     !chapterArg.Equals( "sm", StringComparison.OrdinalIgnoreCase ) )
                {
                    result.Success = false;
                    result.ValidationMessage = $"'{chapterArg} is not a supported chapter format";
                }

                if ( (string)_args["F"] == null )
                {
                    result.Success = false;
                    result.ValidationMessage = "No files were specified";
                }

                string subtitlePrefixFilename = (string)_args["spf"];
                if ( !String.IsNullOrEmpty( subtitlePrefixFilename ) && 
                     !subtitlePrefixFilename.Equals( "auto", StringComparison.OrdinalIgnoreCase ) )
                {
                    FileInfo subtitlePrefixFileInfo = new FileInfo( subtitlePrefixFilename );
                    if ( !subtitlePrefixFileInfo.Exists )
                    {
                        result.Success = false;
                        result.ValidationMessage = $"Subtitle prefix filename, '{subtitlePrefixFilename}' doesn't exist";
                    }
                }
            }

            return result;
        }
Esempio n. 13
0
        public ValidationResult<Record> Validate(Record record)
        {
            var result = new ValidationResult<Record>();

            ValidatePath(record, result);
            ValidateTitle(record, result);
            ValidateKeywords(record, result);
            ValidateDatasetReferenceDate(record, result);
            ValidateTemporalExtent(record, result);
            ValidateTopicCategory(record, result);
            ValidateResourceLocator(record, result);
            ValidateResponsibleOrganisation(record, result);
            ValidateMetadataPointOfContact(record, result);
            ValidateResourceType(record, result);
            ValidateSecurityInvariants(record, result);
            ValidatePublishableInvariants(record, result);
            ValidateBoundingBox(record, result);
            ValidateJnccSpecificRules(record, result);

            if (record.Validation == Validation.Gemini)
            {
                PerformGeminiValidation(record, result);
            }

            return result;
        }
Esempio n. 14
0
        public void Default_constructor_should_create_valid_instance()
        {
            var result = new ValidationResult();

            Assert.That(result.IsValid, Is.True);
            Assert.That(result.BrokenRules, Is.Empty);
        }
Esempio n. 15
0
 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);
 }
 public void Setup()
 {
     result = new ValidationResult(new[] {
                                             new ValidationFailure("foo", "A foo error occurred", "x"),
                                             new ValidationFailure("bar", "A bar error occurred", "y"),
                                         });
 }
 public static ValidationResult Interpret(
     this IEnumerable<IInterpreter> interpreters,
     string validationGroup,
     Exception exception
     )
 {
     if (null == interpreters)
         return null;
     if (null == exception)
         throw new ArgumentNullException("exception");
     var r = new ValidationResult()
     {
         Exception = exception,
         Message = exception.Message,
         ValidationGroup = validationGroup
     };
     foreach (var i in interpreters)
     {
         if (null == i)
             continue;
         XElement furtherInformation = null;
         string updatedMessage = String.Empty;
         if (
             i.Interpret(exception, out furtherInformation, ref updatedMessage) == InterpretationStatus.Interpreted
             )
         {
             r.FurtherInformation = furtherInformation;
             if(false == String.IsNullOrWhiteSpace(updatedMessage))
                 r.Message = updatedMessage;
             return r;
         }
     }
     return r;
 }
        protected override ValidationResult ValidateUrls(IEnumerable<string> urls, IValidatorReportTextWriter writer, string outputPath)
        {
            var result = new ValidationResult();

            if (urls.Count() > 0)
            {
                // Copy the images and CSS files for the HTML documents
                mResourceCopier.CopyResources(outputPath);
            }

            // Process urls
            foreach (var url in urls)
            {
                string fileName = Path.Combine(outputPath, mFileNameGenerator.GenerateFileName(url, "html"));
                using (var outputStream = mStreamFactory.GetFileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    var report = ValidateUrl(url ,writer, outputStream);
                    AddResultTotals(result, report);

                    // Write the filename to the report
                    report.FileName = Path.GetFileName(fileName);

                    writer.WriteUrlElement(report);
                }
            }
            return result;
        }
Esempio n. 19
0
        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;
        }
 protected virtual IEnumerable<ModelValidationResult> ConvertValidationResultToModelValidationResults(ValidationResult result)
 {
     return result.Errors.Select(x => new ModelValidationResult {
         MemberName = x.PropertyName,
         Message = x.ErrorMessage
     });
 }
 public ConvertToContractRequiresFix(ValidationResult currentStatement, ValidatedContractBlock validatedContractBlock)
     : base(currentStatement, validatedContractBlock)
 {
     // TODO: refactoring required!! Not clear logic
     _precondition =
         ContractsEx.Assertions.ContractStatementFactory.TryCreatePrecondition(currentStatement.Statement);
 }
 public void ShowValidationResult(ValidationResult validationResult)
 {
     if (!validationResult.IsValid)
     {
         ShowErrors(validationResult);
     }
 }
Esempio n. 23
0
        /// <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;
        }
        /// <summary>
        /// Adds the supplied <see cref="ValidationResult"/> to its current <see cref="ValidationResultCollectionScope"/>.
        /// </summary>
        /// <param name="result">The supplied <see cref="ValidationResult"/>.</param>
        public void AddValidationResult(ValidationResult result)
        {
            var currentScope = CurrentScope;
            currentScope.ValidationResult.Add(result);

            LogManager.Log(LogLevel.Informational, result.ToString()); // log validation messages with informational level only for debugging purposes
        }
Esempio n. 25
0
        public void ShowResult(IValidationResult Result)
        {
            if (Result == null)
                Result = new ValidationResult();

            int c = 0;

            c = Result.Count(r => r.FromRule is IcDphValidator); SetCount(lblpIcDph, c);
            c = Result.Count(r => r.FromRule is KvKindValidator); SetCount(lblpDruh, c);
            c = Result.Count(r => r.FromRule is PeriodValidator || r.FromRule is YearValidator); SetCount(lblpObdobie, c);
            c = Result.Count(r => r.FromRule is NameValidator); SetCount(lblpNazov, c);
            c = Result.Count(r => r.FromRule is StateValidator); SetCount(lblpStat, c);
            c = Result.Count(r => r.FromRule is CityValidator); SetCount(lblpObec, c);
            c = Result.Count(r => r.FromRule is BlackListValidator); SetCount(lblpBlacklist, c);
            c = Result.Count(r => r.FromRule is TaxPayerValidator); SetCount(lblpTaxpayers, c);
            c = Result.Count(r => r.FromRule is CorrectionValidator); SetCount(lblpKodopravy, c);
            c = Result.Count(r => r.FromRule is GoodsValidator); SetCount(lblpTovary, c);
            c = Result.Count(r => r.FromRule is TaxRateValidator || r.FromRule is ItemTaxValidator); SetCount(lblpTaxes, c);
            c = Result.Count(r => r.ProblemObject is A1); SetCount(lblpA1, c);
            c = Result.Count(r => r.ProblemObject is A2); SetCount(lblpA2, c);
            c = Result.Count(r => r.ProblemObject is B1); SetCount(lblpB1, c);
            c = Result.Count(r => r.ProblemObject is B2); SetCount(lblpB2, c);
            c = Result.Count(r => r.ProblemObject is B3); SetCount(lblpB3, c);
            c = Result.Count(r => r.ProblemObject is C1); SetCount(lblpC1, c);
            c = Result.Count(r => r.ProblemObject is C2); SetCount(lblpC2, c);
            c = Result.Count(r => r.ProblemObject is D1); SetCount(lblpD1, c);
            c = Result.Count(r => r.ProblemObject is D2); SetCount(lblpD2, c);
        }
 public override bool IsApplicable(ValidationResult validationResult, CodeContractStatement contractStatement)
 {
     return validationResult.Match(_ => false,
         error => error.Error == MalformedContractError.ContractStatementInTheMiddleOfTheMethod &&
                  contractStatement.IsEndContractBlock,
         _ => false);
 }
Esempio n. 27
0
        public void Passing_filled_broken_rules_should_create_invalid_instance()
        {
            var result = new ValidationResult(new List<BrokenRule> { new BrokenRule(null, null, "", "", null) });

            Assert.That(result.IsValid, Is.False);
            Assert.That(result.BrokenRules.Count, Is.EqualTo(1));
        }
        public override Action<ITextControl> Apply(
            ValidationResult validationResult, CodeContractStatement contractStatement)
        {
            // This fix contains following steps:
            // 1. Removing original postcondition
            // 2. Looking for contract block of the current method
            // 3. If this block exists, fix should move postcondition to the appropriate place 
            //    (after last postcondition or precondition)
            // 4. Otherwise fix should move the precondition at the beginning of the method.

            // We should get contract block and potential target block before
            // removing current statement
            var contractBlock = GetContractBlock(contractStatement);

            var containingFunction = GetContainingFunction(contractStatement.Statement);

            contractStatement.Statement.RemoveOrReplaceByEmptyStatement();

            ICSharpStatement anchor = GetAnchor(contractBlock, contractStatement);

            ICSharpStatement updatedStatement;

            if (anchor != null)
            {
                updatedStatement = anchor.AddStatementsAfter(new[] {contractStatement.Statement}, contractStatement.Statement);
            }
            else
            {
                updatedStatement = containingFunction.Body.AddStatementAfter(contractStatement.Statement, null);
            }

            return textControl => textControl.Caret.MoveTo(updatedStatement);
        }
        public ValidationResult PerformValidation(string filePath)
        {
            XmlReaderSettings settings = this.CreateSettings();
            string markerAttributeValue = string.Empty;

            var validationResult = new ValidationResult();
            settings.ValidationEventHandler += (sender, args) =>
            {
                string attributeValue = new string(markerAttributeValue.ToCharArray());
                validationResult.Errors.Add(new ValidationResultEntry(args.Message, attributeValue));
            };

            using (XmlReader reader = XmlReader.Create(filePath, settings))
            {
                while (reader.Read())
                {
                    string elementName = reader.Name;
                    if (_markerElement.Equals(elementName))
                    {
                        bool found = reader.MoveToAttribute(_markerAttribute);
                        if (found)
                        {
                            markerAttributeValue = reader.ReadContentAsString() ?? string.Empty;
                        }
                    }
                }
            }

            return validationResult;
        }
        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;
        }
Esempio n. 31
0
 public PausaFormViewModel()
 {
     ValidationResult = new ValidationResult();
     Pausas           = new List <PausaViewModel>();
 }
Esempio n. 32
0
        private void ValidationDetail(TranDetail entity)
        {
            ValidationResults results = new ValidationResults();

            if (baseGridDetail.FormMode == ObjectState.Add)
            {
                if (entity.material_id == 0)
                {
                    ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Material"), this, string.Empty, string.Empty, null);
                    results.AddResult(result);
                }
                else
                {
                    if (entity.warehouse_id_dest != 0)
                    {
                        DataRow[] drs = this.GetDataRowDetail(entity.material_id, entity.warehouse_id_dest);
                        if (drs.Count() >= 1)
                        {
                            ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsDuplicate, "Material"), this, string.Empty, string.Empty, null);
                            results.AddResult(result);
                        }
                    }
                }

                if (entity.warehouse_id_dest == 0)
                {
                    ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Warehouse"), this, string.Empty, string.Empty, null);
                    results.AddResult(result);
                }
            }

            if (string.IsNullOrEmpty(txtLotNo.Text))
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Lot No."), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            else if (Converts.ParseDoubleNullable(txtLotNo.Text) == null)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IncorrectFormatOne, "Lot No."), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            else if (entity.lot_no == 0)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.CompareValueMore, "Lot No.", "0"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }

            if (string.IsNullOrEmpty(txtQuantity.Text))
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Quantity"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            else if (Converts.ParseDoubleNullable(txtQuantity.Text) == null)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IncorrectFormatOne, "Quantity"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            else if (entity.quantity == 0)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.CompareValueMore, "Quantity", "0"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            else
            {
                if (entity.warehouse_id_dest != 0 && entity.material_id != 0)
                {
                    if (!ServiceProvider.PhyLotService.CheckLimitMaterial(entity.material_id, entity.warehouse_id_dest, entity.quantity.Value))
                    {
                        ValidationResult result = new ValidationResult(string.Format(ErrorMessage.CompareValueLessOrEqual, "Quantity", "Max Stock"), this, string.Empty, string.Empty, null);
                        results.AddResult(result);
                    }
                }
            }

            if (results.Count > 0)
            {
                throw new ValidationException(results);
            }
        }
Esempio n. 33
0
 private static ValidationResultModel ToValidationResultModel(this ValidationResult validationResult)
 {
     return(new ValidationResultModel(validationResult));
 }
Esempio n. 34
0
 public Midia()
 {
     ValidationResult = new ValidationResult();
 }
        private async Task ValidateNewPasswordNotInRecentHistory(ChangePasswordCommand command, ValidationResult result)
        {
            var config = await _configurationService.GetAsync <EmployerUsersConfiguration>();

            var recentPasswords = command.User.PasswordHistory.OrderByDescending(p => p.DateSet).Take(config.Account.NumberOfPasswordsInHistory);

            foreach (var historicPassword in recentPasswords)
            {
                if (await _passwordService.VerifyAsync(command.NewPassword, historicPassword.Password, historicPassword.Salt, historicPassword.PasswordProfileId))
                {
                    result.AddError("NewPassword", $"Password has been used too recently. You cannot use your last {config.Account.NumberOfPasswordsInHistory} passwords");
                    return;
                }
            }
        }
 /// <summary>
 /// Adds the result.
 /// </summary>
 /// <param name="validationResult">Validation result.</param>
 public void AddResult(ValidationResult validationResult) => _results.Add(validationResult);
Esempio n. 37
0
 protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult)
 {
 }
Esempio n. 38
0
        public ValidationResult Validate(object value)
        {
            var str = value?.ToString();

            return(string.IsNullOrEmpty(str) ? ValidationResult.CreateInvalid("String must not be null or empty.") : ValidationResult.CreateValid());
        }
Esempio n. 39
0
 protected Entity()
 {
     ValidationResult = new ValidationResult();
 }
Esempio n. 40
0
        public ValidationResult <string> ValidateStudentSubject(Guid studentId, Guid examId, Guid currentId = default)
        {
            var output = new ValidationResult <string>()
            {
                IsSuccess = true
            };

            var studentSubject    = new StudentSubject();
            var studentBySubjects = new List <StudentSubject>();

            studentBySubjects = studentSubject.StudentBySubjects(studentId);
            var exam = new Exam();

            exam = FindExam(ExamId);

            if (exam == null)
            {
                output.IsSuccess = false;
                output.Errors.Add("No has seleccionado ningún Examen");
            }

            else
            {
                studentSubject = studentBySubjects.FirstOrDefault(x => x.SubjectId == exam.SubjectId);


                //On Delete
                if (currentId != default)
                {
                    output.IsSuccess = true;
                }

                //On Create
                else
                {
                    if (studentId == default)
                    {
                        output.IsSuccess = false;
                        output.Errors.Add("el Student no puede estar vacío");
                    }

                    else
                    {
                        if (exam.SubjectId == default)
                        {
                            output.IsSuccess = false;
                            output.Errors.Add("la Asignatura no puede estar vacío");
                        }

                        else
                        {
                            if (studentSubject == null)
                            {
                                output.IsSuccess = false;
                                output.Errors.Add("El Student no está matriculado de la Asignatura");
                            }
                        }
                    }
                }
            }

            return(output);
        }
 public AtividadeApoio()
 {
     ValidationResult = new ValidationResult();
 }
        public void Validate(ValidationResult result, Actions action)
        {
            if (EntityHeader.IsNullOrEmpty(TransmitterType))
            {
                result.AddUserError(PipelineAdminResources.Err_TransmitterTypeIsRequired);
                return;
            }

            switch (TransmitterType.Value)
            {
            case TransmitterTypes.AzureEventHub:
                if (string.IsNullOrEmpty(HostName))
                {
                    result.AddUserError("Host Name is a Required Field.");
                }
                if (string.IsNullOrEmpty(HubName))
                {
                    result.AddUserError("Hub Name is a Required Field.");
                }
                if (string.IsNullOrEmpty(AccessKeyName))
                {
                    result.AddUserError("Access Key Name is a Required Field.");
                }
                if (action == Actions.Create && string.IsNullOrEmpty(AccessKey))
                {
                    result.AddUserError("Access Key is Required for an Azure Event Hub.");
                }
                if (action == Actions.Update && string.IsNullOrEmpty(AccessKey) && string.IsNullOrEmpty(SecureAccessKeyId))
                {
                    result.AddUserError("Access Key is Required for an Azure Event Hub.");
                }
                if (!string.IsNullOrEmpty(AccessKey) && !Utils.StringValidationHelper.IsBase64String(AccessKey))
                {
                    result.AddUserError("Access Key does not appear to be a Base 64 string and is likely incorrect.");
                }
                break;

            case TransmitterTypes.AzureIoTHub:
                if (string.IsNullOrEmpty(HostName))
                {
                    result.AddUserError("Host Name is a Required Field.");
                }
                if (string.IsNullOrEmpty(AccessKeyName))
                {
                    result.AddUserError("Access Key Name is a Required Field.");
                }
                if (action == Actions.Create && string.IsNullOrEmpty(AccessKey))
                {
                    result.AddUserError("Access Key is Required for Azure IoT Event Hub.");
                }
                if (action == Actions.Update && string.IsNullOrEmpty(AccessKey) && string.IsNullOrEmpty(SecureAccessKeyId))
                {
                    result.AddUserError("Access Key is Required for Azure IoT Event Hub.");
                }
                if (!string.IsNullOrEmpty(AccessKey) && !Utils.StringValidationHelper.IsBase64String(AccessKey))
                {
                    result.AddUserError("Access Key does not appear to be a Base 64 string and is likely incorrect.");
                }
                break;

            case TransmitterTypes.AzureServiceBus:
                if (string.IsNullOrEmpty(HostName))
                {
                    result.AddUserError("Host Name is a Required Field.");
                }
                if (string.IsNullOrEmpty(Queue))
                {
                    result.AddUserError("Queue is a Required Field.");
                }
                if (string.IsNullOrEmpty(AccessKeyName))
                {
                    result.AddUserError("Access Key Name is a Required Field.");
                }
                if (action == Actions.Create && string.IsNullOrEmpty(AccessKey))
                {
                    result.AddUserError("Access Key is Required for an Azure Service Bus Transmitter.");
                }
                if (action == Actions.Update && string.IsNullOrEmpty(AccessKey) && string.IsNullOrEmpty(SecureAccessKeyId))
                {
                    result.AddUserError("Access Key is Required for an Azure Service Bus Transmitter.");
                }
                if (!string.IsNullOrEmpty(AccessKey) && !Utils.StringValidationHelper.IsBase64String(AccessKey))
                {
                    result.AddUserError("Access Key does not appear to be a Base 64 string and is likely incorrect.");
                }
                break;

            case TransmitterTypes.MQTTClient:
                if (string.IsNullOrEmpty(HostName))
                {
                    result.AddUserError("Host Name is a Required Field.");
                }
                if (!ConnectToPort.HasValue)
                {
                    result.AddUserError("Port is a Required field, this is usually 1883 or 8883 for a secure connection.");
                }
                if (!Anonymous)
                {
                    if (String.IsNullOrEmpty(UserName))
                    {
                        result.AddUserError("User Name is Required for non-Anonymous Connections.");
                    }
                    if (action == Actions.Create)
                    {
                        if (String.IsNullOrEmpty(Password))
                        {
                            result.AddUserError("Password is Required for non-Anonymous Connections");
                        }
                    }
                    else if (action == Actions.Update)
                    {
                        if (String.IsNullOrEmpty(Password) && String.IsNullOrEmpty(SecurePasswordId))
                        {
                            result.AddUserError("Password is Required for non-Anonymous Connections");
                        }
                    }
                }
                else
                {
                    this.Password = null;
                    this.UserName = null;
                }
                break;

            case TransmitterTypes.OriginalListener:
                break;

            case TransmitterTypes.Rest:
                if (string.IsNullOrEmpty(HostName))
                {
                    result.AddUserError("Host Name is a Required Field.");
                }
                if (String.IsNullOrEmpty(UserName) && !String.IsNullOrEmpty(Password))
                {
                    result.AddUserError("If User Name is Provided, Password must also be provided.");
                }
                if (!Anonymous)
                {
                    if (String.IsNullOrEmpty(UserName))
                    {
                        result.AddUserError("User Name is Required for non-Anonymous Connections.");
                    }
                    if (String.IsNullOrEmpty(UserName))
                    {
                        result.AddUserError("User Name is Required for non-Anonymous Connections.");
                    }
                    if (action == Actions.Create)
                    {
                        if (String.IsNullOrEmpty(Password))
                        {
                            result.AddUserError("Password is Required for non-Anonymous Connections");
                        }
                    }
                    else if (action == Actions.Update)
                    {
                        if (String.IsNullOrEmpty(Password) && String.IsNullOrEmpty(SecurePasswordId))
                        {
                            result.AddUserError("Password is Required for non-Anonymous Connections");
                        }
                    }
                }
                else
                {
                    this.Password = null;
                    this.UserName = null;
                }

                if (Headers == null)
                {
                    Headers = new List <Header>();
                }
                Headers.RemoveAll(hdr => String.IsNullOrEmpty(hdr.Name) && String.IsNullOrEmpty(hdr.Value));

                foreach (var header in Headers)
                {
                    if (string.IsNullOrEmpty(header.Name) || string.IsNullOrEmpty(header.Value))
                    {
                        result.AddUserError("Invalid Header Value, Name and Value are both Required.");
                    }
                }

                break;
            }
        }
        public void Be_Valid()
        {
            ValidationResult validationResult = ResetWalletRequestValidator.TestValidate(ResetWalletRequest);

            validationResult.IsValid.Should().BeTrue();
        }
 protected override void Validate(Question obj, ValidationResult result)
 {
 }
        public void DomainContext_Submit_DomainMethodsThrow_EntityValidationError()
        {
            List <string>[] propChanged = new List <string>[] { new List <string>(), new List <string>(), new List <string>() };
            int             refZip      = 0;

            CityDomainContext citiesProvider = new CityDomainContext(TestURIs.Cities);
            SubmitOperation   so             = null;
            LoadOperation     lo             = citiesProvider.Load(citiesProvider.GetZipsQuery(), false);

            // wait for Load to complete, then invoke some domain methods
            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                // invoke methods that cause exception
                Zip[] zips = citiesProvider.Zips.ToArray();
                citiesProvider.ThrowException(zips[0], "EntityValidationException");
                citiesProvider.ThrowException(zips[1], "EntityValidationException");

                // invoke method that does not cause exception
                zips[2].ReassignZipCode(1, true);
                refZip = zips[2].Code;

                zips[0].PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                {
                    propChanged[0].Add(e.PropertyName);
                };
                zips[1].PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                {
                    propChanged[1].Add(e.PropertyName);
                };
                zips[2].PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                {
                    propChanged[2].Add(e.PropertyName);
                };

                so = citiesProvider.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);
            });
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                Assert.IsNotNull(so.Error);
                DomainOperationException ex = so.Error as DomainOperationException;

                // this is a case where method invocations causes a ValidationException.
                Assert.AreEqual(OperationErrorStatus.ValidationFailed, ex.Status);
                Assert.AreEqual(Resource.DomainContext_SubmitOperationFailed_Validation, ex.Message);

                // verify ValidationError collection is correct
                Zip[] zips = citiesProvider.Zips.ToArray();
                IEnumerable <ValidationResult> errors = zips[0].ValidationErrors;
                LogErrorListContents("citiesProvider.Zips[0].ValidationErrors", errors);
                Assert.AreEqual(1, errors.Count());
                ValidationResult vr = errors.First();
                Assert.AreEqual("Invalid Zip properties!", vr.ErrorMessage);
                Assert.AreEqual(2, vr.MemberNames.Count());
                Assert.IsTrue(vr.MemberNames.Contains("CityName"));
                Assert.IsTrue(vr.MemberNames.Contains("CountyName"));

                errors = zips[1].ValidationErrors;
                LogErrorListContents("citiesProvider.Zips[0].ValidationErrors", errors);
                Assert.AreEqual(1, errors.Count());
                vr = errors.First();
                Assert.AreEqual("Invalid Zip properties!", vr.ErrorMessage);
                Assert.AreEqual(2, vr.MemberNames.Count());
                Assert.IsTrue(vr.MemberNames.Contains("CityName"));
                Assert.IsTrue(vr.MemberNames.Contains("CountyName"));

                // verify the Entity.ValidationErrors collection is populated as expected
                Assert.IsTrue(propChanged[0].Contains("HasValidationErrors"));
                Assert.IsTrue(propChanged[1].Contains("HasValidationErrors"));

                // verify entities are not auto-synced back to the client because there were errors
                Assert.IsFalse(propChanged[2].Contains("Code"));
                Assert.IsFalse(propChanged[2].Contains("FourDigit"));
                Assert.IsFalse(propChanged[2].Contains("HasValidationErrors"));
                Assert.AreEqual(0, zips[2].ValidationErrors.Count());
                Assert.AreEqual(refZip, zips[2].Code);
            });

            EnqueueTestComplete();
        }
Esempio n. 46
0
 public bool IsValid()
 {
     ValidationResult = new DoencaEstaConsistenteValidation().Validate(this);
     return(ValidationResult.IsValid);
 }
        public EmailViewModel(long atividadeId, long emailId, string corpoDoEmail, string texto, string assunto,
                              DateTime dataEmail, DateTime dataEntrada, IEnumerable <AtividadeParteEnvolvida> envolvidos, string sentido)
        {
            EmailIdProvisorio = Guid.NewGuid().ToString();
            ValidationResult  = new ValidationResult();
            Anexos            = new List <EmailAnexosViewModel>();
            AtividadeId       = atividadeId;
            EmailId           = emailId;
            Assunto           = assunto;
            Texto             = texto;
            Html        = corpoDoEmail;
            DataEmail   = dataEmail;
            DataEntrada = dataEntrada;
            Sentido     = "Não Informado";

            if (!string.IsNullOrEmpty(sentido))
            {
                Sentido = sentido.ToUpper().Trim() == "E" ? "Recebido" : "Enviado";
            }

            var sbPara        = new StringBuilder();
            var sbCopia       = new StringBuilder();
            var sbCopiaOculta = new StringBuilder();

            if (envolvidos == null)
            {
                return;
            }


            foreach (var envolvido in envolvidos)
            {
                switch (envolvido.TipoParteEnvolvida.Trim().ToUpper())
                {
                case "R":
                    Remetente      = string.IsNullOrEmpty(envolvido.Nome) ? "" : envolvido.Nome;
                    EmailRemetente = string.IsNullOrEmpty(envolvido.Email) ? "Não identificado" : envolvido.Email;
                    break;

                case "D":
                    if (sbPara.Length == 0)
                    {
                        sbPara.Append(envolvido.Email);
                    }
                    else
                    {
                        sbPara.Append("; " + envolvido.Email);
                    }
                    break;

                case "DC":
                    if (sbCopia.Length == 0)
                    {
                        sbCopia.Append(envolvido.Email);
                    }
                    else
                    {
                        sbCopia.Append("; " + envolvido.Email);
                    }
                    break;

                case "DO":
                    if (sbCopiaOculta.Length == 0)
                    {
                        sbCopiaOculta.Append(envolvido.Email);
                    }
                    else
                    {
                        sbCopiaOculta.Append("; " + envolvido.Email);
                    }
                    break;
                }
            }

            Para        = sbPara.ToString();
            Copia       = sbCopia.ToString();
            CopiaOculta = sbCopiaOculta.ToString();
        }
        public EmailViewModel(int?configuracaoContaEmaild, string tipo, long?pessoaFisicaId, long?pessoaJuridicaId,
                              SelectList configuracaoContasEmail, long?emailPaiId, long?atividadePaiId, long?atividadeId,
                              long?ocorrenciaId, long?atendimentoId, Email emailPai, string assinatura)
        {
            EmailIdProvisorio       = Guid.NewGuid().ToString();
            Anexos                  = new List <EmailAnexosViewModel>();
            ValidationResult        = new ValidationResult();
            ConfiguracaoContaEmaild = configuracaoContaEmaild;
            ConfiguracaoContasEmail = configuracaoContasEmail;
            EmailPaiId              = emailPaiId;
            AtividadePaiId          = atividadePaiId;
            OcorrenciaId            = ocorrenciaId;
            AtendimentoId           = atendimentoId;
            PessoaJuridicaId        = pessoaJuridicaId;
            PessoaFisicaId          = pessoaFisicaId;
            PotencialClienteId      = null;
            Sentido                 = "Enviado";
            DataEmail               = DateTime.Now;

            var sb = new StringBuilder();

            sb.Append("</br></br>");

            if (!string.IsNullOrEmpty(assinatura))
            {
                sb.Append("<div id='dvAssinaturaConta_" + EmailIdProvisorio + "'></div>");
            }
            else
            {
                sb.Append("<div id='dvAssinaturaConta_" + EmailIdProvisorio + "'>" + assinatura + "</div>");
            }

            if (emailPai == null)
            {
                Texto = sb.ToString();
                return;
            }

            sb.Append("</br><hr />");
            sb.Append(ObterCabecalho(emailPai));
            sb.Append(emailPai.CorpoDoEmail);

            //if (emailPai == null) return;

            //var sb = new StringBuilder();
            //sb.Append("</br></br>");
            ////ObterAssinatura -> quando definir as régras e colocar em produção
            //sb.Append("</br><hr />");
            //sb.Append(ObterCabecalho(emailPai));
            //sb.Append(emailPai.CorpoDoEmail);

            // R: Responder, T: Todos, E: Encaminhar
            Assunto = "RES: " + emailPai.Assunto;
            switch (tipo)
            {
            case "T":
                Para = emailPai.Remetente;

                if (!string.IsNullOrEmpty(emailPai.Para))
                {
                    Para = Para + "; " + emailPai.Para;
                }

                if (!string.IsNullOrEmpty(emailPai.Copia))
                {
                    Copia = emailPai.Copia;
                }
                break;

            case "R":
                Para = string.IsNullOrEmpty(emailPai.Remetente) ? emailPai.Endereco : emailPai.Remetente;
                break;

            default:
                Assunto = "ENC: " + emailPai.Assunto;

                if (emailPai.Anexos != null)
                {
                    foreach (var anexo in emailPai.Anexos.Where(w => w.ImagemCorpo == false))
                    {
                        Anexos.Add(new EmailAnexosViewModel(anexo.Id, anexo.Nome, anexo.Path, anexo.Tamanho,
                                                            anexo.Extensao));
                    }
                }
                break;
            }
            Texto = sb.ToString();
        }
Esempio n. 49
0
        public bool IsValid()
        {
            ValidationResult = new AlunoConsistenteValidation().Validate(this);

            return(ValidationResult.IsValid);
        }
Esempio n. 50
0
 public FeaturedResponse(T result, ExecutionStatusType status, ValidationResult validationResult = null) : base(
         result, status)
 {
     ValidationResult = validationResult;
 }
 private void ValidateConfirmPasswordMatchesNewPassword(ChangePasswordCommand command, ValidationResult result)
 {
     if (command.NewPassword != command.ConfirmPassword)
     {
         result.AddError("ConfirmPassword", "Passwords do not match");
     }
 }
Esempio n. 52
0
 public Task Validate(AssignPathCommand request, ValidationResult validationResult)
 {
     return(Task.CompletedTask);
 }
 public async Task <bool> IsValid()
 {
     ValidationResult = await new CreateNewPessoaFisicaCommandValidator().ValidateAsync(this);
     return(ValidationResult.IsValid);
 }
 private void ValidateNewPasswordMeetsSecurityRequirements(ChangePasswordCommand command, ValidationResult result)
 {
     if (command.NewPassword.Length < 8 || command.NewPassword.Length > 16 ||
         !command.NewPassword.HasLowerCharacters() || !command.NewPassword.HasUpperCharacters() ||
         !command.NewPassword.HasNumericCharacters())
     {
         result.AddError("NewPassword", "Password does not meet requirements");
     }
 }
 public bool IsValid(ILocalidadeRepository repository)
 {
     ResultadoValidacao = new LocalidadeAptaParaCadastroValidation(repository).Validate(this);
     return(ResultadoValidacao.IsValid);
 }
 public TestValidationResult(ValidationResult validationResult) : base(validationResult.Errors)
 {
     RuleSetsExecuted = validationResult.RuleSetsExecuted;
 }
 public void SetUp()
 {
     address   = new Address();
     validator = new AddressValidator();
     results   = new ValidationResult();
 }
        private async Task ValidateCurrentPasswordMatchesUser(ChangePasswordCommand command, ValidationResult result)
        {
            var passwordsMatch = await _passwordService.VerifyAsync(command.CurrentPassword, command.User.Password,
                                                                    command.User.Salt, command.User.PasswordProfileId);

            if (!passwordsMatch)
            {
                result.AddError("CurrentPassword", "Invalid password");
            }
        }