Example #1
0
        public List<FilterComparitor> GetComparitors(FilterProperty property)
        {
            if (property != null)
            {
                switch (property.PropertyType)
                {
                    case FilterPropertyType.Boolean:
                        return new List<FilterComparitor>() { new FilterComparitor("==") };

                    case FilterPropertyType.Enum:
                        return EnumComparitors;

                    case FilterPropertyType.Number:
                        return NumberComparitors;

                    case FilterPropertyType.DateTime:
                        return DateComparitors;

                    case FilterPropertyType.String:
                        return StringComparitors;
                }
            }

            return StringComparitors;
        }
        public void ShouldConvertEntityToCorrectJson()
        {
            Guid leftId  = Guid.NewGuid();
            Guid rightId = Guid.NewGuid();

            var left = new FilterProperty
            {
                IsConform = true,
                Value     = "This is a test left",
                ItemId    = leftId
            };
            var right = new FilterProperty
            {
                IsConform = true,
                Value     = "This is a test right",
                ItemId    = rightId
            };
            var combination = new FilterCombination
            {
                RightFilter = right,
                LeftFilter  = left,
                Type        = FormFilterType.And
            };

            string jsonTest = JsonConvert.SerializeObject(combination);

            Assert.AreEqual("{\"EntityDiscriminator\":\"FilterCombination\",\"Type\":0,\"RightFilter\":{\"EntityDiscriminator\":\"FilterProperty\",\"IsConform\":true,\"Value\":\"This is a test right\",\"NotApplicable\":false,\"ItemId\":\"" +
                            rightId + "\",\"Id\":\"" + right.Id + "\",\"EntityVersion\":0,\"Deleted\":false,\"EntityCreationDate\":\"0001-01-01T00:00:00\",\"EntityModificationDate\":\"0001-01-01T00:00:00\",\"EntityCreationUser\":\"00000000-0000-0000-0000-000000000000\"}," +
                            "\"LeftFilter\":{\"EntityDiscriminator\":\"FilterProperty\",\"IsConform\":true,\"Value\":\"This is a test left\",\"NotApplicable\":false,\"ItemId\":\"" + leftId +
                            "\",\"Id\":\"" + left.Id + "\",\"EntityVersion\":0,\"Deleted\":false,\"EntityCreationDate\":\"0001-01-01T00:00:00\",\"EntityModificationDate\":\"0001-01-01T00:00:00\",\"EntityCreationUser\":\"00000000-0000-0000-0000-000000000000\"}," +
                            "\"Id\":\"" + combination.Id + "\",\"EntityVersion\":0,\"Deleted\":false,\"EntityCreationDate\":\"0001-01-01T00:00:00\",\"EntityModificationDate\":\"0001-01-01T00:00:00\",\"EntityCreationUser\":\"00000000-0000-0000-0000-000000000000\"}", jsonTest);
        }
        private static void CheckVisibleConditionEquality(FormFilterCondition templateCondition, FormFilterCondition formCondition, FormTemplate template, Form form)
        {
            if (templateCondition == null)
            {
                Assert.IsNull(formCondition);
                return;
            }

            Assert.AreEqual(templateCondition.GetType(), formCondition.GetType());
            FilterProperty propertyFilter = templateCondition as FilterProperty;

            if (propertyFilter != null)
            {
                FilterProperty formProperty = (FilterProperty)formCondition;
                Assert.AreEqual(propertyFilter.IsConform, formProperty.IsConform);
                Assert.AreEqual(propertyFilter.Value, formProperty.Value);
                Assert.AreEqual(propertyFilter.NotApplicable, formProperty.NotApplicable);
                Guid itemId = form.Items.Find((item) => item.QuestionId == propertyFilter.ItemId).Id;
                Assert.AreEqual(itemId, formProperty.ItemId);
            }
            else
            {
                FilterCombination combination = (FilterCombination)templateCondition;
                FilterCombination formComb    = (FilterCombination)formCondition;
                Assert.AreEqual(combination.Type, formComb.Type);
                CheckVisibleConditionEquality(combination.LeftFilter, formComb.LeftFilter, template, form);
                CheckVisibleConditionEquality(combination.RightFilter, formComb.RightFilter, template, form);
            }
        }
