Exemplo n.º 1
0
        private static Expression ParaseBetween(ParameterExpression parameter, FilterNode conditions)
        {
            ParameterExpression p   = parameter;
            Expression          key = Expression.Property(p, conditions.key);
            var valueArr            = conditions.value.ToString().Split(',');

            if (valueArr.Length != 2)
            {
                throw new NotImplementedException("ParaseBetween参数错误");
            }
            try
            {
                int.Parse(valueArr[0]);
                int.Parse(valueArr[1]);
            }
            catch
            {
                throw new NotImplementedException("ParaseBetween参数只能为数字");
            }
            Expression expression = Expression.Constant(true, typeof(bool));
            //开始位置
            Expression startvalue = Expression.Constant(int.Parse(valueArr[0]));
            Expression start      = Expression.GreaterThanOrEqual(key, Expression.Convert(startvalue, key.Type));

            Expression endvalue = Expression.Constant(int.Parse(valueArr[1]));
            Expression end      = Expression.GreaterThanOrEqual(key, Expression.Convert(endvalue, key.Type));

            return(Expression.AndAlso(start, end));
        }
        /// <summary>
        /// Add a general binder.
        /// </summary>
        /// <param name="binder"></param>
        /// <returns></returns>
        public FluentBinder Bind(IBindingProvider binder)
        {
            if (this._hook != null)
            {
                var fluidBinder = (FluentBindingProvider <TAttribute>)binder;
                fluidBinder.BuildParameterDescriptor = _hook;
                _hook = null;
            }

            // Apply filters
            if (this._filterDescription.Count > 0)
            {
                binder = new FilteringBindingProvider <TAttribute>(
                    _configuration,
                    this._nameResolver,
                    binder,
                    FilterNode.And(this._filterDescription));

                this._filterDescription.Clear();
            }

            var opts = new FluentBinder(_configuration, _nameResolver, binder);

            _binders.Add(opts);
            return(opts);
        }
Exemplo n.º 3
0
        public void ParseOrQuoted()
        {
            var node = FilterNode.Parse("LastName = 'Smi*' OR FirstName = 'J*'");

            Assert.IsNotNull(node);
            Assert.IsNull(node.Evaluated);

            Assert.IsNotNull(node.Left);
            Assert.IsNull(node.Left.Evaluated);
            Assert.IsNull(node.Left.Left);
            Assert.IsNull(node.Left.Right);
            Assert.AreEqual(LogicalOperator.None, node.Left.Operator);
            Assert.IsNotNull(node.Left.Term);
            Assert.AreEqual(RelationalOperator.Equal, node.Left.Term.Operator);
            Assert.AreEqual("LastName", node.Left.Term.PropertyName);
            Assert.AreEqual("Smi*", node.Left.Term.Value);

            Assert.IsNotNull(node.Right);
            Assert.IsNull(node.Right.Evaluated);
            Assert.IsNull(node.Right.Left);
            Assert.IsNull(node.Right.Right);
            Assert.AreEqual(LogicalOperator.None, node.Right.Operator);
            Assert.IsNotNull(node.Right.Term);
            Assert.AreEqual(RelationalOperator.Equal, node.Right.Term.Operator);
            Assert.AreEqual("FirstName", node.Right.Term.PropertyName);
            Assert.AreEqual("J*", node.Right.Term.Value);

            Assert.AreEqual(LogicalOperator.Or, node.Operator);
            Assert.IsNull(node.Term);
        }
Exemplo n.º 4
0
        public async Task ValidateAsync(object?value, ValidationContext context, AddError addError)
        {
            var count = context.Path.Count();

            if (value != null && (count == 0 || (count == 2 && context.Path.Last() == InvariantPartitioning.Key)))
            {
                FilterNode <ClrValue>?filter = null;

                if (value is string s)
                {
                    filter = ClrFilter.Eq(Path(context), s);
                }
                else if (value is double d)
                {
                    filter = ClrFilter.Eq(Path(context), d);
                }

                if (filter != null)
                {
                    var found = await checkUniqueness(filter);

                    if (found.Any(x => x.Id != context.ContentId))
                    {
                        addError(context.Path, T.Get("contents.validation.unique"));
                    }
                }
            }
        }
        public static ValueTask <FilterNode <ClrValue>?> TransformAsync(FilterNode <ClrValue> nodeIn, DomainId appId, ITagService tagService)
        {
            Guard.NotNull(nodeIn, nameof(nodeIn));
            Guard.NotNull(tagService, nameof(tagService));

            return(nodeIn.Accept(new FilterTagTransformer(appId, tagService)));
        }
Exemplo n.º 6
0
        /// <summary>
        /// create the subcategories for each unique propellant combination found
        /// </summary>
        private void GenerateEngineTypes()
        {
            var engines = new List <SubCategoryItem>();

            foreach (List <string> ls in propellantCombos)
            {
                string propList = string.Join(",", ls.ToArray());
                string name     = propList;
                string icon     = propList;
                SetName(ref name);

                if (!string.IsNullOrEmpty(name) && !subCategoriesDict.ContainsKey(name))
                {
                    var checks = new List <ConfigNode>()
                    {
                        CheckNodeFactory.MakeCheckNode(CheckPropellant.ID, propList, exact: true)
                    };
                    var filters = new List <ConfigNode>()
                    {
                        FilterNode.MakeFilterNode(false, checks)
                    };
                    var sC = new SubcategoryNode(SubcategoryNode.MakeSubcategoryNode(name, icon, false, filters), this);
                    subCategoriesDict.Add(name, sC);
                }
            }
        }
Exemplo n.º 7
0
        public async Task ValidateAsync(object?value, ValidationContext context, AddError addError)
        {
            if (context.Mode == ValidationMode.Optimized)
            {
                return;
            }

            var count = context.Path.Count();

            if (value != null && (count == 0 || (count == 2 && context.Path.Last() == InvariantPartitioning.Key)))
            {
                FilterNode <ClrValue>?filter = null;

                if (value is string s)
                {
                    filter = ClrFilter.Eq(Path(context), s);
                }
                else if (value is double d)
                {
                    filter = ClrFilter.Eq(Path(context), d);
                }

                if (filter != null)
                {
                    var found = await checkUniqueness(filter);

                    if (found.Any(x => x.Id != context.ContentId))
                    {
                        addError(context.Path, "Another content with the same value exists.");
                    }
                }
            }
        }
