Exemplo n.º 1
0
        public List <Record> SearchTitle(string title)
        {
            Console.WriteLine("SearchingTitle:" + title);
            var result = records.Find(filterBuilder.Regex(record => record.title, new BsonRegularExpression(title, "i")));

            return(result.ToList());
        }
Exemplo n.º 2
0
        public override FilterDefinition <MongoContentEntity> Visit(SingleValueFunctionCallNode nodeIn)
        {
            var fieldNode = nodeIn.Parameters.ElementAt(0);
            var valueNode = nodeIn.Parameters.ElementAt(1);

            if (nodeIn.Name == "endswith")
            {
                var value = BuildRegex(valueNode, v => v + "$");

                return(Filter.Regex(BuildFieldDefinition(fieldNode), value));
            }
            if (nodeIn.Name == "startswith")
            {
                var value = BuildRegex(valueNode, v => "^" + v);

                return(Filter.Regex(BuildFieldDefinition(fieldNode), value));
            }
            if (nodeIn.Name == "contains")
            {
                var value = BuildRegex(valueNode, v => v);

                return(Filter.Regex(BuildFieldDefinition(fieldNode), value));
            }

            throw new NotSupportedException();
        }
Exemplo n.º 3
0
        public override FilterDefinition <MongoContentEntity> Visit(SingleValueFunctionCallNode nodeIn)
        {
            var fieldNode = nodeIn.Parameters.ElementAt(0);
            var valueNode = nodeIn.Parameters.ElementAt(1);

            if (string.Equals(nodeIn.Name, "endswith", StringComparison.OrdinalIgnoreCase))
            {
                var value = BuildRegex(valueNode, v => v + "$");

                return(Filter.Regex(BuildFieldDefinition(fieldNode), value));
            }

            if (string.Equals(nodeIn.Name, "startswith", StringComparison.OrdinalIgnoreCase))
            {
                var value = BuildRegex(valueNode, v => "^" + v);

                return(Filter.Regex(BuildFieldDefinition(fieldNode), value));
            }

            if (string.Equals(nodeIn.Name, "contains", StringComparison.OrdinalIgnoreCase))
            {
                var value = BuildRegex(valueNode, v => v);

                return(Filter.Regex(BuildFieldDefinition(fieldNode), value));
            }

            throw new NotSupportedException();
        }
Exemplo n.º 4
0
        public async Task <List <LinkTable> > GetSearch(string line)//выборка для общего списка
        {
            // строитель фильтров

            var builder = new FilterDefinitionBuilder <LinkTable>();
            var filters = builder.Or(builder.Regex("Longlink", line), builder.Regex("Shortlink", line));     // фильтр для выборки всех документов

            return(await Links.Find(filters).ToListAsync());
        }
Exemplo n.º 5
0
        public void AddFavorityGenreToFantasyBooks()
        {
            var filter = _filter.Regex(BooksTableFieldNames.Genre, "fantasy") &
                         _filter.Regex(BooksTableFieldNames.Genre, "^((?!favority).)*$");

            var update = _update.AddToSet(BooksTableFieldNames.Genre, "favority");

            _context.Books.UpdateMany(filter, update);
        }
Exemplo n.º 6
0
        public override FilterDefinition <T> Visit(CompareFilter <ClrValue> nodeIn, None args)
        {
            var propertyName = nodeIn.Path.ToString();

            var value = nodeIn.Value.Value;

            switch (nodeIn.Operator)
            {
            case CompareOperator.Empty:
                return(Filter.Or(
                           Filter.Exists(propertyName, false),
                           Filter.Eq <object?>(propertyName, null),
                           Filter.Eq <object?>(propertyName, string.Empty),
                           Filter.Size(propertyName, 0)));

            case CompareOperator.Exists:
                return(Filter.And(
                           Filter.Exists(propertyName, true),
                           Filter.Ne <object?>(propertyName, null)));

            case CompareOperator.Matchs:
                return(Filter.Regex(propertyName, BuildMatchRegex(nodeIn)));

            case CompareOperator.StartsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => "^" + s)));

            case CompareOperator.Contains:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s)));

            case CompareOperator.EndsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s + "$")));

            case CompareOperator.Equals:
                return(Filter.Eq(propertyName, value));

            case CompareOperator.GreaterThan:
                return(Filter.Gt(propertyName, value));

            case CompareOperator.GreaterThanOrEqual:
                return(Filter.Gte(propertyName, value));

            case CompareOperator.LessThan:
                return(Filter.Lt(propertyName, value));

            case CompareOperator.LessThanOrEqual:
                return(Filter.Lte(propertyName, value));

            case CompareOperator.NotEquals:
                return(Filter.Ne(propertyName, value));

            case CompareOperator.In:
                return(Filter.In(propertyName, ((IList)value !).OfType <object>()));
            }

            throw new NotSupportedException();
        }
