public void SetBuildValidationContextSomethingElseTest()
        {
            var expected = new System.ComponentModel.DataAnnotations.ValidationContext(new object());
            var target = new object();

            Factories.BuildValidationContext = (obj) =>
            {
                Assert.AreEqual(target, obj);
                return expected;
            };
            var actual = Factories.BuildValidationContext(target);
            Assert.AreEqual(expected, actual);
        }
        internal void ValidateInterfaceLayer(ValidationContext dslContext)
        {
            var layer = ToolkitInterfaceLayer.GetInterfaceLayer(this);
            if (layer != null)
            {
                var dataContext = new System.ComponentModel.DataAnnotations.ValidationContext(layer, this.Store, null);
                var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>();

                System.ComponentModel.DataAnnotations.Validator.TryValidateObject(layer, dataContext, results, true);

                if (results.Any())
                {
                    var properties = TypeDescriptor.GetProperties(layer);
                    var typeName = this.Info != null ?
                        // If we have an info, first check that it differs from the instance name
                        // to avoid duplicating the same string
                        this.InstanceName != this.Info.DisplayName ?
                            this.InstanceName + @" (" + this.Info.DisplayName + @")" :
                        // If they are equal, just use the instance name.
                            this.InstanceName
                        : this.InstanceName;

                    foreach (var result in results)
                    {
                        // Replace member names with display names in message and member names collection.
                        var members = result.MemberNames
                            .Select(name => new
                            {
                                Name = name,
                                DisplayName = properties[name].DisplayName,
                                FormattedName = typeName + @" '" + properties[name].DisplayName + @"'",
                            });

                        var message = result.ErrorMessage;

                        foreach (var member in members)
                        {
                            if (message.IndexOf(member.Name) != -1)
                                message = message.Replace(member.Name, member.FormattedName);
                            else if (message.IndexOf(member.DisplayName) != -1)
                                message = message.Replace(member.DisplayName, member.FormattedName);
                        }

                        dslContext.LogError(message,
                            Resources.ProductElement_ValidationFailedErrorCode, this);
                    }
                }
            }
        }
Example #3
0
 public static bool TryValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection <System.ComponentModel.DataAnnotations.ValidationResult> validationResults, System.Collections.Generic.IEnumerable <System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes)
 {
     throw null;
 }
Example #4
0
 public static bool TryValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection <System.ComponentModel.DataAnnotations.ValidationResult> validationResults)
 {
     throw null;
 }
        public void ValidateVM()
        {
            var dbContext       = DbContext(GetCurrentMethod());
            var serviceProvider = GetServiceProviderMock(dbContext).Object;

            var data = new DyestuffChemicalUsageReceiptViewModel()
            {
                UsageReceiptItems = new List <DyestuffChemicalUsageReceiptItemViewModel>()
                {
                    new DyestuffChemicalUsageReceiptItemViewModel()
                    {
                        ColorCode           = "code",
                        Adjs1Date           = DateTimeOffset.UtcNow,
                        Adjs2Date           = DateTimeOffset.UtcNow,
                        Adjs3Date           = DateTimeOffset.UtcNow,
                        Adjs4Date           = DateTimeOffset.UtcNow,
                        Adjs5Date           = DateTimeOffset.UtcNow,
                        UsageReceiptDetails = new List <DyestuffChemicalUsageReceiptItemDetailViewModel>()
                        {
                            new DyestuffChemicalUsageReceiptItemDetailViewModel()
                            {
                                Name            = "name",
                                Adjs1Quantity   = 1,
                                Adjs2Quantity   = 1,
                                Adjs3Quantity   = 1,
                                Adjs4Quantity   = 1,
                                Adjs5Quantity   = 1,
                                ReceiptQuantity = 1,
                            }
                        }
                    }
                }
            };


            DyestuffChemicalUsageReceiptFacade facade = new DyestuffChemicalUsageReceiptFacade(serviceProvider, dbContext);

            System.ComponentModel.DataAnnotations.ValidationContext validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(data, serviceProvider, null);
            var response = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.Date = default(DateTimeOffset);
            response  = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.ProductionOrder = new Production.Lib.ViewModels.Integration.Sales.FinishingPrinting.ProductionOrderIntegrationViewModel()
            {
                Id = 1
            };

            response = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.StrikeOff = new Lib.ViewModels.StrikeOff.StrikeOffViewModel()
            {
                Id = 1
            };
            response = data.Validate(validationContext);

            Assert.Empty(response);
        }