Exemplo n.º 8
0
        public static FilterNode Transform(FilterNode nodeIn, Guid appId, ISchemaEntity schema, ITagService tagService)
        {
            Guard.NotNull(tagService, nameof(tagService));
            Guard.NotNull(schema, nameof(schema));

            return(nodeIn.Accept(new FilterTagTransformer(appId, schema, tagService)));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Determines if the specified path is included by the filter.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>True if the specified path is included by the filter.</returns>
        public bool IsPathIncluded(string path)
        {
            PropertyPath propertyPath = PropertyPath.TryParse(path, null);

            if (propertyPath == null || propertyPath.IsExcluded)
            {
                return(false);
            }

            FilterNode node = m_rootNode;

            foreach (string part in propertyPath.Parts)
            {
                FilterNode childNode = node.FindChild(part);
                if (!ShouldIncludeProperty(node, childNode))
                {
                    return(false);
                }
                if (childNode == null)
                {
                    break;
                }
                node = childNode;
            }

            return(true);
        }
Exemplo n.º 10
0
        public async Task ValidateAsync(object value, ValidationContext context, AddError addError)
        {
            var count = context.Path.Count();

            if (value != null && (count == 0 || (count == 2 && context.Path.Last() == InvariantPartitioning.Key)))
            {
                FilterNode <ClrValue> filter = null;

                if (value is string s)
                {
                    filter = ClrFilter.Eq(Path(context), s);
                }
                else if (value is double d)
                {
                    filter = ClrFilter.Eq(Path(context), d);
                }

                if (filter != null)
                {
                    var found = await context.GetContentIdsAsync(context.SchemaId, filter);

                    if (found.Any(x => x != context.ContentId))
                    {
                        addError(context.Path, "Another content with the same value exists.");
                    }
                }
            }
        }
        public async Task <IActionResult> FilterRecords(string model, int pageNo, [FromBody] FilterNode filter, int pageSize = Globals.AdminDefaultPageCount, string orderBy = null)
        {
            try
            {
                ICoreAdminService coreAdminService = new CoreAdminService(Area, _serviceProvider);
                var modelType = coreAdminService.GetModelType(model);
                if (modelType == null)
                {
                    return(BadRequest($"Model {model} is not found"));
                }

                var result = await coreAdminService.GetAllFor(modelType, pageNo, pageSize, orderBy, filter); //_adminRepository.GetAllFor(model, pageNo, pageSize, orderBy);

                if (result != null)
                {
                    return(Ok(result));
                }
                return(NotFound());
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error occured while getting all records for model: {model}", ex);
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }
        }
Exemplo n.º 12
0
        public async Task ValidateAsync(object value, ValidationContext context, AddError addError)
        {
            var count = context.Path.Count();

            if (value != null && (count == 0 || (count == 2 && context.Path.Last() == InvariantPartitioning.Instance.Master.Key)))
            {
                FilterNode filter = null;

                if (value is string s)
                {
                    filter = new FilterComparison(Path(context), FilterOperator.Equals, new FilterValue(s));
                }
                else if (value is double d)
                {
                    filter = new FilterComparison(Path(context), FilterOperator.Equals, new FilterValue(d));
                }

                if (filter != null)
                {
                    var found = await context.GetContentIdsAsync(context.SchemaId, filter);

                    if (found.Any(x => x != context.ContentId))
                    {
                        addError(context.Path, "Another content with the same value exists.");
                    }
                }
            }
        }
        protected QueryBase VisitFilter(FilterNode node, ElasticQueryMapperState state)
        {
            // TODO: Both Solr and Lucene creates a new state from the ExecutionContexts - not sure why
            // var state2 = new LuceneQueryMapperState((IEnumerable<IExecutionContext>) state.ExecutionContexts);

            return(Visit(node.PredicateNode, state));
        }
        public List <FilterNode> BuildFiltersTree()
        {
            var filters = new List <FilterNode>();

            var type  = typeof(IOnlineFilter);
            var types = _nwaves.GetTypes()
                        .Where(p => type.IsAssignableFrom(p) && p != type);

            foreach (var tp in types)
            {
                // at the first level add only "direct implementers" of IOnlineFilter:

                if (tp.BaseType.Name != "Object")
                {
                    continue;
                }

                var newNode = new FilterNode
                {
                    FilterType = tp
                };

                filters.Add(newNode);

                AddFilterNodes(tp, ref newNode);
            }

            return(filters);
        }
Exemplo n.º 15
0
        public static FilterNode <ClrValue> Transform(FilterNode <ClrValue> nodeIn, Guid appId, ITagService tagService)
        {
            Guard.NotNull(nodeIn, nameof(nodeIn));
            Guard.NotNull(tagService, nameof(tagService));

            return(nodeIn.Accept(new FilterTagTransformer(appId, tagService)));
        }
Exemplo n.º 16
0
        public void ParseOr()
        {
            var node = FilterNode.Parse("name = value Or orders > 50");

            Assert.IsNotNull(node);
            Assert.IsNull(node.Evaluated);

            Assert.IsNotNull(node.Left);
            Assert.IsNull(node.Left.Evaluated);
            Assert.IsNull(node.Left.Left);
            Assert.IsNull(node.Left.Right);
            Assert.AreEqual(LogicalOperator.None, node.Left.Operator);
            Assert.IsNotNull(node.Left.Term);
            Assert.AreEqual(RelationalOperator.Equal, node.Left.Term.Operator);
            Assert.AreEqual("name", node.Left.Term.PropertyName);
            Assert.AreEqual("value", node.Left.Term.Value);

            Assert.IsNotNull(node.Right);
            Assert.IsNull(node.Right.Evaluated);
            Assert.IsNull(node.Right.Left);
            Assert.IsNull(node.Right.Right);
            Assert.AreEqual(LogicalOperator.None, node.Right.Operator);
            Assert.IsNotNull(node.Right.Term);
            Assert.AreEqual(RelationalOperator.Greater, node.Right.Term.Operator);
            Assert.AreEqual("orders", node.Right.Term.PropertyName);
            Assert.AreEqual("50", node.Right.Term.Value);

            Assert.AreEqual(LogicalOperator.Or, node.Operator);
            Assert.IsNull(node.Term);
        }
Exemplo n.º 17
0
        public XDocument SaveToXml()
        {
            XDocument document = new XDocument();

            XElement rootElement;

            switch (this.ModelType)
            {
            case YamsterModelType.Message:
                rootElement = new XElement("YamsterMessageQuery");
                break;

            case YamsterModelType.Thread:
                rootElement = new XElement("YamsterThreadQuery");
                break;

            default:
                throw new NotSupportedException();
            }
            document.Add(rootElement);

            rootElement.Add(new XAttribute("Title", this.Title));

            XElement filterNodeElement = null;

            if (FilterNode != null)
            {
                filterNodeElement = FilterNode.SaveToXml();
            }

            rootElement.Add(new XElement("FilterNode", filterNodeElement));

            return(document);
        }
Exemplo n.º 18
0
        public static FilterNode Filter(ODataNode expr)
        {
            var result = new FilterNode(new Token(TokenType.QueryName, "$filter"));

            result.Children.Add(expr);
            return(result);
        }
Exemplo n.º 19
0
            public override void WritePropertyName(string name)
            {
                m_reentrancy++;
                base.WritePropertyName(name);
                m_reentrancy--;

                if (m_reentrancy == 0)
                {
                    // pop the previous property off the stack if we aren't the first one
                    if (m_statusStack.Peek().IsProperty)
                    {
                        m_statusStack.Pop();
                    }

                    // check to see if this property has been included, or an ancestor or a descendant
                    Status     status     = m_statusStack.Peek();
                    FilterNode node       = status.Node;
                    FilterNode childNode  = node == null ? null : node.FindChild(name);
                    bool       isIncluded = status.IsIncluded && (node == null || ShouldIncludeProperty(node, childNode));
                    if (isIncluded)
                    {
                        m_writer.WritePropertyName(name);
                    }

                    // push a node for this property onto the stack
                    m_statusStack.Push(new Status {
                        IsIncluded = isIncluded, IsProperty = true, Node = childNode
                    });
                }
            }
Exemplo n.º 20
0
        public GridPage <DingNew> GetNew(int id)
        {
            var res = new GridPage <DingNew>()
            {
                code = ResCode.Success
            };
            var result = new GridPage <List <DingNew> >()
            {
                code = ResCode.Success
            };
            FilterNode node = new FilterNode();

            node.andorop  = "and";
            node.binaryop = "eq";
            node.key      = "Id";
            node.value    = id;
            var pageReq = new DatetimePointPageReq();

            pageReq.query.Add(node);
            result = DataBaseHelper <DingNew> .GetList(_uowProvider, result, pageReq, x => x.Include(a => a.DingClassify));

            if (result.data.Count > 0)
            {
                res.data = result.data[0];
            }
            return(res);
        }
Exemplo n.º 21
0
        public GridPage <List <DingNew> > GetNews(DatetimePointPageReq pageReq, int?id)
        {
            var res = new GridPage <List <DingNew> >()
            {
                code = ResCode.Success
            };

            if (id != null)
            {
                FilterNode node = new FilterNode();
                node.andorop  = "and";
                node.binaryop = "eq";
                node.key      = "DingClassify.Id";
                node.value    = id;
                if (pageReq == null)
                {
                    pageReq = new DatetimePointPageReq();
                }
                pageReq.query.Add(node);
                res = DataBaseHelper <DingNew> .GetList(_uowProvider, res, pageReq, x => x.Include(a => a.DingClassify));
            }
            else
            {
                //all
                res = DataBaseHelper <DingNew> .GetList(_uowProvider, res, pageReq, x => x.Include(a => a.DingClassify));
            }
            return(res);
        }
Exemplo n.º 22
0
        // var tok = this.expect('code')
        // , node = new nodes.Code(tok.val, tok.buffer, tok.escape)
        // , block
        // , i = 1;
        // node.line = this.line();
        // while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i;
        // block = 'indent' == this.lookahead(i).type;
        // if (block) {
        // this.skip(i-1);
        // node.block = this.block();
        // }
        // return node;

        private Node parseFilter()
        {
            Token token = expect(GetType())
            ;
            Filter    filterToken = (Filter)token;
            Attribute attr        = (Attribute)accept(typeof(Attribute))
            ;

            _jadeLexer.setPipeless(true);
            Node tNode = parseTextBlock();

            _jadeLexer.setPipeless(false);

            FilterNode node = new FilterNode();

            node.setValue(filterToken.getValue());
            node.setLineNumber(line());
            node.setFileName(filename);
            node.setTextBlock(tNode);
            if (attr != null)
            {
                node.setAttributes(attr.getAttributes());
            }
            return(node);
        }
Exemplo n.º 23
0
        public ActionResult <DataRes <List <SingleProductSell> > > GetList(OrderReq req)
        {
            var res = new DataRes <List <SingleProductSell> >()
            {
                code = ResCode.Success
            };

            if (req != null)
            {
                using (var uow = _uowProvider.CreateUnitOfWork())
                {
                    string sql = "select x.Plateform,x.UserAccount,x.SaleOrderCode," +
                                 "x.ShippingMethodPlatform, x.ShippingMethod, x.WarehouseCode," +
                                 "x.DatePaidPlatform, x.PlatformShipTime, x.DateLatestShip, x.Currency," +
                                 "x.CountryCode, ProductCount,a.ProductSku, a.Qty,c.pcrProductSku SubProductSku," +
                                 " a.Qty * c.PcrQuantity SubQty, b.WarehouseId " +
                                 "from EC_SalesOrder x join EC_SalesOrderDetail a on x.OrderId = a.OrderId " +
                                 "join EC_SkuRelation b on a.ProductSku = b.ProductSku " +
                                 "join EC_SkuRelationItems c on b.relationid = c.relationid " +
                                 "order by x.SaleOrderCode";
                    var    repository = uow.GetRepository <SingleProductSell>();
                    string orderStr   = req.order + (req.order.reverse ? " desc" : "");
                    res.data = repository.ListFromSql(sql, FilterNode.ListToString(req.query), orderStr).ToList();
                }
            }
            else
            {
                res.code = ResCode.NoValidate;
                res.msg  = ResMsg.ParameterIsNull;
            }
            return(res);
        }
Exemplo n.º 24
0
        public static ValueTask <FilterNode <ClrValue>?> TransformAsync(FilterNode <ClrValue> nodeIn, Guid appId, ISchemaEntity schema, ITagService tagService)
        {
            Guard.NotNull(nodeIn, nameof(nodeIn));
            Guard.NotNull(tagService, nameof(tagService));
            Guard.NotNull(schema, nameof(schema));

            return(nodeIn.Accept(new FilterTagTransformer(appId, schema, tagService)));
        }
Exemplo n.º 25
0
        public static FilterNode <ClrValue>?Transform(FilterNode <ClrValue> nodeIn, Guid appId, ISchemaEntity schema, ITagService tagService)
        {
            Guard.NotNull(nodeIn);
            Guard.NotNull(tagService);
            Guard.NotNull(schema);

            return(nodeIn.Accept(new FilterTagTransformer(appId, schema, tagService)));
        }
Exemplo n.º 26
0
 public FilteredJsonWriter(JsonWriter writer, FilterNode node)
 {
     m_writer      = writer;
     m_statusStack = new Stack <Status>();
     m_statusStack.Push(new Status {
         IsIncluded = true, Node = node
     });
 }
Exemplo n.º 27
0
        /// <summary>
        /// The subsequent Bind* operations only apply when the Attribute's property is not null.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public FluentBindingRule <TAttribute> WhenIsNotNull(string propertyName)
        {
            var prop = ResolveProperty(propertyName);

            AppendFilter(FilterNode.NotNull(prop));

            return(this);
        }
Exemplo n.º 28
0
        public IEnumerable <ASTNode> Transform(FilterNode item)
        {
            yield return(item);

            foreach (var child in TransformAll(item.FilterContents))
            {
                yield return(child);
            }
        }
Exemplo n.º 29
0
		public void ConstructTerminalNode()
		{
			RelationalExpression exp = new RelationalExpression("Name", "Smith", RelationalOperator.Equal);
			FilterNode node = new FilterNode(exp);
			Assert.AreEqual(exp, node.Term);
			Assert.IsFalse(node.Evaluated.HasValue);
			Assert.IsNull(node.Left);
			Assert.IsNull(node.Right);
			Assert.AreEqual(LogicalOperator.None, node.Operator);
		}
Exemplo n.º 30
0
        public void EvaluateTerminalNodeFalse()
        {
            var exp  = new RelationalExpression("Name", "Smith", RelationalOperator.Equal);
            var node = new FilterNode(exp);

            node.Evaluate(delegate { return(false); });

            Assert.IsTrue(node.Evaluated.HasValue);
            Assert.IsFalse(node.Evaluated.Value);
        }
Exemplo n.º 31
0
        private void addNewFilter_Click(object sender, EventArgs e)
        {
            FilterNode filterNode = new FilterNode();

            filterNode.FilterablePropertyDescription = this.PropertiesToFilter[0];
            filterNode.Operator = (PropertyFilterOperator)this.PropertiesToFilter[0].SupportedOperators.Values.GetValue(0);
            this.incompleteItems.Add(filterNode);
            this.filterNodes.Add(filterNode);
            this.filterNode_PropertyChanged(filterNode, EventArgs.Empty);
        }
Exemplo n.º 32
0
		public void EvaluateTerminalNodeFalse()
		{
			RelationalExpression exp = new RelationalExpression("Name", "Smith", RelationalOperator.Equal);
			FilterNode node = new FilterNode(exp);

			node.Evaluate(delegate(FilterNode n) { return false; });

			Assert.IsTrue(node.Evaluated.HasValue);
			Assert.IsFalse(node.Evaluated.Value);
		}
Exemplo n.º 33
0
        public IEnumerable<Changeset> GetChangesetsByProject(string projectName, FilterNode rootFilterNode, int topRequestValue)
        {
            var key = this.GetChangesetsByProjectKey(projectName, rootFilterNode, topRequestValue);

            if (HttpContext.Current.Items[key] == null)
            {
                HttpContext.Current.Items[key] = this.RequestChangesetsByProject(projectName, rootFilterNode, topRequestValue);
            }

            return (IEnumerable<Changeset>)HttpContext.Current.Items[key];
        }
Exemplo n.º 34
0
        public IEnumerable<Changeset> GetChangesetsByBranch(string path, FilterNode rootFilterNode, int topRequestValue)
        {
            var key = this.GetChangesetsByBranchKey(path, rootFilterNode, topRequestValue);

            if (HttpContext.Current.Items[key] == null)
            {
                HttpContext.Current.Items[key] = this.RequestChangesetsByBranch(path, rootFilterNode, topRequestValue);
            }

            return (IEnumerable<Changeset>)HttpContext.Current.Items[key];
        }
Exemplo n.º 35
0
        public IEnumerable<Changeset> GetChangesetsByProjectCollection(FilterNode rootFilterNode, int topRequestValue)
        {
            var key = this.GetChangesetsByProjectCollectionKey(rootFilterNode, topRequestValue);

            if (HttpContext.Current.Items[key] == null)
            {
                HttpContext.Current.Items[key] = this.RequestChangesetsByProjectCollection(rootFilterNode, topRequestValue);
            }

            return (IEnumerable<Changeset>)HttpContext.Current.Items[key];
        }
Exemplo n.º 36
0
        public IEnumerable<Build> GetBuildsByProject(string projectName, FilterNode rootFilterNode)
        {
            var key = this.GetBuildsByProjectKey(projectName, rootFilterNode);

            if (HttpContext.Current.Items[key] == null)
            {
                HttpContext.Current.Items[key] = this.RequestBuildsByProject(projectName, rootFilterNode);
            }

            return (IEnumerable<Build>)HttpContext.Current.Items[key];
        }
Exemplo n.º 37
0
        public IEnumerable<Build> GetBuildsByProjectCollection(FilterNode rootFilterNode)
        {
            var key = this.GetBuildsByProjectCollectionKey(rootFilterNode);

            if (HttpContext.Current.Items[key] == null)
            {
                HttpContext.Current.Items[key] = this.RequestBuildsByProjectCollection(rootFilterNode);
            }

            return (IEnumerable<Build>)HttpContext.Current.Items[key];
        }
Exemplo n.º 38
0
		public FilterEvaluator(FilterNode expressionTree, PropertyDescriptorCollection listItemProperties)
		{
			if (expressionTree == null)
				throw new ArgumentNullException("expressionTree");
			if (listItemProperties == null)
				throw new ArgumentNullException("listItemProperties");
			if (listItemProperties.Count == 0)
				throw new ArgumentException("listItemProperties");

			this.tree = expressionTree;

			this.CreatePredicates(expressionTree, listItemProperties);
		}
Exemplo n.º 39
0
		public void ConstructOrNode()
		{
			RelationalExpression expLeft = new RelationalExpression("Name", "Smith", RelationalOperator.Less);
			RelationalExpression expRight = new RelationalExpression("Name", "Smith", RelationalOperator.Greater);
			FilterNode nodeLeft = new FilterNode(expLeft);
			FilterNode nodeRight = new FilterNode(expRight);
			FilterNode node = new FilterNode(nodeLeft, nodeRight, LogicalOperator.Or);

			Assert.IsNull(node.Term);
			Assert.IsFalse(node.Evaluated.HasValue);
			Assert.AreEqual(nodeLeft, node.Left);
			Assert.AreEqual(nodeRight, node.Right);
			Assert.AreEqual(LogicalOperator.Or, node.Operator);
		}
Exemplo n.º 40
0
 private string GetChangesetsByProjectCollectionKey(FilterNode rootFilterNode, int topRequestValue)
 {
     return string.Format(CultureInfo.InvariantCulture, "TFSChangesetProxy.GetChangesetsByProjectCollection_{0}_{1}", this.GetFilterNodeKey(rootFilterNode), topRequestValue);
 }
Exemplo n.º 41
0
 private string GetChangesetsByProjectKey(string projectName, FilterNode rootFilterNode, int topRequestValue)
 {
     return string.Format(CultureInfo.InvariantCulture, "TFSChangesetProxy.GetChangesetsByProject_{0}_{1}_{2}", projectName, this.GetFilterNodeKey(rootFilterNode), topRequestValue);
 }
Exemplo n.º 42
0
        private IEnumerable<Changeset> RequestChangesetsByProject(string projectName, FilterNode rootFilterNode, int topRequestValue)
        {
            var versionControlServer = this.TfsConnection.GetService<TeamFoundation.VersionControl.Client.VersionControlServer>();
            var preliminaryChangesets = versionControlServer.QueryHistory(
                GetRequestedPath(null, projectName, rootFilterNode),
                TeamFoundation.VersionControl.Client.VersionSpec.Latest,
                0,
                TeamFoundation.VersionControl.Client.RecursionType.Full,
                GetRequestedCommitter(rootFilterNode),
                GetRequestedVersionFrom(rootFilterNode),
                GetRequestedVersionTo(rootFilterNode),
                topRequestValue,
                false,
                false,
                false);

            return FilterChangesets(preliminaryChangesets.Cast<TeamFoundation.VersionControl.Client.Changeset>().Select(c => c.ToModel(this.GetTfsWebAccessArtifactUrl(c.ArtifactUri))), rootFilterNode).ToArray();
        }
Exemplo n.º 43
0
        private IEnumerable<Changeset> RequestChangesetsByProjectCollection(FilterNode rootFilterNode, int topRequestValue)
        {
            var css = this.TfsConnection.GetService<Microsoft.TeamFoundation.Server.ICommonStructureService3>();
            var teamProjects = css.ListAllProjects();

            return teamProjects.SelectMany(p => this.GetChangesetsByProject(p.Name, rootFilterNode, topRequestValue));
        }
Exemplo n.º 44
0
        private static IEnumerable<Changeset> FilterChangesets(IEnumerable<Changeset> changesets, FilterNode rootFilterNode)
        {
            if (rootFilterNode != null)
            {
                changesets = FilterChangesetsByCreationDate(changesets, rootFilterNode);
                changesets = FilterChangesetsByOwner(changesets, rootFilterNode);
                changesets = FilterChangesetsByComment(changesets, rootFilterNode);
                changesets = FilterChangesetsByArtifactUri(changesets, rootFilterNode);
            }

            return changesets;
        }
Exemplo n.º 45
0
        private static IEnumerable<Build> FilterBuilds(IEnumerable<Build> builds, FilterNode rootFilterNode)
        {
            if (rootFilterNode != null)
            {
                var startTimeParameter = rootFilterNode.SingleOrDefault(p => p.Key.Equals("StartTime"));
                var finishTimeParameter = rootFilterNode.SingleOrDefault(p => p.Key.Equals("FinishTime"));
                var buildFinishedParameter = rootFilterNode.SingleOrDefault(p => p.Key.Equals("BuildFinished"));
                var requestedByParameter = rootFilterNode.SingleOrDefault(p => p.Key.Equals("RequestedBy"));
                var startTimeValue = default(DateTime);

                if (startTimeParameter != null && DateTime.TryParse(startTimeParameter.Value, out startTimeValue))
                {
                    switch (startTimeParameter.Sign)
                    {
                        case FilterExpressionType.Equal:
                            builds = builds.Where(b => b.StartTime.Equals(startTimeValue));
                            break;

                        case FilterExpressionType.NotEqual:
                            builds = builds.Where(b => !b.StartTime.Equals(startTimeValue));
                            break;

                        case FilterExpressionType.GreaterThan:
                            builds = builds.Where(b => b.StartTime > startTimeValue);
                            break;

                        case FilterExpressionType.LessThan:
                            builds = builds.Where(b => b.StartTime < startTimeValue);
                            break;

                        default:
                            throw new NotSupportedException("Start time field can only be filtered with equality, inequality, greater than and less than operators");
                    }
                }

                var finishTimeValue = default(DateTime);
                if (finishTimeParameter != null && DateTime.TryParse(finishTimeParameter.Value, out finishTimeValue))
                {
                    switch (finishTimeParameter.Sign)
                    {
                        case FilterExpressionType.Equal:
                            builds = builds.Where(b => b.FinishTime.Equals(finishTimeValue));
                            break;

                        case FilterExpressionType.NotEqual:
                            builds = builds.Where(b => !b.FinishTime.Equals(finishTimeValue));
                            break;

                        case FilterExpressionType.GreaterThan:
                            builds = builds.Where(b => b.FinishTime > finishTimeValue);
                            break;

                        case FilterExpressionType.LessThan:
                            builds = builds.Where(b => b.FinishTime < finishTimeValue);
                            break;

                        default:
                            throw new NotSupportedException("Finish time field can only be filtered with equality, inequality, greater than and less than operators");
                    }
                }

                var buildFinishedValue = default(bool);
                if (buildFinishedParameter != null && bool.TryParse(buildFinishedParameter.Value, out buildFinishedValue))
                {
                    switch (buildFinishedParameter.Sign)
                    {
                        case FilterExpressionType.Equal:
                            builds = builds.Where(b => b.BuildFinished == buildFinishedValue);
                            break;

                        case FilterExpressionType.NotEqual:
                            builds = builds.Where(b => b.BuildFinished != buildFinishedValue);
                            break;

                        default:
                            throw new NotSupportedException("Build Finished field can only be filtered with equality and inequality operators");
                    }
                }

                if (requestedByParameter != null)
                {
                    switch (requestedByParameter.Sign)
                    {
                        case FilterExpressionType.Equal:
                            builds = builds.Where(b => b.RequestedBy.Equals(requestedByParameter.Value));
                            break;

                        case FilterExpressionType.NotEqual:
                            builds = builds.Where(b => !b.RequestedBy.Equals(requestedByParameter.Value));
                            break;

                        default:
                            throw new NotSupportedException("Requested By field can only be filtered with equality and inequality operators");
                    }
                }
            }

            return builds;
        }
Exemplo n.º 46
0
        private static TeamFoundation.Build.Client.IBuildDetailSpec CreateBuildDetailSpec(TeamFoundation.Build.Client.IBuildServer buildServer, string projectName, FilterNode rootFilterNode)
        {
            var detailSpec = default(TeamFoundation.Build.Client.IBuildDetailSpec);

            if (rootFilterNode != null)
            {
                var definitionSpec = buildServer.CreateBuildDefinitionSpec(projectName);
                var definition = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Definition", StringComparison.OrdinalIgnoreCase));
                var number = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Number", StringComparison.OrdinalIgnoreCase));
                var quality = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Quality", StringComparison.OrdinalIgnoreCase));
                var reason = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Reason", StringComparison.OrdinalIgnoreCase));
                var status = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Status", StringComparison.OrdinalIgnoreCase));
                var requestedFor = rootFilterNode.SingleOrDefault(p => p.Key.Equals("RequestedFor", StringComparison.OrdinalIgnoreCase));

                if (definition != null)
                {
                    if (definition.Sign != FilterExpressionType.Equal)
                    {
                        throw new DataServiceException(501, "Not Implemented", "Build Definition can only be filtered with an equality operator", "en-US", null);
                    }

                    definitionSpec.Name = definition.Value;
                }

                detailSpec = buildServer.CreateBuildDetailSpec(definitionSpec);
                if (number != null)
                {
                    if (number.Sign != FilterExpressionType.Equal)
                    {
                        throw new DataServiceException(501, "Not Implemented", "Build Number can only be filtered with an equality operator", "en-US", null);
                    }

                    detailSpec.BuildNumber = number.Value;
                }

                if (quality != null)
                {
                    if (quality.Sign != FilterExpressionType.Equal)
                    {
                        throw new DataServiceException(501, "Not Implemented", "Build Quality can only be filtered with an equality operator", "en-US", null);
                    }

                    detailSpec.Quality = quality.Value;
                }

                if (requestedFor != null)
                {
                    if (requestedFor.Sign != FilterExpressionType.Equal)
                    {
                        throw new DataServiceException(501, "Not Implemented", "Requested For can only be filtered with an equality operator", "en-US", null);
                    }

                    detailSpec.RequestedFor = requestedFor.Value;
                }

                if (status != null)
                {
                    if (status.Sign != FilterExpressionType.Equal)
                    {
                        throw new DataServiceException(501, "Not Implemented", "Build Status can only be filtered with an equality operator", "en-US", null);
                    }

                    var statusValue = default(TeamFoundation.Build.Client.BuildStatus);
                    if (Enum.TryParse<TeamFoundation.Build.Client.BuildStatus>(status.Value, out statusValue))
                    {
                        detailSpec.Status = statusValue;
                    }
                }

                if (reason != null)
                {
                    if (reason.Sign != FilterExpressionType.Equal)
                    {
                        throw new DataServiceException(501, "Not Implemented", "Build Reason can only be filtered with an equality operator", "en-US", null);
                    }

                    var reasonValue = default(TeamFoundation.Build.Client.BuildReason);
                    if (Enum.TryParse<TeamFoundation.Build.Client.BuildReason>(reason.Value, out reasonValue))
                    {
                        detailSpec.Reason = reasonValue;
                    }
                }

                return detailSpec;
            }
            else
            {
                detailSpec = buildServer.CreateBuildDetailSpec(projectName);
            }

            return detailSpec;
        }
Exemplo n.º 47
0
		public void EvaluateAndTreeTrueTrue()
		{
			FilterNode nodeLeft = new FilterNode(new TestFilterNode(true), new TestFilterNode(false), LogicalOperator.Or);
			FilterNode nodeRight = new FilterNode(new TestFilterNode(true), new TestFilterNode(true), LogicalOperator.And);
			FilterNode node = new FilterNode(nodeLeft, nodeRight, LogicalOperator.And);

			Assert.IsTrue(node.Evaluate(delegate(FilterNode n) { return ((TestFilterNode)n).Result; }));

			Assert.IsTrue(nodeLeft.Evaluated.HasValue);
			Assert.IsTrue(nodeLeft.Evaluated.Value);
			Assert.IsTrue(nodeRight.Evaluated.HasValue);
			Assert.IsTrue(nodeRight.Evaluated.Value);
			Assert.IsTrue(node.Evaluated.HasValue);
			Assert.IsTrue(node.Evaluated.Value);
		}
Exemplo n.º 48
0
 private string GetChangesetsByBranchKey(string path, FilterNode rootFilterNode, int topRequestValue)
 {
     return string.Format(CultureInfo.InvariantCulture, "TFSChangesetProxy.GetChangesetsByBranch_{0}_{1}_{2}", path, this.GetFilterNodeKey(rootFilterNode), topRequestValue);
 }
Exemplo n.º 49
0
		private bool Evaluator(FilterNode node)
		{
			return this.nodePredicates[node](this.currentListItem);
		}
Exemplo n.º 50
0
 private string GetBuildsByProjectCollectionKey(FilterNode rootFilterNode)
 {
     return string.Format(CultureInfo.InvariantCulture, "TFSBuildProxy.GetBuildsByProjectCollection_{0}", this.GetFilterNodeKey(rootFilterNode));
 }
Exemplo n.º 51
0
 private string GetBuildsByProjectKey(string projectName, FilterNode rootFilterNode)
 {
     return string.Format(CultureInfo.InvariantCulture, "TFSBuildProxy.GetBuildsByProject_{0}_{1}", projectName, this.GetFilterNodeKey(rootFilterNode));
 }
Exemplo n.º 52
0
        private IEnumerable<Build> RequestBuildsByProject(string projectName, FilterNode rootFilterNode)
        {
            var buildServer = this.TfsConnection.GetService<TeamFoundation.Build.Client.IBuildServer>();

            var spec = CreateBuildDetailSpec(buildServer, projectName, rootFilterNode);
            var preliminaryResults = buildServer.QueryBuilds(spec).Builds.Select(b => b.ToModel());

            return FilterBuilds(preliminaryResults, rootFilterNode).ToArray();
        }
Exemplo n.º 53
0
        private IEnumerable<Build> RequestBuildsByProjectCollection(FilterNode rootFilterNode)
        {
            var teamProjects = this.TfsConnection.CatalogNode.QueryChildren(
                    new Guid[] { CatalogResourceTypes.TeamProject },
                    false,
                    CatalogQueryOptions.None);

            IEnumerable<Build> preliminaryResults = null;
            var buildServer = this.TfsConnection.GetService<TeamFoundation.Build.Client.IBuildServer>();

            if (rootFilterNode != null && rootFilterNode.Count(p => p.Key.Equals("Project", StringComparison.OrdinalIgnoreCase)) > 0)
            {
                var projectParameter = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Project", StringComparison.OrdinalIgnoreCase));
                var spec = CreateBuildDetailSpec(buildServer, projectParameter.Value, rootFilterNode);
                preliminaryResults = buildServer.QueryBuilds(spec).Builds.Select(b => b.ToModel());
            }
            else
            {
                var specs = teamProjects.Select(t => CreateBuildDetailSpec(buildServer, t.Resource.DisplayName, rootFilterNode));
                preliminaryResults = specs.Select(s => buildServer.QueryBuilds(s)).SelectMany(r => r.Builds).Select(b => b.ToModel());
            }

            return FilterBuilds(preliminaryResults, rootFilterNode).ToArray();
        }
Exemplo n.º 54
0
        private static TeamFoundation.VersionControl.Client.VersionSpec GetRequestedVersionTo(FilterNode rootFilterNode)
        {
            if (rootFilterNode != null)
            {
                if (rootFilterNode.SingleOrDefault(p => p.Key.Equals("Id", StringComparison.OrdinalIgnoreCase)) != null)
                {
                    return GetRequestedIdVersionTo(rootFilterNode);
                }
                else if (rootFilterNode.SingleOrDefault(p => p.Key.Equals("CreationDate", StringComparison.OrdinalIgnoreCase)) != null)
                {
                    return GetRequestedDateVersionTo(rootFilterNode);
                }
            }

            return null;
        }
Exemplo n.º 55
0
		public void ConstructAndTree()
		{
			FilterNode nodeLeft = new FilterNode(new TestFilterNode(true), new TestFilterNode(true), LogicalOperator.Or);
			FilterNode nodeRight = new FilterNode(new TestFilterNode(true), new TestFilterNode(true), LogicalOperator.Or);
			FilterNode node = new FilterNode(nodeLeft, nodeRight, LogicalOperator.And);

			Assert.IsNull(node.Term);
			Assert.IsFalse(node.Evaluated.HasValue);
			Assert.AreEqual(nodeLeft, node.Left);
			Assert.AreEqual(nodeRight, node.Right);
			Assert.AreEqual(LogicalOperator.And, node.Operator);
		}
Exemplo n.º 56
0
		protected virtual void CreatePredicates(FilterNode tree, PropertyDescriptorCollection properties)
		{
			nodePredicates = new Dictionary<FilterNode, Predicate>();

			List<PropertyDescriptor> propList = new List<PropertyDescriptor>();

			foreach (FilterNode node in tree)
			{
				// Only create predicates for terminal nodes.
				if (node.Term == null)
					continue;

				string propertyName = node.Term.PropertyName;
				string propertyValue = node.Term.Value;
				PropertyDescriptor property = null;

				// Verify that the property name in the expression is a property of the list item type.
				// If the property name is of the form "A.B", it is assumed to refer to a property of a property (a property path).
				if (propertyName.Contains("."))
				{
					property = new PropertyPathDescriptor(properties[0].ComponentType, propertyName);
				}
				else
				{
					foreach (PropertyDescriptor prop in properties)
					{
						if (prop.Name == propertyName)
						{
							property = prop;
							break;
						}
					}
				}

				if (property == null)
					throw new ArgumentException("The property '" + propertyName + "' is not a property of the list item type.", "Filter");

				if (!propList.Contains(property))
					propList.Add(property);

				// "null" is a special literal meaning a null value, not the characters 'n' 'u' 'l' 'l'.
				if (string.Compare(propertyValue, "null", true) == 0)
					propertyValue = null;

				// If the property is of string type, create a predicate that does regular expression matching.  Otherwise create a predicate
				// that uses the default Comparer<T> where T is the property type.
				Predicate predicate = null;
				if (property.PropertyType == typeof(string))
				{
					predicate = new StringComparerPredicate(property, propertyValue, node.Term.Operator).Matches;
				}
				else
				{
					Type predicateType = typeof(PropertyComparerPredicate<>).MakeGenericType(new Type[] { property.PropertyType });
					object pred = Activator.CreateInstance(predicateType, property, propertyValue, node.Term.Operator);
					predicate = (Predicate)Delegate.CreateDelegate(typeof(Predicate), pred, predicateType.GetMethod("Matches"));
				}

				// Save the predicate for use by the Evaluator method.
				this.nodePredicates.Add(node, predicate);
			}

			// Save the list of properties referenced in the filter expression.
			this.props = new PropertyDescriptorCollection(propList.ToArray(), true);
		}
Exemplo n.º 57
0
        /// <summary>
        /// Gets the count treshold to minimize the number of elements retrieved from TFS
        /// </summary>
        private int GetTopRequestValue(ODataQueryOperation operation, FilterNode parameters)
        {
            int topRequestValue = int.MaxValue;

            if (parameters == null || !parameters.Any(p => p.Key.Equals("Owner") || p.Key.Equals("CreationDate") || p.Key.Equals("Comment") || p.Key.Equals("ArtifactUri")))
            {
                if (operation.IsCountRequest)
                {
                    if (!string.IsNullOrEmpty(operation.ContinuationToken))
                    {
                        var parts = operation.ContinuationToken.Split(':').Select(int.Parse);
                        topRequestValue = parts.First() + parts.Last() + 1;
                    }
                }
                else
                {
                    if (operation.TopCount > 0)
                    {
                        topRequestValue = operation.TopCount + operation.SkipCount + 1;
                    }
                }
            }

            return topRequestValue;
        }
        private void AddFilterNode(string fieldName, object value, FilterExpressionType expressionType, FilterNodeRelationship filterNodeRelationship)
        {
            if (this.rootFilterNode != null && this.rootFilterNode.SingleOrDefault(p => p.Key.Equals(fieldName, StringComparison.OrdinalIgnoreCase)) != null)
            {
                throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "More than one filter expression found for attribute {0}. Only one filter expression per attribute is supported.", fieldName));
            }

            var filterNode = new FilterNode { Key = fieldName, Value = (value == null) ? "null" : value.ToString(), Sign = expressionType, NodeRelationship = filterNodeRelationship };
            if (this.rootFilterNode != null)
            {
                this.rootFilterNode.AddNode(filterNode);
            }
            else
            {
                this.rootFilterNode = filterNode;
            }
        }
