Exemple #1
0
 private object GetPropertyText()
 {
     if (GetSForm()?.CurrentControl != null && PropertyControl != null)
     {
         return(PropertyControl?.GetValue(GetSForm()?.CurrentControl));
     }
     if (GetSForm() == null)
     {
         RemoveErrorProvider();
         return(null);
     }
     RemoveErrorProvider();
     return(new SReflection().ConvertProperty(PropertyControl));
 }
Exemple #2
0
        private Dictionary <string, bool> IsValid()
        {
            if (!(FindForm() is FBase))
            {
                return(new Dictionary <string, bool>());
            }
            if (!(GetSForm().StateForm == StateForm.Inserting || GetSForm().StateForm == StateForm.Editing))
            {
                return(new Dictionary <string, bool>());
            }
            try
            {
                if (Name == string.Empty)
                {
                    return(new Dictionary <string, bool>());
                }
                Validations = new Dictionary <string, bool>();

                if (GetSForm() == null)
                {
                    RemoveErrorProvider();
                    return(new Dictionary <string, bool>());
                }
                if (PropertyControl == null)
                {
                    return(new Dictionary <string, bool>());
                }
                var validationAttributes = GetAttribute();
                var reflection           = new SReflection();
                foreach (var attribute in validationAttributes)
                {
                    try
                    {
                        var validationAttribute = attribute as ValidationAttribute;
                        if (validationAttribute == null)
                        {
                            continue;
                        }
                        bool isValid;

                        var operatorValue = GetAttribute <OperationValue>(PropertyControl);
                        if (operatorValue != null)
                        {
                            decimal result     = 0;
                            var     component1 =
                                GetSForm()
                                .GetListControls()
                                .FirstOrDefault(c => c.Name == operatorValue.PropertyOperationName);
                            var componentTotal =
                                GetSForm()
                                .GetListControls()
                                .FirstOrDefault(c => c.Name == operatorValue.PropertyResultName);
                            if (component1 != null)
                            {
                                if (componentTotal != null)
                                {
                                    switch (operatorValue.TypeOperation)
                                    {
                                    case TypeOperation.Division:
                                        if ((decimal)ValueControl != 0)
                                        {
                                            result = (decimal)component1.ValueControl / (decimal)ValueControl;
                                        }
                                        break;

                                    case TypeOperation.Multiplication:
                                        result = (decimal)ValueControl * (decimal)component1.ValueControl;
                                        break;

                                    case TypeOperation.Sum:
                                        result = (decimal)ValueControl + (decimal)component1.ValueControl;
                                        break;

                                    case TypeOperation.Subtraction:
                                        result = (decimal)component1.ValueControl - (decimal)ValueControl;
                                        break;

                                    case TypeOperation.SubtractionInversion:
                                        result = (decimal)ValueControl - (decimal)component1.ValueControl;
                                        break;

                                    case TypeOperation.SubtractionPorcent:
                                        result = (decimal)component1.ValueControl - (((decimal)component1.ValueControl / 100) * (decimal)ValueControl);
                                        break;

                                    case TypeOperation.AditionalPorcent:
                                        result = (decimal)component1.ValueControl + (((decimal)component1.ValueControl / 100) * (decimal)ValueControl);
                                        break;

                                    case TypeOperation.PorcentValue:
                                        result = (((decimal)component1.ValueControl / 100) * (decimal)ValueControl);
                                        break;

                                    default:
                                        result = 0;
                                        break;
                                    }
                                }
                            }
                            componentTotal.Disable      = false;
                            componentTotal.ValueControl = result;
                        }

                        if (validationAttribute is LockedTrueValue)
                        {
                            var lockedTrueValue = validationAttribute as LockedTrueValue;
                            var valid           = false;
                            if (lockedTrueValue.UniqueValue)
                            {
                                valid = lockedTrueValue.Value[0].ToString() != ValueControl.ToString();
                            }
                            for (var i = 0; i < lockedTrueValue.PropertyName.Count(); i++)
                            {
                                if (!lockedTrueValue.UniqueValue)
                                {
                                    valid = lockedTrueValue.Value[i]?.ToString() != PropertyControl?.GetValue(GetSForm()?.CurrentControl)?.ToString();
                                }

                                var component = GetSForm().GetListControls().FirstOrDefault(c => c.Name == lockedTrueValue.PropertyName[i]);
                                component.Disable = valid;
                                if (!valid)
                                {
                                    component.Clear();
                                }
                            }
                        }

                        if (validationAttribute is CompareAttribute)
                        {
                            var otherName     = validationAttribute.GetType().GetProperty("OtherProperty").GetValue(validationAttribute).ToString();
                            var otherProperty = CurrentControl.GetType().GetProperty(otherName);
                            var otherValue    = otherProperty.GetValue(CurrentControl);
                            isValid = otherValue?.ToString() == ValueControl.ToString();
                        }
                        else
                        {
                            if (this is SComboBox)
                            {
                                isValid = !ValueControl.ToString().Equals("0");
                            }
                            else
                            {
                                isValid = validationAttribute.IsValid(ValueControl);
                            }
                        }
                        var key = validationAttribute.FormatErrorMessage(DisplayName(PropertyControl));
                        if (!isValid && !Validations.ContainsKey(key))
                        {
                            Validations.Add(key, false);
                        }

                        var compoundIndex = GetSForm().GetAttribute <CompoundIndex>();
                        var unique        = attribute as Unique;

                        if ((compoundIndex != null && compoundIndex.Properties.Contains(Name)) || unique != null)
                        {
                            var typeValue = ValueControl as string;
                            if (!(typeValue != null && ReferenceEquals(ValueControl, string.Empty)))
                            {
                                // Pego o tipo do contexto.
                                var typeDataSource = GetSForm().InvokeMethod.TypeModel;

                                // Para garantia de Lista anonima (generica), pesquisa pela propriedade Id,
                                // chave primária do objeto.
                                var property = PropertyControl;

                                // Pego o valor da propriedade do objeto atual.
                                var value = ValueControl;

                                // se o tipo do objeto já foi informado para mesmo contexto, não é passado mais.
                                var parameterType = Expression.Parameter(typeDataSource);

                                // passa o tipo da propriedade
                                var prop = Expression.Property(parameterType, property);
                                // converte o tipo do dado, para garantir a identidade do mesmo.
                                var convertedValue = reflection.ChangeType(value, property.PropertyType);
                                // cria expressao do valor que será passada na expressão.
                                var soap = Expression.Constant(convertedValue);
                                // relaciona a propriedade com o dado. Exemplo: param0 => param0 == 1
                                var equal = Expression.Equal(prop, soap);

                                Expression expressionCompound = null;
                                // Se acaso for index composto adiciona mais uma expressão
                                if (compoundIndex != null && compoundIndex.Properties.Contains(Name))
                                {
                                    // Pesquiso  as outras propriedades que fazem parte da composição.
                                    var properties = compoundIndex.Properties.Where(c => c != Name);

                                    expressionCompound = (from index in properties select typeDataSource.GetProperty(index) into propertyCompoundId let propCompoundId = Expression.Property(parameterType, propertyCompoundId) let convertedValueCompoundId = reflection.ChangeType(propertyCompoundId.GetValue(GetSForm().CurrentControl), propertyCompoundId.PropertyType) let soapCompoundId = Expression.Constant(convertedValueCompoundId) select Expression.Equal(propCompoundId, soapCompoundId)).Aggregate(expressionCompound, (current, equalCompoundId) => current == null ? equalCompoundId : Expression.And(equalCompoundId, current));
                                }

                                if (expressionCompound != null)
                                {
                                    equal = Expression.And(equal, expressionCompound);
                                }

                                var propertyId = typeDataSource.GetProperty("Id");
                                // passa o tipo da propriedade
                                var propId = Expression.Property(parameterType, propertyId);
                                // converte o tipo do dado, para garantir a identidade do mesmo.
                                var convertedValueId = Convert.ChangeType(propertyId.GetValue(GetSForm().CurrentControl), propertyId.PropertyType);
                                // cria expressao do valor que será passada na expressão.
                                var soapId = Expression.Constant(convertedValueId);
                                // relaciona a propriedade com o dado. Exemplo: param0 => param0 == 1
                                var equalId = Expression.NotEqual(propId, soapId);

                                var yourExpression = Expression.And(equal, equalId);

                                var delegateType = typeof(Func <,>).MakeGenericType(typeDataSource, typeof(bool));
                                var expression   = Expression.Lambda(delegateType, yourExpression, true, parameterType);
                                var objetoApp    = GetSForm().InvokeMethod;
                                var method       = objetoApp.Methods.FirstOrDefault(c => c.Key == TypeExecute.Search).Value;
                                if (string.IsNullOrEmpty(method))
                                {
                                    MessageBox.Show("Método Search não configurado\nController: " + objetoApp.TypeController.Name,
                                                    "ESR Softwares", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                }
                                var result = reflection.GetListContext(objetoApp.TypeController, method, expression);

                                var components = GetSForm().GetListControls().Where(c =>
                                {
                                    if (compoundIndex == null)
                                    {
                                        return(false);
                                    }
                                    foreach (var s in compoundIndex.Properties)
                                    {
                                        if (Equals(s, c.Name))
                                        {
                                            break;
                                        }
                                    }
                                    return(false);
                                });

                                if (result.Any())
                                {
                                    if (compoundIndex != null && compoundIndex.Properties.Contains(Name))
                                    {
                                        var enumerable      = components as IList <IComponent> ?? components.ToList();
                                        var componentValues = enumerable.Aggregate("", (current, component) => current + component.Caption + " = " + component.ValueControl + " ");
                                        foreach (var component in enumerable)
                                        {
                                            component.SetError("Já existem dados com " + componentValues);
                                            component.ComponentBackColor = Color.FromArgb(255, 255, 173, 178);
                                        }
                                        Validations.Add("Já existem dados com " + (componentValues == "" ? " este registro" : componentValues), false);
                                    }
                                    else
                                    {
                                        Validations.Add("Este " + GetTextLabel() + " já existe, considere em informar outro", false);
                                    }
                                }
                                else
                                {
                                    foreach (var component in components)
                                    {
                                        if (!component.Validations.Values.Contains(false))
                                        {
                                            component.RemoveErrorProvider();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    SComponent.BackColor = Validations.Values.Contains(false) ? Color.FromArgb(255, 255, 173, 178) : Color.White;
                }
                return(Validations);
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }