/// <summary>
        /// Import items into the entity repository.
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public override BoolErrorsItem <IList <T> > Import(IList <T> items)
        {
            // Check for overriden handler.
            if (_importHandler != null)
            {
                return(base.Import(items));
            }

            // Get the service for the enitity of type T.
            IEntityService <T> service = EntityRegistration.GetService <T>();

            service.Create(items);
            bool success = true;
            IValidationResults errors = new ValidationResults();
            int ndx = 1;

            foreach (T item in items)
            {
                IEntity entity = item as IEntity;
                if (entity.Errors.HasAny)
                {
                    success = false;
                    // Now copy over the errors w/ context information( e.g. 1st entity imported ).
                    errors.Add("Item # [" + ndx + "] : ");
                    entity.Errors.EachFull(err => errors.Add(err));
                }
                ndx++;
            }
            string fullError = errors.Message();

            return(new BoolErrorsItem <IList <T> >(items, success, fullError, errors));
        }
예제 #2
0
        public override ValidationResults <SourceValidationOccurance> ValidateData(ProcessedDataPackage package)
        {
            ValidationResults <SourceValidationOccurance> results = new ValidationResults <SourceValidationOccurance>();

            results.Score = -1;

            PageSourceData data = package.GetData <PageSourceData>();

            if (data == null || String.IsNullOrEmpty(data.PageSource))
            {
                return(results);
            }

            using (StringReader reader = new StringReader(data.PageSource))
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ProhibitDtd             = false;
                settings.ValidationType          = ValidationType.DTD;
                settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(

                    delegate(object sender, System.Xml.Schema.ValidationEventArgs e)
                {
                    int position = GetIndex(data.PageSource, e.Exception.LineNumber, e.Exception.LinePosition);
                    int length   = data.PageSource.Length - position > DISPLAYBUFFER ? DISPLAYBUFFER : data.PageSource.Length - position;

                    SourceValidationOccurance p = new SourceValidationOccurance(data, position, length);
                    p.Comment = e.Exception.Message;
                    results.Add(p);
                });
                settings.XmlResolver = new XHTMLXmlResolver();

                using (XmlReader xmlReader = XmlReader.Create(reader, settings))
                {
                    try
                    {
                        while (xmlReader.Read())
                        {
                        }
                    }
                    catch (System.Xml.XmlException ex)
                    {
                        int position = GetIndex(data.PageSource, ex.LineNumber, ex.LinePosition);
                        int length   = data.PageSource.Length - position > DISPLAYBUFFER ? DISPLAYBUFFER : data.PageSource.Length - position;

                        SourceValidationOccurance p = new SourceValidationOccurance(data, position, length);
                        p.Comment = ex.Message;
                        results.Add(p);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }

            results.Score = (results.Count == 0 ? 100 : 0);

            return(results);
        }
예제 #3
0
        public static BoolResult <IList <TEntity> > SPToList <TEntity>(this DataBase db, string spName, Func <IDataReader, TEntity> func, params IDataParameter[] parameters)
        {
            Guard.IsNotNull(func, "Func<IDataReader, TEntity> is null");
            ValidationResults validationResults = new ValidationResults();
            IList <TEntity>   list       = new List <TEntity>();
            IDataReader       dataReader = null;

            try
            {
                dataReader = db.ExecuteSPReader(db.ConnectionString, spName, parameters);
                while (dataReader.Read())
                {
                    list.Add(func(dataReader));
                }
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            finally
            {
                if (dataReader != null)
                {
                    dataReader.Close();
                }
            }
            return(new BoolResult <IList <TEntity> >(list, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #4
0
        public static BoolResult <IList <TEntity> > RefSPToList <TEntity>(this DataBase db, string spName, params IDataParameter[] parameters) where TEntity : class, new()
        {
            ValidationResults validationResults = new ValidationResults();
            IList <TEntity>   list       = new List <TEntity>();
            IDataReader       dataReader = null;

            try
            {
                dataReader = db.ExecuteSPReader(db.ConnectionString, spName, parameters);
                DynamicBuilder <TEntity> dynamicBuilder = DynamicBuilder <TEntity> .CreateBuilder(dataReader);

                while (dataReader.Read())
                {
                    TEntity item = dynamicBuilder.Build(dataReader);
                    list.Add(item);
                }
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            finally
            {
                if (dataReader != null)
                {
                    dataReader.Close();
                }
            }
            return(new BoolResult <IList <TEntity> >(list, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #5
0
        public static BoolResult <TEntity> RefToSingle <TEntity>(this DataBase db, string strSql, params IDataParameter[] parameters) where TEntity : class, new()
        {
            ValidationResults validationResults = new ValidationResults();
            TEntity           item       = default(TEntity);
            IDataReader       dataReader = null;

            try
            {
                dataReader = db.ExecuteReader(db.ConnectionString, CommandType.Text, strSql, parameters);
                DynamicBuilder <TEntity> dynamicBuilder = DynamicBuilder <TEntity> .CreateBuilder(dataReader);

                if (dataReader.Read())
                {
                    item = dynamicBuilder.Build(dataReader);
                }
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            finally
            {
                if (dataReader != null)
                {
                    dataReader.Close();
                }
            }
            return(new BoolResult <TEntity>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #6
0
        public static BoolResult <IList <TEntity> > SPToList <TEntity>(this DataBase db, string spName, IRowMapper <IDataReader, TEntity> rowMapper, params IDataParameter[] parameters) where TEntity : class, new()
        {
            Guard.IsNotNull(rowMapper, "IRowMapper is null");
            ValidationResults validationResults = new ValidationResults();
            IList <TEntity>   item       = new List <TEntity>();
            IDataReader       dataReader = null;

            try
            {
                dataReader = db.ExecuteSPReader(db.ConnectionString, spName, parameters);
                item       = rowMapper.MapRows(dataReader);
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            finally
            {
                if (dataReader != null)
                {
                    dataReader.Close();
                }
            }
            return(new BoolResult <IList <TEntity> >(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #7
0
        /// <summary>
        /// This checks all the rules for the table that target points too if target does not point to a table returns does not check anything
        /// </summary>
        public void CheckRule()
        {
            //Clear the list from last time
            ValidationResults.Clear();

            // Make sure the target is not null and it is an StreamPropertiesTable
            if (target != null && target is StreamPropertiesTable)
            {
                ITableAdapter tableAdapter = TableAdapterFactory.CreateTableAdapter(
                    target as StreamPropertiesTable);

                ValidationResult vr;

                if (StreamType.Chemical == (target as StreamPropertiesTable).StreamType)
                {
                    vr = unitsAreConsistant(tableAdapter);

                    if (!vr.IsEmpty)
                    {
                        ValidationResults.Add(vr);
                    }

                    vr = sumOfPartsEqualsTotalQuantity(tableAdapter);

                    if (!vr.IsEmpty)
                    {
                        ValidationResults.Add(vr);
                    }
                }
            }
        }
예제 #8
0
        private void CheckDayGender()
        {
            FiscalCodeValidationResult result = null;

            if (_generator.MainFiscalCode.DayGenderRepresentation == _fiscalCodeToValidate.DayGenderRepresentation)
            {
                result = _localizationProvider.GetLocalizedMessage("msg_day_gender_main_ok");
            }
            else if (_generator.FiscalCodes.Any(fc =>
                                                fc.DayGenderRepresentation == _fiscalCodeToValidate.DayGenderRepresentation))
            {
                result = _localizationProvider.GetLocalizedMessage("msg_day_gender_omocode_ok");
            }
            else
            {
                result = _localizationProvider.GetFormattedLocalizedMessage("msg_day_gender_wrong",
                                                                            new[]
                {
                    _generator.MainFiscalCode.DayGenderRepresentation,
                    _fiscalCodeToValidate.DayGenderRepresentation
                });
            }

            ValidationResults.Add(result);
        }
예제 #9
0
        /// <summary>
        /// Calls IsValid with the specified context (to avoid deadlocks)
        /// Try to call this instead of IsValid when possible.
        /// Note that this same validation will be done by the service layer when SaveChanges() is called
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns>
        ///   <c>true</c> if [is valid group member] [the specified rock context]; otherwise, <c>false</c>.
        /// </returns>
        public bool IsValidDocument(RockContext rockContext, out string errorMessage)
        {
            var result = base.IsValid;

            errorMessage = string.Empty;
            if (result)
            {
                var documentType = DocumentType ?? new DocumentTypeService(rockContext).Get(DocumentTypeId);

                if (documentType == null)
                {
                    errorMessage = $"Invalid document type found.";
                    ValidationResults.Add(new ValidationResult(errorMessage));
                    result = false;
                }

                if (documentType != null && documentType.MaxDocumentsPerEntity.HasValue)
                {
                    var documentsPerEntityCount = new DocumentService(rockContext)
                                                  .Queryable()
                                                  .Where(a => a.DocumentTypeId == DocumentTypeId && EntityId == this.EntityId)
                                                  .Count();

                    if (documentsPerEntityCount >= documentType.MaxDocumentsPerEntity.Value)
                    {
                        errorMessage = $"Unable to add document because there is a limit of {documentType.MaxDocumentsPerEntity} documents for this type.";
                        ValidationResults.Add(new ValidationResult(errorMessage));
                        result = false;
                    }
                }
            }

            return(result);
        }
예제 #10
0
        public static BoolResult <bool> RunTransaction(this DataBase db, Action <IDbTransaction> action)
        {
            ValidationResults validationResults = new ValidationResults();
            IDbConnection     connection        = db.GetConnection(db.ConnectionString);

            connection.Open();
            IDbTransaction dbTransaction = connection.BeginTransaction();

            try
            {
                action(dbTransaction);
                dbTransaction.Commit();
            }
            catch (Exception ex)
            {
                dbTransaction.Rollback();
                validationResults.Add(ex.Message);
            }
            finally
            {
                if (connection != null || connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    connection.Dispose();
                }
            }
            return(new BoolResult <bool>(validationResults.IsValid, validationResults.IsValid, string.Empty, validationResults));
        }
        /// <summary>
        /// Prüft das Eingabeelement auf Korrektheit der Daten
        /// </summary>
        public override void Validate()
        {
            if (Disabled)
            {
                return;
            }

            if (Required && string.IsNullOrWhiteSpace(base.Value))
            {
                ValidationResults.Add(new ValidationResult()
                {
                    Type = TypesInputValidity.Error, Text = "Das Textfeld darf nicht leer sein!"
                });

                return;
            }

            if (!string.IsNullOrWhiteSpace(MinLength) && Convert.ToInt32(MinLength) > base.Value.Length)
            {
                ValidationResults.Add(new ValidationResult()
                {
                    Type = TypesInputValidity.Error, Text = "Der Text entsprcht nicht der minimalen Länge von " + MinLength + "!"
                });
            }

            if (!string.IsNullOrWhiteSpace(MaxLength) && Convert.ToInt32(MaxLength) < base.Value.Length)
            {
                ValidationResults.Add(new ValidationResult()
                {
                    Type = TypesInputValidity.Error, Text = "Der Text ist größer als die maximalen Länge von " + MaxLength + "!"
                });
            }

            base.Validate();
        }
예제 #12
0
        public static BoolResult <TEntity> ToSingle <TEntity>(this DataBase db, string strSql, Func <IDataReader, TEntity> func, params IDataParameter[] parameters)
        {
            Guard.IsNotNull(func, "Func<IDataReader, TEntity> is null");
            ValidationResults validationResults = new ValidationResults();
            TEntity           item       = default(TEntity);
            IDataReader       dataReader = null;

            try
            {
                dataReader = db.ExecuteReader(db.ConnectionString, CommandType.Text, strSql, parameters);
                if (dataReader.Read())
                {
                    item = func(dataReader);
                }
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            finally
            {
                if (dataReader != null)
                {
                    dataReader.Close();
                }
            }
            return(new BoolResult <TEntity>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #13
0
        public override ValidationResults <SourceValidationOccurance> ValidateData(ProcessedDataPackage package)
        {
            ValidationResults <SourceValidationOccurance> results = new ValidationResults <SourceValidationOccurance>();

            results.Score = -1;

            PageSourceData data = package.GetData <PageSourceData>();

            if (data == null || String.IsNullOrEmpty(data.PageSource))
            {
                return(results);
            }

            MatchCollection mc = regex.Matches(data.PageSource);

            int i = 0;

            foreach (Match m in mc)
            {
                String ma = m.ToString();
                results.Add(new SourceValidationOccurance(data, m.Index, m.Length));
                i++;
            }

            if (results.Count == 0)
            {
                results.Score = 100;
            }
            else
            {
                results.Score = 0;
            }

            return(results);
        }
예제 #14
0
 public void AddValidationResult(String message)
 {
     ValidationResults.Add(new ValidationResult
     {
         ID      = Guid.NewGuid(),
         Message = message
     });
 }
예제 #15
0
        public override ValidationResults <SourceValidationOccurance> ValidateData(ProcessedDataPackage package)
        {
            ValidationResults <SourceValidationOccurance> results = new ValidationResults <SourceValidationOccurance>();

            results.Score = -1;

            PageSourceData data = package.GetData <PageSourceData>();

            if (data == null || String.IsNullOrEmpty(data.PageSource))
            {
                return(results);
            }

            int headIndex = 0;

            results.Score = 100;

            Match headMatch = head.Match(data.PageSource);

            if (headMatch != null && headMatch.Success)
            {
                headIndex = headMatch.Index;
            }

            MatchCollection mc = linkinsidesideofhead.Matches(data.PageSource);

            int i = 0;

            foreach (Match m in mc)
            {
                if (m.Index < headIndex)
                {
                    String ma = m.ToString();
                    results.Add(new SourceValidationOccurance(data, m.Index, m.Length));
                    i++;
                }
            }

            results.ResultsExplenation = String.Format(message, results.Count);

            int c = 0;

            for (int xx = 0; xx < grades.Length; xx++)
            {
                if (grades[xx] < results.Count)
                {
                    c++;
                }
                else
                {
                    break;
                }
            }
            results.Score -= c * 10;

            return(results);
        }
 /// <summary>
 /// SQL+.NET Enforcing some custom validation in the derived class
 /// </summary>
 public override bool IsValid()
 {
     if (NumberOne + NumberTwo != NumberResult)
     {
         List <string> memberNames = new List <string> {
             nameof(NumberResult)
         };
         ValidationResults.Add(new ValidationResult($"Sorry, {NumberOne} + {NumberTwo} does not equal {NumberResult}", memberNames));
     }
     return(base.IsValid());
 }
예제 #17
0
 private void CheckSurnameTriplet()
 {
     if (_fiscalCodeToValidate.SurnameTriplet == _generator.FiscalCodes[0].SurnameTriplet)
     {
         ValidationResults.Add(_localizationProvider.GetLocalizedMessage("msg_surname_triplet_ok"));
     }
     else
     {
         ValidationResults.Add(_localizationProvider.GetFormattedLocalizedMessage("msg_surname_triplet_wrong",
                                                                                  new[] { _generator.FiscalCodes[0].SurnameTriplet, _fiscalCodeToValidate.SurnameTriplet }));
     }
 }
예제 #18
0
        private bool ValidarData(object model)
        {
            ValidationResult valor = null;
            PreAvisoDTO      obj   = new PreAvisoDTO();

            obj = (PreAvisoDTO)model;
            string[] strObjeto;


            if (obj.Data_evento > DateTime.Now)
            {
                strObjeto    = new string[1];
                strObjeto[0] = "Data_evento";
                valor        = new ValidationResult(string.Format("A Data do Evento: {0} precisa ser menor que a data atual!", obj.Data_evento), strObjeto);
                ValidationResults.Add(valor);
            }


            if ((obj.Data_comunicacao_sinistro > DateTime.Now) && (obj.Data_comunicacao_sinistro > obj.Data_evento))
            {
                strObjeto    = new string[1];
                strObjeto[0] = "Data_comunicacao_sinistro";
                valor        = new ValidationResult(string.Format("A data de comunicação do sinistro é maior que a data atual e menor que a data do evento."), strObjeto);
                ValidationResults.Add(valor);
            }


            if (obj.Lista_de_Causa_Mortis.Length > 0)
            {
                CausaSinistroBlo objCausaSinistro = new CausaSinistroBlo();
                foreach (Object item in obj.Lista_de_Causa_Mortis)
                {
                    if (objCausaSinistro.RecuperarCausaSinistro(Convert.ToInt32(item)) == null)
                    {
                        strObjeto    = new string[1];
                        strObjeto[0] = "Lista_de_Causa_Mortis";
                        valor        = new ValidationResult(string.Format("A causa Mortis:{0} não existe na Base de dados", item), strObjeto);
                        ValidationResults.Add(valor);
                    }
                }
            }

            if (ValidationResults.Count <= 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
 private void CheckWhereClause()
 {
     try
     {
         var result = _expressions.BuildExpressionTree(SelectedQuery.WhereClause);
         QueryExpressionHelper.ReadFromSqlExpr(result);
     }
     catch (Exception exc)
     {
         ValidationResults.Add(new RuleValidationResult {
             Type = ValidationResultTypes.Error, Message = $"Where Clause error: {exc.Message}"
         });
         //Errors += "\r\n" + exc.Message;
     }
 }
예제 #20
0
        public static BoolResult <int> NonQuery(this DataBase db, string strSql, params IDataParameter[] parameters)
        {
            ValidationResults validationResults = new ValidationResults();
            int item = -1;

            try
            {
                item = db.ExecuteNonQuery(db.ConnectionString, CommandType.Text, strSql, parameters);
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            return(new BoolResult <int>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #21
0
        public static BoolResult <DataTable> ToDataTable(this DataBase db, string strSql, params IDataParameter[] parameters)
        {
            ValidationResults validationResults = new ValidationResults();
            DataTable         item = null;

            try
            {
                item = db.ExecuteDataset(db.ConnectionString, CommandType.Text, strSql, parameters).Tables[0];
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            return(new BoolResult <DataTable>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #22
0
        public static BoolResult <DataSet> SPToDataSet(this DataBase db, string spName, params IDataParameter[] parameters)
        {
            ValidationResults validationResults = new ValidationResults();
            DataSet           item = null;

            try
            {
                item = db.ExecuteDataset(db.ConnectionString, spName, parameters);
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            return(new BoolResult <DataSet>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #23
0
        public override ValidationResults <String> ValidateData(ProcessedDataPackage package)
        {
            ValidationResults <String> results = new ValidationResults <String>();

            results.Score = -1;

            DownloadData data = package.GetData <DownloadData>();

            if (data == null || data.Count == 0)
            {
                return(results);
            }

            results.Score = 100;

            foreach (DownloadState ds in data)
            {
                try{
                    Uri u = new Uri(ds.URL);
                    if (results.Contains(u.Host.Trim().ToLower()) == false)
                    {
                        results.Add(u.Host);
                    }
                }
                catch
                {
                }
            }

            results.ResultsExplenation = message;

            int c = 0;

            for (int xx = 0; xx < grades.Length; xx++)
            {
                if (grades[xx] < results.Count)
                {
                    c++;
                }
                else
                {
                    break;
                }
            }
            results.Score -= c * 10;

            return(results);
        }
        /// <inheritdoc/>
        public Task ValidateEntityAsync(
            SubmitContext context,
            ChangeSetEntry entry,
            ValidationResults validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationEntry dataModificationEntry = entry as DataModificationEntry;

            if (dataModificationEntry != null)
            {
                object entity = dataModificationEntry.Entity;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(entity.GetType())
                    .GetTypeDescriptor(entity).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(entity);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable <DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType <DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(entity);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ValidationResult()
                            {
                                Id           = validationAttribute.GetType().FullName,
                                Message      = validationResult.ErrorMessage,
                                Severity     = ValidationSeverity.Error,
                                Target       = entity,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return(Task.WhenAll());
        }
예제 #25
0
        private void CheckMonthRepresentation()
        {
            FiscalCodeValidationResult result = null;

            if (_fiscalCodeToValidate.MonthRepresentation == _generator.MainFiscalCode.MonthRepresentation)
            {
                result = _localizationProvider.GetLocalizedMessage("msg_month_ok");
            }
            else
            {
                result = _localizationProvider.GetFormattedLocalizedMessage("msg_month_wrong",
                                                                            new[] { _generator.MainFiscalCode.MonthRepresentation, _fiscalCodeToValidate.MonthRepresentation });
            }

            ValidationResults.Add(result);
        }
예제 #26
0
        public static BoolResult <TType> Scalar <TType>(this DataBase db, string strSql, params IDataParameter[] parameters)
        {
            ValidationResults validationResults = new ValidationResults();
            TType             item = default(TType);

            try
            {
                object input = db.ExecuteScalar(db.ConnectionString, CommandType.Text, strSql, parameters);
                item = TypeParsers.ConvertTo <TType>(input);
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            return(new BoolResult <TType>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #27
0
        public static BoolResult <bool> SPScalar(this DataBase db, string spName, params IDataParameter[] parameters)
        {
            ValidationResults validationResults = new ValidationResults();
            bool item = false;

            try
            {
                object obj = db.ExecuteScalar(db.ConnectionString, spName, parameters);
                item = (obj != null && obj != DBNull.Value && int.Parse(obj.ToString()) > 0);
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            return(new BoolResult <bool>(item, validationResults.IsValid, string.Empty, validationResults));
        }
예제 #28
0
        private void CheckNameTriplet()
        {
            FiscalCodeValidationResult result = null;

            if (_fiscalCodeToValidate.NameTriplet == _generator.FiscalCodes[0].NameTriplet)
            {
                result = _localizationProvider.GetLocalizedMessage("msg_name_triplet_ok");
            }
            else
            {
                result = _localizationProvider.GetFormattedLocalizedMessage("msg_name_triplet_wrong",
                                                                            new[] { _generator.FiscalCodes[0].NameTriplet, _fiscalCodeToValidate.NameTriplet });
            }

            ValidationResults.Add(result);
        }
        /// <inheritdoc/>
        public Task ValidateEntityAsync(
            SubmitContext context,
            ChangeSetEntry entry,
            ValidationResults validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationEntry dataModificationEntry = entry as DataModificationEntry;
            if (dataModificationEntry != null)
            {
                object entity = dataModificationEntry.Entity;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(entity.GetType())
                    .GetTypeDescriptor(entity).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(entity);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable<DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType<DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(entity);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ValidationResult()
                            {
                                Id = validationAttribute.GetType().FullName,
                                Message = validationResult.ErrorMessage,
                                Severity = ValidationSeverity.Error,
                                Target = entity,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return Task.WhenAll();
        }
        /// <inheritdoc/>
        public Task ValidateEntityAsync(
            SubmitContext context,
            ChangeSetEntry entry,
            ValidationResults validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationEntry dataModificationEntry = entry as DataModificationEntry;
            if (dataModificationEntry != null)
            {
                object entity = dataModificationEntry.Entity;

                // TODO (.NETCORE): Use PropertyDescriptorCollection in .NET Core (when available?)
                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                IEnumerable<PropertyInfo> properties = entity.GetType().GetTypeInfo().DeclaredProperties;

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(entity);

                foreach (var property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable<DataAnnotations.ValidationAttribute> validationAttributes =
                        property.GetCustomAttributes().OfType<DataAnnotations.ValidationAttribute>();

                    foreach (var validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(entity);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ValidationResult()
                            {
                                Id = validationAttribute.GetType().FullName,
                                Message = validationResult.ErrorMessage,
                                Severity = ValidationSeverity.Error,
                                Target = entity,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return Task.WhenAll();
        }
예제 #31
0
        /// <summary>
        /// Calls IsValid with the specified context (to avoid deadlocks)
        /// Try to call this instead of IsValid when possible.
        /// Note that this same validation will be done by the service layer when SaveChanges() is called
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>
        ///   <c>true</c> if [is valid group member] [the specified rock context]; otherwise, <c>false</c>.
        /// </returns>
        public bool IsValidGroupMember(RockContext rockContext)
        {
            var result = base.IsValid;

            if (result)
            {
                string errorMessage;

                if (!ValidateGroupMembership(rockContext, out errorMessage))
                {
                    ValidationResults.Add(new ValidationResult(errorMessage));
                    result = false;
                }
            }

            return(result);
        }
예제 #32
0
        public override ValidationResults <SourceValidationOccurance> ValidateData(ProcessedDataPackage package)
        {
            ValidationResults <SourceValidationOccurance> results = new ValidationResults <SourceValidationOccurance>();

            results.Score = -1;

            PageSourceData data = package.GetData <PageSourceData>();

            if (data == null || String.IsNullOrEmpty(data.PageSource))
            {
                return(results);
            }

            String buffer = data.PageSource;

            var res = Regex.Match(buffer, "(?<=__VIEWSTATE\" value=\")(?<val>.*?)(?=\")").Groups["val"];

            if (res.Success == false)
            {
                results.Score = 100;
                return(results);
            }

            SourceValidationOccurance occurrence = new SourceValidationOccurance(data, res.Index, res.Length);

            results.Add(occurrence);

            if (res.Length > errorThreshold)
            {
                results.Score = 45;
            }
            else if (res.Length > warningThreshold)
            {
                results.Score = 65;
            }
            else if (res.Length > barelyPassedThreshold)
            {
                results.Score = 85;
            }
            else
            {
                results.Score = 100;
            }

            return(results);
        }