Exemplo n.º 7
0
        public static IList <BsonDocument> GetSrmStartEventsForWorker(int workerId, IMongoCollection <BsonDocument> collection)
        {
            var filter = Query.And(Query.Eq("worker", workerId),
                                   Query.Eq("k", "msg"),
                                   Query.Regex("v", new BsonRegularExpression("^Resource Manager: listening on port")));

            return(collection.Find(filter).ToList());
        }
Exemplo n.º 8
0
        public static Dictionary <int, IList <BsonDocument> > GetQueriesBySessionIdForLogfile(string file, IMongoCollection <BsonDocument> collection)
        {
            Dictionary <int, IList <BsonDocument> > queryLinesBySession = new Dictionary <int, IList <BsonDocument> >();
            var filter = Query.And(
                Query.Eq("file", file),
                Query.Or(Query.Regex("message", new BsonRegularExpression("QueryExecute")),
                         Query.Regex("message", new BsonRegularExpression("StatementPrepare")),
                         Query.Regex("message", new BsonRegularExpression("StatementExecute"))));

            var cursor = collection.Find(filter).ToCursor();

            foreach (var document in cursor.ToEnumerable())
            {
                string message = BsonDocumentHelper.GetString("message", document);
                if (String.IsNullOrWhiteSpace(message))
                {
                    continue;
                }

                // Get the first space-delimited segment in the message.
                int indexOfSpace = message.IndexOf(' ');
                if (indexOfSpace == -1)
                {
                    var line = BsonDocumentHelper.GetInt("line", document);
                    Log.WarnFormat("Failed to find expected session ID in message '{0}'. ({1}:{2})  Skipping event..", message, file, line);
                    continue;
                }
                string firstMessageSegment = message.Substring(0, indexOfSpace);

                // Get Session ID out of the segment.
                int  sessionId       = 0;
                bool parsedSessionId = false;
                if (!String.IsNullOrWhiteSpace(firstMessageSegment))
                {
                    string sessionIdString = firstMessageSegment.Replace("Session", "").Replace(":", "");
                    parsedSessionId = Int32.TryParse(sessionIdString, out sessionId);
                }
                if (!parsedSessionId)
                {
                    var line = BsonDocumentHelper.GetInt("line", document);
                    Log.WarnFormat("Failed to parse expected session ID in message '{0}'. ({1}:{2})  Skipping event..", message, file, line);
                    continue;
                }

                if (!queryLinesBySession.ContainsKey(sessionId))
                {
                    queryLinesBySession[sessionId] = new List <BsonDocument>();
                }
                queryLinesBySession[sessionId].Add(document);
            }

            return(queryLinesBySession);
        }
Exemplo n.º 9
0
        public async Task DeleteByPrefixAsync(string prefix,
                                              CancellationToken ct = default)
        {
            var name = GetFileName(prefix, nameof(prefix));

            try
            {
                var match = new BsonRegularExpression($"^{name}");

                var fileQuery = await bucket.FindAsync(Filters.Regex(x => x.Id, match), cancellationToken : ct);

                await fileQuery.ForEachAsync(async file =>
                {
                    try
                    {
                        await bucket.DeleteAsync(file.Id, ct);
                    }
                    catch (GridFSFileNotFoundException)
                    {
                        return;
                    }
                }, ct);
            }
            catch (GridFSFileNotFoundException)
            {
                return;
            }
        }