Exemplo n.º 59
0
		public void EvaluateOrNodeFalseFalse()
		{
			RelationalExpression expLeft = new RelationalExpression("Name", "Smith", RelationalOperator.Less);
			RelationalExpression expRight = new RelationalExpression("Name", "Smith", RelationalOperator.Greater);
			FilterNode nodeLeft = new FilterNode(expLeft);
			FilterNode nodeRight = new FilterNode(expRight);
			FilterNode node = new FilterNode(nodeLeft, nodeRight, LogicalOperator.Or);

			Assert.IsFalse(node.Evaluate(delegate(FilterNode n) { return false; }));

			Assert.IsTrue(nodeLeft.Evaluated.HasValue);
			Assert.IsFalse(nodeLeft.Evaluated.Value);
			Assert.IsTrue(nodeRight.Evaluated.HasValue);
			Assert.IsFalse(nodeRight.Evaluated.Value);
			Assert.IsTrue(node.Evaluated.HasValue);
			Assert.IsFalse(node.Evaluated.Value);
		}
Exemplo n.º 60
0
        private static string GetRequestedPath(string branch, string projectName, FilterNode rootFilterNode)
        {
            var path = "$/";
            var branchParameter = default(FilterNode);

            if (rootFilterNode != null)
            {
                branchParameter = rootFilterNode.SingleOrDefault(p => p.Key.Equals("Branch", StringComparison.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(branch))
            {
                var branchName = EntityTranslator.DecodePath(branch);
                path = string.Format(CultureInfo.InvariantCulture, branchName.StartsWith("$/", StringComparison.Ordinal) ? "{0}/*" : "$/{0}/*", branchName);
            }
            else if (branchParameter != null && !string.IsNullOrEmpty(branchParameter.Value))
            {
                if (branchParameter.Sign != FilterExpressionType.Equal)
                {
                    throw new DataServiceException(501, "Not Implemented", "Changeset Branch can only be filtered with an equality operator", "en-US", null);
                }

                var branchName = EntityTranslator.DecodePath(branchParameter.Value);
                path = string.Format(CultureInfo.InvariantCulture, branchName.StartsWith("$/", StringComparison.Ordinal) ? "{0}/*" : "$/{0}/*", branchName);
            }
            else if (!string.IsNullOrEmpty(projectName))
            {
                path = string.Format(CultureInfo.InvariantCulture, "$/{0}", projectName);
            }

            return path;
        }