Example #6
0
        /// <summary>
        /// Initializes a model by subscribing to all events.
        /// </summary>
        /// <param name="modelProperty">The name of the model property.</param>
        /// <param name="model">The model.</param>
        private void InitializeModelInternal(string modelProperty, object model)
        {
            if (model != null)
            {
                ViewModelManager.RegisterModel(this, model);
            }

            _modelsDirtyFlags[modelProperty] = false;
            _modelErrorInfo[modelProperty] = new ModelErrorInfo(model);
            _modelErrorInfo[modelProperty].Updated += OnModelErrorInfoUpdated;

            var modelAsINotifyPropertyChanged = model as INotifyPropertyChanged;
            if (modelAsINotifyPropertyChanged != null)
            {
                modelAsINotifyPropertyChanged.PropertyChanged += OnModelPropertyChangedInternal;
            }

            if (SupportIEditableObject)
            {
                if (_modelObjectsInfo[modelProperty].SupportIEditableObject)
                {
                    if (model != null)
                    {
                        EditableObjectHelper.BeginEditObject(model);
                    }
                }
            }

#if (NET || SL5) && !NET35
            if (ValidateModelsOnInitialization)
            {
                var validationResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
                var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);

                System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, validationContext, validationResults, true);
                _modelErrorInfo[modelProperty].InitializeDefaultErrors(validationResults);
            }
#endif
            InitializeModel(modelProperty, model);
        }
 protected override System.ComponentModel.DataAnnotations.ValidationResult? IsValid(object?value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     throw null;
 }
 public System.ComponentModel.DataAnnotations.ValidationResult? GetValidationResult(object?value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     throw null;
 }
Example #9
0
 public static void ValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
 }
        /// <summary>
        /// Validates the property using data annotations.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The value to validate.</param>
        /// <returns>
        /// <c>true</c> if no errors using data annotations are found; otherwise <c>false</c>.
        /// </returns>
        private bool ValidatePropertyUsingAnnotations(string propertyName, object value)
        {
            if (SuspendValidation)
            {
                _propertiesNotCheckedDuringDisabledValidation.Add(propertyName);
                return(true);
            }

#if !WINDOWS_PHONE && !NETFX_CORE && !PCL && !NET35
            var type = GetType();

            try
            {
                if (!_propertyValuesIgnoredOrFailedForValidation[type].Contains(propertyName))
                {
                    if (!_propertyValuesAtLeastOnceValidated[type].Contains(propertyName))
                    {
#if NET
                        if (type.GetPropertyEx(propertyName) == null)
                        {
                            Log.Debug("Property '{0}' cannot be found via reflection, ignoring this property for type '{1}'", propertyName, type.FullName);

                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return(false);
                        }
#else
                        // Checking via reflection is faster than catching the exception
                        if (!Reflection.PropertyHelper.IsPublicProperty(this, propertyName))
                        {
                            Log.Debug("Property '{0}' is not a public property, cannot validate non-public properties in silverlight", propertyName);

                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return(false);
                        }
#endif
                    }
                    else
                    {
                        _propertyValuesAtLeastOnceValidated[type].Add(propertyName);
                    }

                    if (!_dataAnnotationsValidationContext.ContainsKey(propertyName))
                    {
                        _dataAnnotationsValidationContext[propertyName] = new System.ComponentModel.DataAnnotations.ValidationContext(this, null, null)
                        {
                            MemberName = propertyName
                        };
                    }

                    System.ComponentModel.DataAnnotations.Validator.ValidateProperty(value, _dataAnnotationsValidationContext[propertyName]);

                    // If succeeded, clear any previous error
                    if (_dataAnnotationValidationResults.ContainsKey(propertyName))
                    {
                        _dataAnnotationValidationResults[propertyName] = null;
                    }
                }
            }
            catch (System.ComponentModel.DataAnnotations.ValidationException validationException)
            {
                _dataAnnotationValidationResults[propertyName] = validationException.Message;
                return(false);
            }
            catch (Exception ex)
            {
                _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);

                Log.Warning(ex, "Failed to validate property '{0}' via Validator (property does not exists?)", propertyName);
            }