Exemplo n.º 10
0
        private FilterDefinition <ToDoListEntity> ApplyWhereStatement(FilterDefinitionBuilder <ToDoListEntity> builder, ListQueryDataStructure queryDataStructure)
        {
            FilterDefinition <ToDoListEntity> filter = builder.Ne(x => x.Status, (int)ToDoListStatus.Archived);

            if (queryDataStructure.Id.HasValue)
            {
                filter = filter & (builder.Eq(x => x.Id, queryDataStructure.Id.Value));
            }

            if (queryDataStructure.UserId.HasValue)
            {
                filter = filter & (builder.Eq(x => x.UserId, queryDataStructure.UserId.Value));
            }

            if (!string.IsNullOrWhiteSpace(queryDataStructure.Name))
            {
                filter = filter & (builder.Regex(x => x.Name, queryDataStructure.Name));
            }

            if (queryDataStructure.Statuses != null && queryDataStructure.Statuses.Any())
            {
                filter = filter & (builder.In(x => x.Status, queryDataStructure.Statuses));
            }

            return(filter);
        }
        public async Task <IReadOnlyList <IConfigurationEntry> > GetEntries(string component, ConfigurationPath pathPrefix, bool forPages = false, bool recursive = true)
        {
            var filterBuilder = new FilterDefinitionBuilder <MongoDbConfigurationDocument>();

            if (string.IsNullOrWhiteSpace(component))
            {
                component = "root";
            }
            var filter = filterBuilder.Eq(a => a.Component, component);

            if (!ConfigurationPath.IsNullOrEmpty(pathPrefix))
            {
                filter = recursive ? filterBuilder.Regex(a => a.Path, new Regex(pathPrefix.ToString(asPrefix: true))) : filterBuilder.Eq(a => a.Path, pathPrefix.ToString());
            }
            if (forPages)
            {
                filter = filter & filterBuilder.Eq(a => a.VisibleToPages, true);
            }

            var results = await settingsCollectionData.FindAsync(filter);

            var records = await results.ToListAsync();

            return(records.Select(doc => RebuildConfigurationEntry(doc)).ToList());
        }
Exemplo n.º 12
0
 private FilterDefinition <ForumQuestionItem> GetRegexFilter(
     FilterDefinitionBuilder <ForumQuestionItem> builder, string prop, string term
     )
 {
     return(builder.Regex(prop,
                          new BsonRegularExpression("/" + term + "/is")
                          ));
 }
        private List <Book> GetBooksOfFantasyGenre()
        {
            var filter = _filter.Regex(BooksTableFieldNames.Genre, "fantasy");

            return(_context.Books.Find(filter).ToEnumerable()
                   .Select(doc => BookConverter.ConvertDocumentToBook(doc))
                   .ToList());
        }
Exemplo n.º 14
0
 /// <summary>
 /// Creates a regular expression filter to perform a case-insensitive search.
 /// </summary>
 /// <typeparam name="T">The data object type.</typeparam>
 /// <param name="filter">The filter definition builder.</param>
 /// <param name="propertyPath">The property path.</param>
 /// <param name="propertyValue">The property value.</param>
 /// <returns>The regular expression filter definition.</returns>
 public static FilterDefinition <T> EqIgnoreCase <T>(this FilterDefinitionBuilder <T> filter, string propertyPath, string propertyValue)
 {
     if (string.IsNullOrEmpty(propertyPath) || propertyValue == null)
     {
         return(null);
     }
     return(filter.Regex(propertyPath, new BsonRegularExpression("^" + Regex.Escape(propertyValue) + "$", "i")));
 }