Example #4
0
        public override string ToString()
        {
            FilterAttribute lvda = (FilterAttribute)
                                   FilterProperty.GetCustomAttributes(typeof(FilterAttribute), false).FirstOrDefault();

            if (lvda == null)
            {
                return("");
            }
            string res = lvda.Title + " ";

            if (AllValues != null && Values.Length == AllValues.Length)
            {
                res += "All";
                return(res);
            }
            for (int i = 0; i < Values.Length; i++)
            {
                if (i > 0)
                {
                    res += ",";
                }
                res += Values[i].ToString();
            }
            return(res);
        }
Example #5
0
        public FilterGroup AddFilterGroup(string caption, FilterProperty property,
                                          ExpressionType expressionType = ExpressionType.In, string description = default)
        {
            var group = new FilterGroup(caption, property, expressionType, description);

            FilterGroups.Add(group);
            return(group);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                if (reader.TokenType == JsonToken.Null)
                {
                    return(null);
                }
                JObject jo = JObject.Load(reader);

                if (typeof(Entity).IsAssignableFrom(objectType))
                {
                    Entity entity = null;
                    if (jo.ContainsKey("EntityDiscriminator"))
                    {
                        var entityDiscriminatorValue = jo["EntityDiscriminator"].Value <string>();
                        switch (entityDiscriminatorValue)
                        {
                        case "Note":
                            entity = new Note();

                            break;

                        case "Form":
                            entity = new Form();
                            break;

                        case "FilterProperty":
                            entity = new FilterProperty();

                            break;

                        case "FilterCombination":
                            entity = new FilterCombination();
                            break;

                        default:
                            throw new Exception("EntityDiscriminator " + entityDiscriminatorValue + " not managed in the serialization");
                        }
                    }
                    else
                    {
                        entity = (Entity)Activator.CreateInstance(objectType);
                    }
                    serializer.Populate(jo.CreateReader(), entity);
                    return(entity);
                }
                else
                {
                    throw new Exception("Converter used with not managed type " + objectType?.Name);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Example #7
0
        public FilterGroup AddHiddenFilterGroup(FilterProperty property, ExpressionType expressionType = ExpressionType.In)
        {
            var group = new FilterGroup(property, expressionType)
            {
                Hidden = true
            };

            FilterGroups.Add(group);
            return(group);
        }
Example #8
0
    public FilterProperty[] GetFilterProperties()
    {
        int i;

        Type filterControlType = this.ControlInterfaceType;

        PropertyInfo[] properties = filterControlType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        FilterProperty[] filterProperties = new FilterProperty[properties.Length];

        for (i = 0; i < filterProperties.Length; i++)
        {
            filterProperties[i] = new FilterProperty(properties[i], this);
        }

        return(filterProperties);
    }
        private EditPropertyViewModel CreateEditPropertyViewModel(
            MessageFilterComponent component,
            FilterProperty existingProperty,
            string name
            )
        {
            System.Diagnostics.Debug.Assert(component != null);

            var isCheckType = component.GetIsBooleanProperty(name);

            return(new EditPropertyViewModel
            {
                IsIncluded = existingProperty != null && existingProperty.IsIncluded,
                Id = existingProperty != null ? (int?)existingProperty.FilterPropertyId : null,
                Timestamp = existingProperty != null ? existingProperty.Timestamp : null,
                Name = name,
                Value = existingProperty != null ? existingProperty.Value : string.Empty,
                IsCheckType = isCheckType,
                IsChecked = isCheckType && existingProperty != null?string.Equals(existingProperty.Value, "true", StringComparison.OrdinalIgnoreCase) : false
            });
        }
Example #10
0
        private Expression <Func <T, bool> > BuildPredicate <T>(ParameterExpression predParam, Expression currentLeft, FilterProperty filterProp, object propValue, bool fuzzyMatch, int index = 0) where T : class
        {
            for (; index < filterProp.SplitPropertyName.Length; index++)
            {
                var name = filterProp.SplitPropertyName[index];
                if (typeof(IEnumerable).IsAssignableFrom(currentLeft.Type))
                {
                    var subtype  = currentLeft.Type.GetGenericArguments()[0];
                    var method   = BuildPredicateMethod.MakeGenericMethod(subtype);
                    var newParam = Expression.Parameter(subtype);
                    var predExpr = (Expression)method.Invoke(this, new object[] { newParam, newParam, filterProp, propValue, fuzzyMatch, index });
                    currentLeft = Expression.Call(
                        typeof(Enumerable), "Any", new Type[] { subtype },
                        currentLeft,
                        predExpr
                        );
                    return(Expression.Lambda <Func <T, bool> >(currentLeft, new[] { predParam }));
                }
                //else
                currentLeft = Expression.PropertyOrField(currentLeft, name);
            }

            Expression <Func <T, bool> > subPredicate = null;

            //we build the right differently for fuzzy vs not
            if (!fuzzyMatch)
            {
                Expression right;
                //this is for when we have an enumerable in the filter and we want to map it to a singular property on the entity
                if (typeof(IEnumerable).IsAssignableFrom(filterProp.Property.PropertyType) && filterProp.Property.PropertyType != typeof(string))
                {
                    var propValueConstant = Expression.Constant(propValue);
                    var subtype           = propValueConstant.Type.GetGenericArguments()[0];
                    right        = Expression.Call(typeof(Enumerable), "Contains", new Type[] { subtype }, propValueConstant, currentLeft);
                    subPredicate = Expression.Lambda <Func <T, bool> >(right, new[] { predParam });
                }
                else
                {
                    //we have to do a conversion or else it will blow up when the entity type is nullable
                    right = Expression.Convert(Expression.Constant(propValue), currentLeft.Type);
                    var mapped = FilterTestMap[filterProp.Test](currentLeft, right);
                    if (mapped.Type != typeof(bool))
                    {
                        // Handle conditions that do no return a boolean initially
                        subPredicate = Expression.Lambda <Func <T, bool> >(Expression.GreaterThan(mapped, Expression.Constant(0)), new[] { predParam });
                    }
                    else
                    {
                        subPredicate = Expression.Lambda <Func <T, bool> >(mapped, new[] { predParam });
                    }
                }


                //we enqueue the filteroperations to do "look back" style of operations
                FilterOperations.Enqueue(filterProp.Operation);
            }
            else//its a fuzzy match
            {
                var right = Expression.Call(null, LikeMethod, Expression.Constant(EF.Functions), currentLeft, Expression.Constant(propValue));
                subPredicate = Expression.Lambda <Func <T, bool> >(right, new[] { predParam });
            }
            return(subPredicate);
        }
Example #11
0
        ///<summary>
        /// Проверяется, подходит ли элемент под фильтр
        ///</summary>
        ///<param name="item">Проверяемый элемент</param>
        ///<returns>Результат - подходит ли элемент</returns>
        public bool Acceptable(BaseEntityObject item)
        {
            if (item == null || FilterProperty == null || Values.Length == 0)
            {
                return(true);
            }
            PropertyInfo typeProp;

            if ((typeProp = item.GetType().GetProperty(FilterProperty.Name)) == null ||
                !FilterProperty.PropertyType.Name.Equals(typeProp.PropertyType.Name))
            {
                return(true);
            }

            if (FilterProperty.PropertyType.Name.ToLower() != "string" &&
                FilterProperty.PropertyType.GetInterface(typeof(IEnumerable <>).Name) != null)
            {
                //Если свойство не string (string реализует интерфейс IEnumerable<>)
                //и реализует интерфейс IEnumerable<> то
                //производится поиск параметра универсального типа
                Type t = FilterProperty.PropertyType;

                while (t != null)
                {
                    if (t.IsGenericType)
                    {
                        t = t.GetGenericArguments().FirstOrDefault();
                        break;
                    }
                    t = t.BaseType;
                }
                if (t == null)
                {
                    return(false);
                }
                if (t.Name != typeof(T).Name)
                {
                    return(false);
                }
            }
            else if (FilterProperty.PropertyType.Name != typeof(T).Name)
            {
                return(false);
            }

            object propertyValue = FilterProperty.GetValue(item, null);

            if (propertyValue == null)
            {
                return(false);
            }

            //Тип свойства реалтзует интерфейс IEnumerable
            if (FilterProperty.PropertyType.Name.ToLower() != "string" &&
                FilterProperty.PropertyType.GetInterface(typeof(IEnumerable <>).Name) != null)
            {
                IEnumerable <T> convertedPropertyValue = ((IEnumerable <T>)propertyValue).ToArray();
                if (!convertedPropertyValue.Any())
                {
                    return(false);
                }
                switch (FilterType)
                {
                case FilterType.Equal:
                    return(convertedPropertyValue.Contains(Values[0]));

                case FilterType.NotEqual:
                    return(!convertedPropertyValue.Contains(Values[0]));

                case FilterType.In:
                    return(convertedPropertyValue.Any(cpv => Values.Contains(cpv)));

                //return Values.Any(v => convertedPropertyValue.Contains(v));
                default:
                    return(false);
                }
            }
            //Проверка, является ли переданный тип наследником BaseSmartCoreObject
            if (FilterProperty.PropertyType.IsSubclassOf(typeof(AbstractDictionary)) ||
                FilterProperty.PropertyType.IsSubclassOf(typeof(StaticDictionary)))
            {
                switch (FilterType)
                {
                case FilterType.Equal:
                    return(propertyValue.Equals(Values[0]));

                case FilterType.NotEqual:
                    return(!propertyValue.Equals(Values[0]));

                case FilterType.In:
                    return(Values.Any(v => propertyValue.Equals(v)));

                default:
                    return(false);
                }
            }
            if (FilterProperty.PropertyType.GetInterface(typeof(IBaseEntityObject).Name) != null)
            {
                switch (FilterType)
                {
                case FilterType.Equal:
                    return(propertyValue.Equals(Values[0]));

                case FilterType.NotEqual:
                    return(!propertyValue.Equals(Values[0]));

                case FilterType.In:
                    return(Values.Any(v => propertyValue.Equals(v)));

                default:
                    return(false);
                }
            }
            if (FilterProperty.PropertyType.Name == typeof(Lifelength).Name)
            {
                Lifelength convertedPropertyValue = (Lifelength)propertyValue;
                Lifelength convertedFilterValue   = Values[0] as Lifelength ?? Lifelength.Null;

                switch (FilterType)
                {
                case FilterType.Less:
                    return(convertedPropertyValue.IsLessIgnoreNulls(convertedFilterValue));

                case FilterType.LessOrEqual:
                    return(convertedPropertyValue.IsLessOrEqualByAnyParameter(convertedFilterValue));

                case FilterType.Equal:
                    return(convertedPropertyValue.Equals(convertedFilterValue));

                case FilterType.GratherOrEqual:
                    return(convertedPropertyValue.IsGreaterOrEqualByAllParameters(convertedFilterValue));

                case FilterType.Grather:
                    return(convertedPropertyValue.IsGratherIgnoreNulls(convertedFilterValue));

                case FilterType.NotEqual:
                    return(!convertedPropertyValue.Equals(convertedFilterValue));

                case FilterType.In:
                    return(Values.OfType <Lifelength>().Any(convertedPropertyValue.Equals));

                default:
                    return(false);
                }
            }
            if (FilterProperty.PropertyType.IsEnum)
            {
                switch (FilterType)
                {
                case FilterType.Equal:
                    return(Equals(propertyValue, Values[0]));

                case FilterType.NotEqual:
                    return(!Equals(propertyValue, Values[0]));

                case FilterType.In:
                {
                    return(Values.Any(value => Equals(value, propertyValue)));
                }

                default:
                    return(false);
                }
            }

            string typeName = FilterProperty.PropertyType.Name.ToLower();

            switch (typeName)
            {
            case "bool":
            case "boolean":
            {
                bool convertedPropertyValue = Convert.ToBoolean(propertyValue);
                bool convertedFilterValue   = Convert.ToBoolean(Values[0]);
                switch (FilterType)
                {
                case FilterType.Equal:
                    return(convertedPropertyValue == convertedFilterValue);

                case FilterType.NotEqual:
                    return(convertedPropertyValue != convertedFilterValue);

                case FilterType.In:
                    return(Values.Any(v => convertedFilterValue == Convert.ToBoolean(v)));

                default:
                    return(false);
                }
            }

            case "datetime":
            {
                DateTime convertedPropertyValue = Convert.ToDateTime(propertyValue);
                DateTime convertedFilterValue   = Convert.ToDateTime(Values[0]);
                switch (FilterType)
                {
                case FilterType.Less:
                    return(convertedPropertyValue < convertedFilterValue);

                case FilterType.LessOrEqual:
                    return(convertedPropertyValue <= convertedFilterValue);

                case FilterType.Equal:
                    return(convertedPropertyValue == convertedFilterValue);

                case FilterType.GratherOrEqual:
                    return(convertedPropertyValue >= convertedFilterValue);

                case FilterType.Grather:
                    return(convertedPropertyValue > convertedFilterValue);

                case FilterType.NotEqual:
                    return(convertedPropertyValue != convertedFilterValue);

                case FilterType.In:
                    return(Values.Any(v => convertedFilterValue == Convert.ToDateTime(v)));

                case FilterType.Between:
                    return(Convert.ToDateTime(Values[0]) <= convertedPropertyValue && convertedPropertyValue <= Convert.ToDateTime(Values[1]));

                default:
                    return(false);
                }
            }

            case "double":
            {
                double convertedPropertyValue = Convert.ToDouble(propertyValue);
                double convertedFilterValue   = Convert.ToDouble(Values[0]);
                switch (FilterType)
                {
                case FilterType.Less:
                    return(convertedPropertyValue < convertedFilterValue);

                case FilterType.LessOrEqual:
                    return(convertedPropertyValue <= convertedFilterValue);

                case FilterType.Equal:
                    return(convertedPropertyValue == convertedFilterValue);

                case FilterType.GratherOrEqual:
                    return(convertedPropertyValue >= convertedFilterValue);

                case FilterType.Grather:
                    return(convertedPropertyValue > convertedFilterValue);

                case FilterType.NotEqual:
                    return(convertedPropertyValue != convertedFilterValue);

                case FilterType.In:
                    return(Values.Any(v => convertedFilterValue == Convert.ToDouble(v)));

                default:
                    return(false);
                }
            }

            case "int16":
            {
                Int16 convertedPropertyValue = Convert.ToInt16(propertyValue);
                Int16 convertedFilterValue   = Convert.ToInt16(Values[0]);
                switch (FilterType)
                {
                case FilterType.Less:
                    return(convertedPropertyValue < convertedFilterValue);

                case FilterType.LessOrEqual:
                    return(convertedPropertyValue <= convertedFilterValue);

                case FilterType.Equal:
                    return(convertedPropertyValue == convertedFilterValue);

                case FilterType.GratherOrEqual:
                    return(convertedPropertyValue >= convertedFilterValue);

                case FilterType.Grather:
                    return(convertedPropertyValue > convertedFilterValue);

                case FilterType.NotEqual:
                    return(convertedPropertyValue != convertedFilterValue);

                case FilterType.In:
                    return(Values.Any(v => convertedFilterValue == Convert.ToInt16(v)));

                default:
                    return(false);
                }
            }

            case "int32":
            {
                Int32 convertedPropertyValue = Convert.ToInt32(propertyValue);
                Int32 convertedFilterValue   = Convert.ToInt32(Values[0]);
                switch (FilterType)
                {
                case FilterType.Less:
                    return(convertedPropertyValue < convertedFilterValue);

                case FilterType.LessOrEqual:
                    return(convertedPropertyValue <= convertedFilterValue);

                case FilterType.Equal:
                    return(convertedPropertyValue == convertedFilterValue);

                case FilterType.GratherOrEqual:
                    return(convertedPropertyValue >= convertedFilterValue);

                case FilterType.Grather:
                    return(convertedPropertyValue > convertedFilterValue);

                case FilterType.NotEqual:
                    return(convertedPropertyValue != convertedFilterValue);

                case FilterType.In:
                    return(Values.Any(v => convertedFilterValue == Convert.ToInt32(v)));

                default:
                    return(false);
                }
            }

            case "string":
            {
                string convertedPropertyValue = propertyValue.ToString().Trim().ToLower();
                //для строкового фильтра в FilterType.Equal и FilterType.NotEqual
                //проверяются все значения
                switch (FilterType)
                {
                case FilterType.Equal:
                    return(Values.Select(v => new Pattern(v.ToString().Trim().ToLower(), true, true)).All(p => p.IsMatch(convertedPropertyValue)));

                case FilterType.NotEqual:
                    return(!Values.Select(v => new Pattern(v.ToString().Trim().ToLower(), true, true)).Any(p => p.IsMatch(convertedPropertyValue)));

                case FilterType.In:
                    return(Values.Select(v => new Pattern(v.ToString().Trim().ToLower(), true, true)).Any(p => p.IsMatch(convertedPropertyValue)));

                default:
                    return(false);
                }
            }
            }
            return(true);
        }
Example #12
0
 set => this.SetValue(FilterProperty, value);
Example #13
0
        public static IQueryable <TModel> Where <TModel>(this IQueryable <TModel> source, string FilterStrValstring) where TModel : ModelBase
        {
            var queryExpr           = source.Expression;
            var type                = typeof(TModel);
            var parameterExpression = Expression.Parameter(type, "x");
            var constant            = Expression.Constant("");
            var property            = Expression.Property(parameterExpression, "lastname");
            var expression          = Expression.Equal(property, constant);

            string test = FilterStrValstring;

            //http://xxxxx.com/catalog/v1/products?name=pizza,pates&rating=4,5&days=sunda
            //FilterStrValstring = "lastname=Guyzo,jean&email&firstname";
            var FilterValues = FilterStrValstring.Trim().Split('&').Select(x => x.Trim()).ToList();

            /*
             * Use cases
             * (rating=[4,10]) the value contain in this sequence
             * (rating=[,10])  the values less or equal than 10
             * (rating=[4,])   tht value greater or equal than 4
             */
            // equal Case

            foreach (var FilterProperty in FilterValues)
            {
                var Tosplit = FilterProperty.Split("=");
                if (Tosplit.Length <= 1)
                {
                    continue;
                }

                var    propertyToincludeInFilter = Tosplit[0]; //property to Filter
                string fieldsTofilter            = Tosplit[1]; //table of properties

                if (fieldsTofilter.Trim().StartsWith("[") && fieldsTofilter.Trim().EndsWith("]"))
                { //case value in []
                    var item = new StringBuilder(fieldsTofilter);
                    item.Replace("[", "");
                    item.Replace("]", "");
                    string item2 = item.ToString().Trim();
                    var    value = item2.Split(",");



                    var val1 = value[0].Equals("")? "0": value[0]; // check this case [,ConstSecond]
                    var val2 = value[1].Equals("") ? value[0] : value[1];
                    // check this Case ["",""] empty set
                    if (val1.Equals("") && val2.Equals(""))
                    {
                        continue;
                    }

                    //value of set example [Constfirst,ConstSecond]
                    var Constfirst  = Expression.Constant(Int32.Parse(val1), typeof(int));
                    var ConstSecond = Expression.Constant(Int32.Parse(val2), typeof(int));
                    var property3   = Expression.Property(parameterExpression, propertyToincludeInFilter);


                    var expressionFirst  = Expression.GreaterThanOrEqual(property3, Constfirst);
                    var expressionSecond = Expression.LessThanOrEqual(property3, ConstSecond);

                    expression = Expression.And(expressionSecond, expressionFirst);
                    //expression = Expression.Or(expression,expressionSecond);
                }
                else  //case equal
                {
                    foreach (var item in fieldsTofilter.Split(","))
                    {
                        if (string.IsNullOrEmpty(item))
                        {
                            continue;
                        }

                        constant = Expression.Constant(item);
                        var property2   = Expression.Property(parameterExpression, propertyToincludeInFilter);
                        var expression2 = Expression.Equal(property2, constant);
                        expression = Expression.Or(expression, expression2);
                    }
                }
            }// End equal case

            var lambda = Expression.Lambda <Func <TModel, bool> >(expression, parameterExpression);

            return(source.Where(lambda));
        }
 public IQueryBuilder SetQueryArguments(FilterProperty property, ExpressionType expressionType = ExpressionType.In, params FilterParameter[] parameters)
 {
     (_queryGroups ??= new List <FilterGroup>())
     .Add(new FilterGroup(property, expressionType).AssignParameters(parameters.ToArray()));
     return(this);
 }
 public override FilterList GetAutoFilterFields(Type cardType, FilterProperty filterProperty, FullTextSearchResultModel searchModel)
 {
     return(null);
 }
Example #16
0
        private void FilterCommand_Excute(object obj)
        {
            var    txt          = obj as System.Windows.Controls.TextBox;
            string text         = txt.Text;
            bool   excuteFilter = false;

            #region 锁检测
            if (1 == Interlocked.Read(ref usingResource))
            {
                return;
            }
            //原始值是0,判断是时候使用原始值,但判断后值为1,进行了设置
            if (0 == Interlocked.Exchange(ref usingResource, 1))
            {
                if (text != null)
                {
                    if (text == "")
                    {
                        excuteFilter = true;
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(text))
                        {
                            excuteFilter = true;
                        }
                        else
                        {
                        }
                    }
                }
            }
            #endregion

            try
            {
                if (excuteFilter)
                {
                    if (txt.IsFocused)
                    {
                        if (ItemsSource != null && ItemsSource.Count > 0)
                        {
                            if (ComparePropertyList == null)//筛选比较的列
                            {
                                ComparePropertyList = new List <FilterProperty>();
                            }

                            string enColumnName = txt.DataContext.ToString();//属性名  英文名


                            if (!string.IsNullOrWhiteSpace(text))
                            {
                                PropertyInfo filterProperty = typePropertylist.FirstOrDefault(fp => fp.Name == enColumnName);
                                if (filterProperty != null)
                                {
                                    object filterValue;
                                    string conditionStr = GetValueAndCondition(text, out filterValue);
                                    if (!text.StartsWith("=") && !text.StartsWith("!like") && "string" == filterProperty.PropertyType.ToString().Replace("System.Nullable`1[", "").Replace("]", "").Replace("System.", "").ToLower())
                                    {
                                        conditionStr = "like";
                                    }
                                    FilterProperty filterfp = ComparePropertyList.FirstOrDefault(p => p.PropertyName == enColumnName);
                                    if (filterfp == null)
                                    {
                                        FilterProperty fp = new FilterProperty();
                                        fp.PropertyName  = enColumnName;
                                        fp.ConditionStr  = conditionStr;
                                        fp.PropertyInfo  = filterProperty;
                                        fp.PropertyValue = filterValue;
                                        ComparePropertyList.Add(fp);
                                    }
                                    else
                                    {
                                        filterfp.PropertyName  = enColumnName;
                                        filterfp.ConditionStr  = conditionStr;
                                        filterfp.PropertyValue = filterValue;
                                    }

                                    object value = ChangeValueForType(filterProperty.PropertyType, text);
                                    filterProperty.SetValue(Condition, value, null);
                                }
                            }
                            else
                            {
                                PropertyInfo filterProperty = typePropertylist.FirstOrDefault(fp => fp.Name == enColumnName);
                                if (filterProperty != null)
                                {
                                    FilterProperty fp = ComparePropertyList.FirstOrDefault(p => p.PropertyName == enColumnName);
                                    if (fp != null)
                                    {
                                        ComparePropertyList.Remove(fp);
                                    }
                                    object value = GetDefaultForType(filterProperty.PropertyType);
                                    filterProperty.SetValue(Condition, value, null);
                                }
                            }

                            SetFilterComm(Condition);

                            int rowCount = this.ListCollectionView.Count;//最大行

                            if (rowCount <= 0)
                            {
                                this.ListCollectionView.Remove(this.Condition);

                                this.ListCollectionView.AddNewItem(this.Condition);

                                this.ListCollectionView.CommitNew();    //未解决问题 输入= 就会提交事务失败
                                if (this.ListCollectionView.Count != 1) //应对提交事务失败时出现的BUG
                                {
                                    this.ItemsSource.Remove(this.Condition);
                                }
                            }
                            else if (rowCount == 1)
                            {
                                if (this.Condition.Equals(this.ListCollectionView.GetItemAt(0)))
                                {
                                    this.ListCollectionView.Remove(this.Condition);
                                    this.ListCollectionView.AddNewItem(this.Condition);
                                    this.ListCollectionView.CommitNew();
                                }
                                else
                                {
                                    this.ListCollectionView.Remove(this.Condition);
                                    this.ListCollectionView.CommitNew();
                                }
                            }
                            else
                            {
                                this.ListCollectionView.Remove(this.Condition);
                                this.ListCollectionView.CommitNew();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                Interlocked.Exchange(ref usingResource, 0);
            }
        }
Example #17
0
    public FilterProperty[] GetFilterProperties()
    {
        int i;

        Type filterControlType 		= this.ControlInterfaceType;
        PropertyInfo[] properties 	= filterControlType.GetProperties( BindingFlags.Public | BindingFlags.Instance );

        FilterProperty[] filterProperties = new FilterProperty[ properties.Length ];

        for( i = 0; i < filterProperties.Length; i++ )
        {
            filterProperties[i] = new FilterProperty( properties[i], this );
        }

        return filterProperties;
    }
 set => SetValue(FilterProperty, value);
 set => base.SetValue(FilterProperty, value);