#endif

            return(true);
        }
        public async Task Should_Success_Validate_Data()
        {
            GarmentUnitDeliveryOrderViewModel viewModelNullItems = new GarmentUnitDeliveryOrderViewModel
            {
                DONo = "DONo"
            };

            Assert.True(viewModelNullItems.Validate(null).Count() > 0);

            GarmentUnitDeliveryOrderViewModel viewModelWithItems = new GarmentUnitDeliveryOrderViewModel
            {
                DONo  = "DONo",
                Items = new List <GarmentUnitDeliveryOrderItemViewModel>
                {
                    new GarmentUnitDeliveryOrderItemViewModel
                    {
                        IsSave   = true,
                        Quantity = 0
                    }
                }
            };

            Assert.True(viewModelWithItems.Validate(null).Count() > 0);

            var garmentUnitReceiptNoteFacade = new GarmentUnitReceiptNoteFacade(GetServiceProvider().Object, _dbContext(GetCurrentMethod()));
            var data = await garmentUnitReceiptNoteDataUtil(garmentUnitReceiptNoteFacade, GetCurrentMethod()).GetTestData();

            var item = data.Items.First();

            var serviceProvider = GetServiceProvider();

            serviceProvider.Setup(x => x.GetService(typeof(PurchasingDbContext)))
            .Returns(_dbContext(GetCurrentMethod()));

            GarmentUnitDeliveryOrderViewModel viewModelWithItemsQuantityOver = new GarmentUnitDeliveryOrderViewModel
            {
                DONo  = "DONo",
                Items = new List <GarmentUnitDeliveryOrderItemViewModel>
                {
                    new GarmentUnitDeliveryOrderItemViewModel
                    {
                        URNItemId = item.Id,
                        IsSave    = true,
                        Quantity  = (double)(item.SmallQuantity - item.OrderQuantity + 1)
                    }
                }
            };

            System.ComponentModel.DataAnnotations.ValidationContext validationDuplicateContext = new System.ComponentModel.DataAnnotations.ValidationContext(viewModelWithItemsQuantityOver, serviceProvider.Object, null);
            Assert.True(viewModelWithItemsQuantityOver.Validate(validationDuplicateContext).Count() > 0);

            GarmentUnitDeliveryOrderViewModel viewModelWithItems2 = new GarmentUnitDeliveryOrderViewModel
            {
                DONo       = "DONo",
                UnitDOType = "RETUR",
                Items      = new List <GarmentUnitDeliveryOrderItemViewModel>
                {
                    new GarmentUnitDeliveryOrderItemViewModel
                    {
                        IsSave        = true,
                        Quantity      = 10,
                        ReturQtyCheck = 1
                    }
                }
            };

            Assert.True(viewModelWithItems2.Validate(null).Count() > 0);
        }
Example #12
0
        public async void Validate_ViewModel()
        {
            var dbContext = DbContext(GetCurrentMethod());
            var vm        = new ShinProductionOrderViewModel()
            {
                Code = "a",
                ArticleFabricEdge = "a",
                DeliveryDate      = DateTimeOffset.UtcNow,
                Remark            = "a",
                ApprovalMD        = new ApprovalViewModel()
                {
                    ApprovedBy   = "a",
                    ApprovedDate = DateTimeOffset.UtcNow,
                    IsApproved   = true
                },
                IsCalculated   = true,
                IsClosed       = true,
                IsCompleted    = true,
                IsRequested    = true,
                IsUsed         = true,
                AutoIncreament = 0,
                LampStandards  = new List <ProductionOrder_LampStandardViewModel>(),
                Details        = new List <ProductionOrder_DetailViewModel>()
            };
            var sp = GetServiceProviderMock(DbContext(GetCurrentMethod()));

            var facade = new ShinProductionOrderFacade(sp.Object, dbContext);

            sp.Setup(s => s.GetService(typeof(IShinProductionOrder)))
            .Returns(facade);

            var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(vm, sp.Object, null);
            var response          = vm.Validate(validationContext);

            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.FinishingPrintingSalesContract = new ShinFinishingPrintingSalesContractViewModel()
            {
                Id = 1,
                PreSalesContract = new FinishingPrintingPreSalesContractViewModel()
                {
                    Unit = new UnitViewModel()
                    {
                        Name = "printing"
                    }
                }
            };
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.Run   = "1 run";
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.RunWidth = new List <ProductionOrder_RunWidthViewModel>()
            {
                new ProductionOrder_RunWidthViewModel()
                {
                    Value = -1
                }
            };

            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.RunWidth = new List <ProductionOrder_RunWidthViewModel>()
            {
                new ProductionOrder_RunWidthViewModel()
                {
                    Value = 1
                }
            };
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.StandardTests = new StandardTestsViewModel()
            {
                Id = 1
            };
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.Account = new AccountViewModel();
            response   = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.MaterialOrigin = "a";
            response          = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.HandlingStandard = "e";
            response            = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.ShrinkageStandard = "e";
            response             = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            //  var data = await DataUtil(facade, dbContext).GetTestData();
            vm.OrderQuantity = 1;
            //vm.FinishingPrintingSalesContract.Id = data.SalesContractId;
            vm.FinishingPrintingSalesContract.Id = 1;
            vm.Details = new List <ProductionOrder_DetailViewModel>()
            {
                new ProductionOrder_DetailViewModel()
                {
                    Quantity = 5,
                }
            };
            vm.LampStandards = new List <ProductionOrder_LampStandardViewModel>();
            response         = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.LampStandards.Add(new ProductionOrder_LampStandardViewModel()
            {
            });

            vm.Details = new List <ProductionOrder_DetailViewModel>()
            {
                new ProductionOrder_DetailViewModel()
                {
                    Quantity = -1,
                }
            };
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.LampStandards.FirstOrDefault().Name = "a";
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.Details = new List <ProductionOrder_DetailViewModel>();
            response   = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());

            vm.Details = new List <ProductionOrder_DetailViewModel>()
            {
                new ProductionOrder_DetailViewModel()
            };
            response = vm.Validate(validationContext);
            Assert.NotEmpty(response);
            Assert.True(0 < response.Count());
        }
Example #13
0
 public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection <System.ComponentModel.DataAnnotations.ValidationResult> validationResults, bool validateAllProperties)
 {
     return(default(bool));
 }
Example #14
0
 protected virtual System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     return(default(System.ComponentModel.DataAnnotations.ValidationResult));
 }
Example #15
0
 public System.ComponentModel.DataAnnotations.ValidationResult GetValidationResult(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     return(default(System.ComponentModel.DataAnnotations.ValidationResult));
 }
Example #16
0
 public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
 }
Example #17
0
 public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, bool validateAllProperties)
 {
 }
Example #18
0
        /// <summary>
        ///   Validates given object using information contained in the
        ///   <see cref="ValidateAttribute"/> custom attribute.
        /// </summary>
        /// <param name="obj">The object to be validated.</param>
        /// <param name="validationErrors">All validation errors found.</param>
        /// <returns>True if object is valid, false otherwise.</returns>
        public static bool Validate(object obj, out IList<ValidationError> validationErrors)
        {
            // The list of errors which will be populated during the validation process.
            validationErrors = new List<ValidationError>();

#if !(NET35 || PORTABLE || NETSTD11 || NETSTD13)

            // Applies standard .NET validation.
            var netValidationErrors = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
            var netValidationContext = new System.ComponentModel.DataAnnotations.ValidationContext(obj, null, null);
            if (!System.ComponentModel.DataAnnotations.Validator.TryValidateObject(obj, netValidationContext, netValidationErrors, true))
            {
                foreach (var netValidationError in netValidationErrors)
                foreach (var memberName in netValidationError.MemberNames)
                {
                    validationErrors.Add(new ValidationError
                    {
                        Path = $"{RootPlaceholder}.{memberName}",
                        Reason = netValidationError.ErrorMessage
                    });
                }
            }

#endif

            // Apply the final Thrower validation.
            return ValidateInternal(obj, RootPlaceholder, DefaultValidation, validationErrors);
        }