Exemplo n.º 15
0
        private FilterDefinition <MessageJournalEntryDocument> BuildFilter(MessageJournalFilter filter, FilterDefinition <MessageJournalEntryDocument> filterDef,
                                                                           FilterDefinitionBuilder <MessageJournalEntryDocument> fb)
        {
            if (filter == null)
            {
                return(filterDef);
            }

            if (filter.Topics.Any())
            {
                var topics = filter.Topics.Select(Normalize);
                filterDef = filterDef & fb.In(e => e.Topic, topics);
            }

            if (filter.Categories.Any())
            {
                var categories = filter.Categories.Select(Normalize);
                filterDef = filterDef & fb.In(e => e.Category, categories);
            }

            if (filter.From != null)
            {
                filterDef = filterDef & fb.Gte(e => e.Timestamp, filter.From);
            }

            if (filter.To != null)
            {
                filterDef = filterDef & fb.Lte(e => e.Timestamp, filter.To);
            }

            if (filter.Origination != null)
            {
                var origination = Normalize(filter.Origination);
                filterDef = filterDef & fb.Eq(e => e.Origination, origination);
            }

            if (filter.Destination != null)
            {
                var destination = Normalize(filter.Destination);
                filterDef = filterDef & fb.Eq(e => e.Destination, destination);
            }

            if (!string.IsNullOrWhiteSpace(filter.MessageName))
            {
                var partial = Normalize(filter.MessageName);
                var pattern = ".*" + Regex.Escape(partial) + ".*";
                var regex   = new BsonRegularExpression(pattern, "i");
                filterDef = filterDef & fb.Regex(e => e.MessageName, regex);
            }

            if (filter.RelatedTo != null)
            {
                var relatedTo = Normalize(filter.RelatedTo);
                filterDef = filterDef & fb.Eq(e => e.RelatedTo, relatedTo);
            }

            return(filterDef);
        }
        public async Task <PublicCompanyDataModel> GetCompanyById(string companyname)
        {
            var filter    = _builder.Regex(e => e.CompanyName, $"/^{companyname}$/i");
            var mongouser = await _context.Companies.Find(filter).FirstOrDefaultAsync();

            var returnuser = _mapper.Map <PublicCompanyDataModel>(mongouser);

            return(returnuser);
        }
Exemplo n.º 17
0
        public override FilterDefinition <T> Visit(FilterComparison nodeIn)
        {
            var propertyName = string.Join(".", nodeIn.Lhs);

            switch (nodeIn.Operator)
            {
            case FilterOperator.Empty:
                return(Filter.Or(Filter.Exists(propertyName, false), Filter.Eq(propertyName, default(T)), Filter.Eq(propertyName, string.Empty), Filter.Eq(propertyName, new T[0])));

            case FilterOperator.StartsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => "^" + s)));

            case FilterOperator.Contains:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s)));

            case FilterOperator.EndsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s + "$")));

            case FilterOperator.Equals:
                return(Filter.Eq(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.GreaterThan:
                return(Filter.Gt(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.GreaterThanOrEqual:
                return(Filter.Gte(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.LessThan:
                return(Filter.Lt(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.LessThanOrEqual:
                return(Filter.Lte(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.NotEquals:
                return(Filter.Ne(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.In:
                return(Filter.In(propertyName, ((IList)nodeIn.Rhs.Value).OfType <object>()));
            }

            throw new NotSupportedException();
        }
Exemplo n.º 18
0
        /// <summary>
        /// 搜索按钮点击时触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBtn_Click(object sender, EventArgs e)
        {
            string text = searchText.Text.Trim();

            if (string.IsNullOrEmpty(text))
            {
                MessageBox.Show("请输入要查询的内容");
                return;
            }
            string name = title.SelectedItem.ToString();
            //将中文对应到数据库中的要查询的key
            Dictionary <string, string> searchKey = new Dictionary <string, string> {
                { "同义词", "standard" }, { "停用词", "stopword" }, { "专有名词", "properNouns" }
            };

            switch (name)
            {
            case STOPWORD:
            {
                //设置过滤器
                FilterDefinitionBuilder <Stopword> builderFilter = new FilterDefinitionBuilder <Stopword>();
                //使用正则表达式匹配所有包含text的value
                BsonRegularExpression       regex  = new BsonRegularExpression(string.Format(".*{0}.*", text));
                FilterDefinition <Stopword> filter = builderFilter.Regex(searchKey[name], regex);

                databind(name, filterStop: filter);
            }
            break;

            case SYNONYM:
            {
                //设置过滤器
                FilterDefinitionBuilder <Synonym> builderFilter = new FilterDefinitionBuilder <Synonym>();
                //使用正则表达式匹配所有包含text的value
                BsonRegularExpression      regex  = new BsonRegularExpression(string.Format(".*{0}.*", text));
                FilterDefinition <Synonym> filter = builderFilter.Regex(searchKey[name], regex);

                databind(name, filterSynonym: filter);
            }
            break;

            case PROPERNOUNS:
            {
                //设置过滤器
                FilterDefinitionBuilder <Proper> builderFilter = new FilterDefinitionBuilder <Proper>();
                //使用正则表达式匹配所有包含text的value
                BsonRegularExpression     regex  = new BsonRegularExpression(string.Format(".*{0}.*", text));
                FilterDefinition <Proper> filter = builderFilter.Regex(searchKey[name], regex);

                databind(name, filterProper: filter);
            }
            break;
            }
        }
Exemplo n.º 19
0
        public async Task <IEnumerable <Product> > GetProducts(string name)
        {
            var builder = new FilterDefinitionBuilder <Product>();
            var filter  = builder.Empty;

            if (!string.IsNullOrWhiteSpace(name))
            {
                filter &= builder.Regex("name", new BsonRegularExpression(name));
            }
            return(await products.Find(filter).ToListAsync());
        }
Exemplo n.º 20
0
        //Переход по ссылке
        public async Task <string> ClickOnTheLink(string link)
        {
            var builder  = new FilterDefinitionBuilder <Link>();
            var filter   = builder.Regex("Hash", new BsonRegularExpression(link));
            var fullLink = await Links.Find(filter).FirstOrDefaultAsync();

            fullLink.NumberOfTransitions++;
            await Links.ReplaceOneAsync(new BsonDocument("Hash", link), fullLink);

            return(fullLink.Title);
        }
Exemplo n.º 21
0
        public override async Task <IEnumerable <Product> > GetAll(string query = null)
        {
            var builder = new FilterDefinitionBuilder <Product>();
            var filter  = builder.Empty;

            if (!String.IsNullOrWhiteSpace(query))
            {
                filter = filter & builder.Regex(x => x.Name, BsonRegularExpression.Create(new Regex(query, RegexOptions.IgnoreCase)));
            }

            return(await Items.Find(filter).ToListAsync());
        }
Exemplo n.º 22
0
        //Получение полной ссылки по сокращённой
        public async Task <string> GetLink(string abbreviated)
        {
            CounterOfVisits visits = await Visits.Find(c => c.Id == "5e392e65fc42fe269cb9dc0a").FirstOrDefaultAsync();

            visits.Counter++;
            await Visits.ReplaceOneAsync(new BsonDocument("_id", new ObjectId("5e392e65fc42fe269cb9dc0a")), visits);

            var builder = new FilterDefinitionBuilder <Link>();
            var filter2 = builder.Regex("AbbreviatedTitle", new BsonRegularExpression(abbreviated));
            var link    = await Links.Find(filter2).FirstOrDefaultAsync();

            return(link.Title);
        }
Exemplo n.º 23
0
        public override FilterDefinition <T> VisitFuncOp([NotNull] FilterParser.FuncOpContext context)
        {
            string id  = context.ID().GetText();
            string str = context.STRING().GetText().Trim('\'');;

            var func = context.func.Type;

            switch (func)
            {
            case FilterParser.STARTSWITH:
                return(_builder.Regex(id, new BsonRegularExpression($"^{str}", "i")));

            case FilterParser.ENDSWITH:
                return(_builder.Regex(id, new BsonRegularExpression($"{str}$", "i")));

            case FilterParser.SUBSTRINGOF:
                return(_builder.Regex(id, new BsonRegularExpression($"{str}", "i")));

            default:
                throw new InvalidOperationException($"Invalid StringOp {context.GetText()}");
            }
        }
Exemplo n.º 24
0
        public async Task <IEnumerable <User> > GetUsers(string name, long chatId)
        {
            var builder = new FilterDefinitionBuilder <User>();
            var filter  = builder.Empty;

            if (!String.IsNullOrWhiteSpace(name))
            {
                filter &= builder.Regex("Name", new BsonRegularExpression(name));
            }

            filter &= builder.Eq("ChatId", chatId);

            return(await Users.Find(filter).ToListAsync());
        }
Exemplo n.º 25
0
        public async Task <List <Models.Task> > GetTasks(
            long?id,
            DateTime?date,
            string?title,
            string?category,
            long?assigneeId,
            bool?isCompleted,
            long?teamId
            )
        {
            var filterBuilder = new FilterDefinitionBuilder <Task>();
            var filter        = filterBuilder.Empty;

            if (!String.IsNullOrWhiteSpace(title))
            {
                filter = filter & filterBuilder.Regex("title", new BsonRegularExpression(title));
            }

            if (id.HasValue)
            {
                filter = filter & filterBuilder.Eq("id", id.Value);
            }

            if (date.HasValue)
            {
                filter = filter & filterBuilder.Eq("date", date.ToString());
            }

            if (assigneeId.HasValue)
            {
                filter = filter & filterBuilder.Eq("assigneeId", assigneeId.Value);
            }

            if (isCompleted.HasValue)
            {
                filter = filter & filterBuilder.Eq("isCompleted", isCompleted.Value);
            }

            if (!String.IsNullOrWhiteSpace(category))
            {
                filter = filter & filterBuilder.Eq("category", category);
            }

            if (teamId.HasValue)
            {
                filter = filter & filterBuilder.Eq("teamId", teamId.Value);
            }

            return(await Tasks.Find(filter).ToListAsync());
        }
Exemplo n.º 26
0
        public async Task LoadAsync()
        {
            var value = this.searchText;

            if (string.IsNullOrWhiteSpace(value))
            {
                this.Searched = false;
                this.Things.Clear();
                this.Words.Collection.Clear();
            }
            else
            {
                this.Searched = true;
                var builder = new FilterDefinitionBuilder <Thing>();
                FilterDefinition <Thing> filter;
                switch (this.SearchModes.Selected.Value.Value)
                {
                case SearchMode.Normal:
                    filter = builder.Regex(
                        PropertySelector <Thing> .Start().SelectMany(z => z.Words).Select(z => z.Text).ToString(),
                        new Regex(Regex.Escape(value), RegexOptions.IgnoreCase));
                    break;

                case SearchMode.WholeWord:
                    filter = builder.Eq(PropertySelector <Thing> .Start().SelectMany(z => z.Words).Select(z => z.Text).ToString(), value);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                string category = null;
                if (this.ExistsCategorys.Selected != string.Empty)
                {
                    category = this.ExistsCategorys.Selected;
                    filter   = filter & builder.AnyEq(z => z.Categorys, this.ExistsCategorys.Selected);
                }
                filter = builder.Eq(z => z.Id, value) | filter;
                var queryResult = await App.Current.ThingSetAccessor.FindAsync(filter, 20);

                this.HasNext = queryResult.HasNext;
                var sortedItems = await queryResult.Items
                                  .OrderBy(z => z.Words.Any(x => x.Text == value)? -1 : 1)
                                  .ThenBy(z => z.Words.Any(x => x.Text.Equals(value, StringComparison.OrdinalIgnoreCase)) ? -1 : 1)
                                  .ToArrayAsync();

                this.Things.Reset(sortedItems.Select(z => new ThingViewModel(z, category)));
                this.Words.Collection.Reset(this.Things.SelectMany(z => z.Words));
            }
            this.RefreshProperties();
        }
Exemplo n.º 27
0
        public static FilterDefinition <BsonDocument> GetApacheRequests(IMongoCollection <BsonDocument> collection, bool includeGatewayHealthCheckRequests = false)
        {
            // Filter down to only access files.
            FilterDefinition <BsonDocument> query = Query.Regex("file", new BsonRegularExpression("^access.*"));

            // Gateway health check requests are generally noise, but may be desired in some situations.
            if (!includeGatewayHealthCheckRequests)
            {
                query = Query.And(query,
                                  Query.Ne("resource", "/favicon.ico"));
            }

            return(query);
        }
Exemplo n.º 28
0
        public IPageList <T> Query <T>(FilterCondition filter) where T : IBaseObject
        {
            this.CheckType <T>();
            IMongoCollection <T>        collection       = this.GetCollection <T>();
            FilterDefinitionBuilder <T> filter2          = Builders <T> .Filter;
            SortDefinitionBuilder <T>   sort             = Builders <T> .Sort;
            FilterDefinition <T>        filterDefinition = filter2.Empty;

            foreach (FilterValue current in filter.Fields)
            {
                switch (current.FilterType)
                {
                case FilterType.LTE:
                    filterDefinition &= filter2.Lte <object>(current.FieldName, current.Value);
                    break;

                case FilterType.GTE:
                    filterDefinition &= filter2.Gte <object>(current.FieldName, current.Value);
                    break;

                case FilterType.LT:
                    filterDefinition &= filter2.Lt <object>(current.FieldName, current.Value);
                    break;

                case FilterType.GT:
                    filterDefinition &= filter2.Gt <object>(current.FieldName, current.Value);
                    break;

                case FilterType.EQ:
                    goto IL_12E;

                case FilterType.Like:
                    filterDefinition &= filter2.Regex(current.FieldName, new Regex(current.Value.ToString(), RegexOptions.IgnoreCase));
                    break;

                default:
                    goto IL_12E;
                }
                continue;
IL_12E:
                filterDefinition &= filter2.Eq <object>(current.FieldName, current.Value);
            }
            Task <long>        task  = collection.CountAsync(filterDefinition, null, default(CancellationToken));
            SortDefinition <T> sort2 = (filter.Direction == OrderDirection.DESC) ? sort.Descending(filter.OrderBy) : sort.Ascending(filter.OrderBy);
            Task <List <T> >   task2 = collection.Find(filterDefinition, null).Sort(sort2).Limit(new int?(filter.PageSize)).Skip(new int?((filter.PageIndex - 1) * filter.PageSize)).ToListAsync(default(CancellationToken));

            return(new PageList <T>(task2.Result, filter.PageIndex, filter.PageSize, (int)task.Result));
        }
Exemplo n.º 29
0
        public async Task <IEnumerable <NoSQLFile> > GetFiles(Dictionary <string, string> filterCriteria)
        {
            // filter builder
            var builder = new FilterDefinitionBuilder <NoSQLFile>();
            var filter  = builder.Empty; // get all documents

            // filter by FileName
            foreach (var item in filterCriteria)
            {
                if (!String.IsNullOrWhiteSpace(item.Value))
                {
                    filter = filter & builder.Regex(item.Key, new BsonRegularExpression(item.Value));
                }
            }
            return(await _files.Find(filter).ToListAsync());
        }
Exemplo n.º 30
0
        ///  <summary>
        ///  Get commands for the apache session using the list of vizqlsessionIDs
        ///
        ///  </summary>
        ///  <param name="browserSession">Browser session</param>
        /// <param name="mongoDatabase"></param>
        ///  <param name="vizqlSessionIds">vizqlSessionIDs used in case of correlated vizql sessions</param>
        ///  <returns></returns>
        private List <TabCommand> GetVizqlServerCommands(BrowserSession browserSession, IMongoDatabase mongoDatabase, List <string> vizqlSessionIds)
        {
            var commands = new List <TabCommand>();
            var vizqlSessionCollection = mongoDatabase.GetCollection <BsonDocument>("vizqlserver_cpp");

            foreach (var vizqlSessionId in vizqlSessionIds)
            {
                // making query compatible with old and newer command name, suggest to remove command-pre when tableau version < 2018.3 becomes less relevant
                var commandQuery = Query.And(Query.Regex("sess", vizqlSessionId + "*"), Query.Or(Query.Eq("k", "command-pre"), Query.Eq("k", "begin-commands-controller.invoke-command")));
                var commandsLogs = vizqlSessionCollection.Find(commandQuery).ToList();

                Log.DebugFormat("Getting commands for vizqlserver session {0}", vizqlSessionId);
                foreach (var commandLog in commandsLogs)
                {
                    //convert the current time to UTC
                    var browserStartTime = (DateTime)commandLog.GetElement("ts").Value - _timeOffset;
                    var timeStr          = browserStartTime.ToUniversalTime().ToString(UtcDateFormat);

                    var jsonCmd = commandLog["v"]["args"].ToString();

                    var command = BuildCommand(jsonCmd);
                    if (command == null)
                    {
                        Log.WarnFormat("Failed to build command from-- {0}", jsonCmd);
                        continue;
                    }

                    //get the user name if it is not already there
                    if (browserSession.User == null)
                    {
                        var user = (string)commandLog.GetValue("user", null);
                        if (user != null)
                        {
                            browserSession.User = user;
                        }
                    }
                    var commandValue = new TabCommand(timeStr, command);
                    commands.Add(commandValue);
                }
            }

            //sort them as due to querying multiple vizqlsession the commands might come in different order
            commands.Sort();
            return(commands);
        }