Example #19
0
 public static void ValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.IEnumerable <System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes)
 {
 }
        public async Task ValidateVM()
        {
            var dbContext       = DbContext(GetCurrentMethod());
            var serviceProvider = GetServiceProviderMock(dbContext).Object;

            var data = new StrikeOffViewModel()
            {
                Remark = "test",
                Cloth  = "tes"
            };
            StrikeOffFacade facade = new StrikeOffFacade(serviceProvider, dbContext);

            System.ComponentModel.DataAnnotations.ValidationContext validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(data, serviceProvider, null);
            var response = data.Validate(validationContext);

            Assert.NotEmpty(response);

            var model = await DataUtil(facade, dbContext).GetTestData();

            data.Code = model.Code;
            response  = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.Code = "testCodeNew" + Guid.NewGuid().ToString();
            response  = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.Type = "type";
            response  = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.StrikeOffItems = new List <StrikeOffItemViewModel>()
            {
            };
            response = data.Validate(validationContext);

            Assert.NotEmpty(response);


            data.StrikeOffItems = new List <StrikeOffItemViewModel>()
            {
                new StrikeOffItemViewModel()
            };
            response = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.StrikeOffItems = new List <StrikeOffItemViewModel>()
            {
                new StrikeOffItemViewModel()
                {
                    ColorCode     = "code",
                    DyeStuffItems = new List <DyeStuffItemViewModel>()
                    {
                        new DyeStuffItemViewModel()
                        {
                            Quantity = 500
                        }
                    },
                    ChemicalItems = new List <ChemicalItemViewModel>()
                    {
                        new ChemicalItemViewModel()
                        {
                            Name     = "air",
                            Quantity = 100
                        }
                    }
                }
            };
            response = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.StrikeOffItems = new List <StrikeOffItemViewModel>()
            {
                new StrikeOffItemViewModel()
                {
                    ColorCode     = "code",
                    DyeStuffItems = new List <DyeStuffItemViewModel>()
                    {
                        new DyeStuffItemViewModel()
                        {
                            Quantity = 500
                        }
                    },
                    ChemicalItems = new List <ChemicalItemViewModel>()
                    {
                        new ChemicalItemViewModel()
                        {
                            Name     = "air",
                            Quantity = -100,
                            Index    = 0
                        }
                    }
                }
            };
            response = data.Validate(validationContext);

            Assert.NotEmpty(response);
            Assert.Equal(0, data.StrikeOffItems.FirstOrDefault().ChemicalItems.FirstOrDefault().Index);

            data.StrikeOffItems = new List <StrikeOffItemViewModel>()
            {
                new StrikeOffItemViewModel()
                {
                    ColorCode     = "code",
                    DyeStuffItems = new List <DyeStuffItemViewModel>()
                    {
                        new DyeStuffItemViewModel()
                        {
                            Quantity = 500
                        }
                    },
                    ChemicalItems = new List <ChemicalItemViewModel>()
                    {
                        new ChemicalItemViewModel()
                        {
                        }
                    }
                }
            };
            response = data.Validate(validationContext);

            Assert.NotEmpty(response);

            data.StrikeOffItems = new List <StrikeOffItemViewModel>()
            {
                new StrikeOffItemViewModel()
                {
                    ColorCode     = "code",
                    DyeStuffItems = new List <DyeStuffItemViewModel>()
                    {
                        new DyeStuffItemViewModel()
                        {
                            Product  = new Lib.ViewModels.Integration.Master.ProductIntegrationViewModel(),
                            Quantity = 1001
                        }
                    },
                    ChemicalItems = new List <ChemicalItemViewModel>()
                    {
                        new ChemicalItemViewModel()
                        {
                        }
                    }
                }
            };
            response = data.Validate(validationContext);

            Assert.NotEmpty(response);
        }
 public void Validate(object?value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
 }
 public override System.Collections.Generic.IEnumerable <System.ComponentModel.DataAnnotations.ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     throw new NotImplementedException();
 }
 public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection <System.ComponentModel.DataAnnotations.ValidationResult>?validationResults, bool validateAllProperties)
 {
     throw null;
 }
Example #24
0
 protected virtual System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     throw null;
 }
Example #25
0
        /// <summary>
        /// Validates the property using data annotations.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The value to validate.</param>
        /// <param name="catelPropertyData">The catel property data. Can be <c>null</c> for non-Catel properties.</param>
        /// <returns><c>true</c> if no errors using data annotations are found; otherwise <c>false</c>.</returns>
        private bool ValidatePropertyUsingAnnotations(string propertyName, object value, PropertyData catelPropertyData)
        {
            if (SuspendValidation)
            {
                _propertiesNotCheckedDuringDisabledValidation.Add(propertyName);
                return true;
            }

#if !WINDOWS_PHONE && !NETFX_CORE && !PCL && !NET35
            var type = GetType();

            try
            {
                if (!_propertyValuesIgnoredOrFailedForValidation[type].Contains(propertyName))
                {
                    if (catelPropertyData != null)
                    {
                        var propertyInfo = catelPropertyData.GetPropertyInfo(type);
                        if (propertyInfo == null || !propertyInfo.HasPublicGetter)
                        {
                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return false;
                        }
                    }
                    else
                    {
#if NET
                        if (type.GetPropertyEx(propertyName) == null)
                        {
                            Log.Debug("Property '{0}' cannot be found via reflection, ignoring this property for type '{1}'", propertyName, type.FullName);

                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return false;
                        }
#else
                        // Checking via reflection is faster than catching the exception
                        if (!Reflection.PropertyHelper.IsPublicProperty(this, propertyName))
                        {
                            Log.Debug("Property '{0}' is not a public property, cannot validate non-public properties in silverlight", propertyName);

                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return false;
                        }
#endif
                    }

                    if (!_dataAnnotationsValidationContext.ContainsKey(propertyName))
                    {
                        _dataAnnotationsValidationContext[propertyName] = new System.ComponentModel.DataAnnotations.ValidationContext(this, null, null) { MemberName = propertyName };
                    }

                    System.ComponentModel.DataAnnotations.Validator.ValidateProperty(value, _dataAnnotationsValidationContext[propertyName]);

                    // If succeeded, clear any previous error
                    if (_dataAnnotationValidationResults.ContainsKey(propertyName))
                    {
                        _dataAnnotationValidationResults[propertyName] = null;
                    }
                }
            }
            catch (System.ComponentModel.DataAnnotations.ValidationException validationException)
            {
                _dataAnnotationValidationResults[propertyName] = validationException.Message;
                return false;
            }
            catch (Exception ex)
            {
                _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);

                Log.Warning(ex, "Failed to validate property '{0}' via Validator (property does not exists?)", propertyName);
            }
#endif

            return true;
        }
Example #26
0
 protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
 {
     if (string.IsNullOrEmpty(this.PropertyName))
     {
         return(base.IsValid(value, validationContext));
     }
     else
     {
         PropertyInfo Property         = null;
         var          PropertyNameInfo = validationContext.ObjectInstance.GetType().GetProperty(this.PropertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
         if (PropertyNameInfo != null && PropertyNameInfo.CanRead && PropertyNameInfo.PropertyType == typeof(bool))
         {
             Property = PropertyNameInfo;
         }
         if (Property == null)
         {
             return(base.IsValid(value, validationContext));
         }
         else
         {
             var Value = (bool)Property.GetValue(validationContext.ObjectInstance, null);
             if (!this.IsValid(Value))
             {
                 return(new System.ComponentModel.DataAnnotations.ValidationResult(this.ErrorMessageString));
             }
             else
             {
                 return(null);
             }
         }
     }
 }