Esempio n. 1
0
        public static FilterDefinition <TelemetryData> CreateFilter(long?timeStampStart = null, long?timeStampStop = null, string deviceId = null)
        {
            var filterDefinitions = new List <FilterDefinition <TelemetryData> >();

            if (timeStampStart != null)
            {
                filterDefinitions.Add(Builder.Gte(telemetryData => telemetryData.UnixTimeStamp, timeStampStart));
            }

            if (timeStampStop != null)
            {
                filterDefinitions.Add(Builder.Lte(telemetryData => telemetryData.UnixTimeStamp, timeStampStop));
            }

            if (deviceId != null)
            {
                filterDefinitions.Add(Builder.Eq(telemetryData => telemetryData.DeviceId, deviceId));
            }

            var filter = Builder.Empty;

            foreach (var filterDefinition in filterDefinitions)
            {
                filter &= filterDefinition;
            }

            return(filter);
        }
Esempio n. 2
0
        public async Task <List <Movie> > GetMovies(int yearLowerBand, int yearUpperBand)
        {
            var movies = new List <Movie>();

            var projectionBuilder = new ProjectionDefinitionBuilder <Movie>();
            var projection        = projectionBuilder
                                    .Include(x => x.Awards)
                                    .Include(x => x.Genres)
                                    .Include(x => x.Plot)
                                    .Include(x => x.Rated)
                                    .Include(x => x.Title)
                                    .Include(x => x.Year)
                                    .Exclude("_id");

            var filterBuilder = new FilterDefinitionBuilder <Movie>();
            var filter        = filterBuilder.Gte(x => x.Year, yearLowerBand) & filterBuilder.Lte(x => x.Year, yearUpperBand);

            using (IAsyncCursor <Movie> documents = await _database.GetCollection <Movie>("movies")
                                                    .FindAsync(filter, new FindOptions <Movie, Movie>
            {
                Projection = projection
            }))
            {
                while (documents.MoveNext())
                {
                    movies.AddRange(documents.Current);
                }
            }

            return(movies);
        }
Esempio n. 3
0
        public async Task <string> FilterMovies(int yearLowerBand, int yearUpperBand)
        {
            var movies = new List <BsonDocument>();

            var projectionBuilder = new ProjectionDefinitionBuilder <BsonDocument>();
            var projection        = projectionBuilder
                                    .Include("awards")
                                    .Include("genres")
                                    .Include("plot")
                                    .Include("rated")
                                    .Include("title")
                                    .Include("year")
                                    .Exclude("_id");

            var filterBuilder = new FilterDefinitionBuilder <BsonDocument>();
            var filter        = filterBuilder.Gte("year", yearLowerBand) & filterBuilder.Lte("year", yearUpperBand);

            using (IAsyncCursor <BsonDocument> documents = await _database.GetCollection <BsonDocument>("movies").FindAsync(filter))
            {
                while (documents.MoveNext())
                {
                    movies.AddRange(documents.Current);
                }
            }

            return(movies.ToJson());
        }
Esempio n. 4
0
        public override FilterDefinition <T> VisitIntOp([NotNull] FilterParser.IntOpContext context)
        {
            string id      = context.ID().GetText();
            string integer = context.INT().GetText();

            var op = context.op.Type;

            switch (op)
            {
            case FilterParser.EQ:
                return(_builder.Eq(id, integer));

            case FilterParser.NE:
                return(_builder.Ne(id, integer));

            case FilterParser.GT:
                return(_builder.Gt(id, integer));

            case FilterParser.GE:
                return(_builder.Gte(id, integer));

            case FilterParser.LT:
                return(_builder.Lt(id, integer));

            case FilterParser.LE:
                return(_builder.Lte(id, integer));

            default:
                throw new InvalidOperationException($"Invalid StringOp {context.GetText()}");
            }
        }
Esempio n. 5
0
        public List <TimedTrainingScore> Get(int user, DateTime?from, DateTime?to, string show)
        {
            FilterDefinitionBuilder <TimedTrainingScore> builder = Builders <TimedTrainingScore> .Filter;
            FilterDefinition <TimedTrainingScore>        filter  = builder.Eq("owner", user);

            if (from.HasValue && to.HasValue)
            {
                filter &= builder.Lte("dateRecorded", to.Value) & builder.Gte("dateRecorded", from.Value);
            }
            var found = scoreCollection.Find(filter).ToList();

            if (show == "each")
            {
                return(found);
            }
            else
            {
                var groups = found.GroupBy(x => new { x.DateRecordedUtc.Date, x.Type, x.Variant });
                if (show == "bestDay")
                {
                    Func <TimedTrainingScore, TimedTrainingScore, TimedTrainingScore> bestOfADayAggregator = (agg, next) => next.Score > agg.Score ? next : agg;
                    List <TimedTrainingScore> result = groups.Select(x => x.Aggregate(bestOfADayAggregator)).ToList();
                    for (int i = 0; i < result.Count; i++)
                    {
                        result[i].DateRecordedUtc = result[i].DateRecordedUtc.Date;
                    }
                    return(result);
                }
                else // show == "avgDay"
                {
                    return(groups.Select(x => new TimedTrainingScore(x.Average(y => y.Score), x.Key.Type, user, x.Key.Date, x.Key.Variant)).ToList());
                }
            }
        }
        private List <FilterDefinition <Flight> > CreateClauses(SearchCriteriaModel criteriaModel, FilterDefinitionBuilder <Flight> filterBuilder)
        {
            var clauses = new List <FilterDefinition <Flight> >();

            if (criteriaModel.FromDate != null)
            {
                var fromDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.FromDate), DateTimeKind.Utc);
                var clause   = filterBuilder.Gte(f => f.FlightDate, fromDate);
                clauses.Add(clause);
            }
            if (criteriaModel.ToDate != null)
            {
                var toDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.ToDate), DateTimeKind.Utc);
                var clause = filterBuilder.Lte(f => f.FlightDate, toDate);
                clauses.Add(clause);
            }
            if (criteriaModel.AirlineId != null)
            {
                var clause = filterBuilder.Eq(f => f.AirlineId, criteriaModel.AirlineId.Value);
                clauses.Add(clause);
            }
            if (criteriaModel.OriginId != null)
            {
                var clause = filterBuilder.Eq(f => f.OriginAirportId, criteriaModel.OriginId.Value);
                clauses.Add(clause);
            }
            if (criteriaModel.DestinationId != null)
            {
                var clause = filterBuilder.Eq(f => f.DestinationAirportId, criteriaModel.DestinationId.Value);
                clauses.Add(clause);
            }
            return(clauses);
        }
        public async Task <List <RatingWithMetadata> > GetAsync(int user, DateTime?from, DateTime?to, string show)
        {
            FilterDefinitionBuilder <RatingWithMetadata> builder = Builders <RatingWithMetadata> .Filter;
            FilterDefinition <RatingWithMetadata>        filter  = builder.Eq("owner", user);

            if (from.HasValue && to.HasValue)
            {
                filter &= builder.Lte("timestampUtc", to.Value) & builder.Gte("timestampUtc", from.Value);
            }
            var found = await ratingCollection.Find(filter).ToListAsync();

            if (show == "each")
            {
                return(found);
            }
            else
            {
                var groups = found.GroupBy(x => new { timestamp = x.TimestampUtc.Date, variant = x.Variant });
                Func <RatingWithMetadata, RatingWithMetadata, RatingWithMetadata> bestOfADayAggregator  = (agg, next) => next.Rating.Value > agg.Rating.Value ? next : agg;
                Func <RatingWithMetadata, RatingWithMetadata, RatingWithMetadata> endOfTheDayAggregator = (agg, next) => next.TimestampUtc > agg.TimestampUtc ? next : agg;
                Func <RatingWithMetadata, RatingWithMetadata, RatingWithMetadata> aggregator            = show == "bestDay" ? bestOfADayAggregator : endOfTheDayAggregator;
                List <RatingWithMetadata> result = groups.Select(x => x.Aggregate(aggregator)).ToList();
                for (int i = 0; i < result.Count; i++)
                {
                    result[i].TimestampUtc = result[i].TimestampUtc.Date;
                }
                return(result);
            }
        }
Esempio n. 8
0
        private async Task StoreArchiveEventsAsync(IEnumerable <IDomainEvent> archiveEvents)
        {
            var filterBuilder = Builders <IDomainEvent> .Filter;
            var filter        = filterBuilder.And(
                filterBuilder.Eq(nameof(IDomainEvent.AggregateId), archiveEvents.First().AggregateId),
                filterBuilder.Eq(nameof(IDomainEvent.AggregateType), archiveEvents.First().AggregateType.AssemblyQualifiedName));

            switch (_archiveBehavior)
            {
            case SnapshotEventsArchiveBehavior.StoreToNewDatabase:
                var otherDbArchiveCollection = await GetArchiveDatabaseEventCollectionAsync <IDomainEvent>().ConfigureAwait(false);

                await otherDbArchiveCollection.InsertManyAsync(archiveEvents).ConfigureAwait(false);

                break;

            case SnapshotEventsArchiveBehavior.StoreToNewTable:
                var archiveCollection = await GetArchiveEventCollectionAsync <IDomainEvent>().ConfigureAwait(false);

                await archiveCollection.InsertManyAsync(archiveEvents).ConfigureAwait(false);

                break;
            }

            var deleteFilterBuilder = new FilterDefinitionBuilder <IDomainEvent>();
            var deleteFilter        = deleteFilterBuilder.And(filter, deleteFilterBuilder.Lte(nameof(IDomainEvent.Sequence), archiveEvents.Max(e => e.Sequence)));

            await(await GetEventCollectionAsync <IDomainEvent>().ConfigureAwait(false)).DeleteManyAsync(deleteFilter).ConfigureAwait(false);
        }
        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);
        }
Esempio n. 10
0
        public Task <IEnumerable <Product> > GetProductsByPriceAsync(double min, double max, CancellationToken cancellationToken = default(CancellationToken))
        {
            var filterBuilder = new FilterDefinitionBuilder <Product>();
            var filter        = filterBuilder.And(
                filterBuilder.Gte(p => p.Price, min),
                filterBuilder.Lte(p => p.Price, max));

            return(products.FindAsync(filter, cancellationToken));
        }
Esempio n. 11
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();
        }
        /// <summary>
        /// Count the past deadline incidents
        /// </summary>
        /// <returns></returns>
        public int CountPastDeadlineIncidents(int userId, bool adminRights)
        {
            //Select collection
            var collection = ConfigDB.GetDatabase().GetCollection <IncidentModel>("Incidents");
            //Count documents (select)
            DateTime dateTime = DateTime.Now;
            var      filter1  = Builder.Lte(x => x.DateDeadline, dateTime) & Builder.Eq(x => x.Status, "open");
            var      filter2  = Builder.Lte(x => x.DateDeadline, dateTime) & Builder.Eq(x => x.Status, "open") & Builder.Eq(x => x.UserId, userId);
            double   count;

            if (adminRights)
            {
                count = collection.CountDocuments(filter1);
            }
            else
            {
                count = collection.CountDocuments(filter2);
            }
            return(Convert.ToInt32(count));
        }
Esempio n. 13
0
        public static IList <BsonDocument> GetDataEngineEventsForLineRange(int workerId, string file, string threadId, int startLine, int endLine, IMongoCollection <BsonDocument> collection)
        {
            var filter = Query.And(Query.Eq("worker", workerId),
                                   Query.Eq("tid", threadId),
                                   Query.Eq("file", file),
                                   Query.Gte("line", startLine),
                                   Query.Lte("line", endLine));

            var sort = Builders <BsonDocument> .Sort.Ascending("line");

            return(collection.Find(filter).Sort(sort).ToList());
        }
Esempio n. 14
0
        public FilterDefinition <IUser> ConcatenateFilter(List <SearchFilter> filters, FilterDefinitionBuilder <IUser> builder, FilterDefinition <IUser> filter, int i)
        {
            if (filters[i] is SearchFilter)
            {
                switch (filters[i].FieldName)
                {
                case "_id":
                    filter = filter & builder.Ne("_id", ((ValueSearchFilter <string>)filters[i]).Value);
                    break;

                case "UserType":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <string>)filters[i]).Value);
                    break;

                case "Gender":
                    if (((ValueSearchFilter <int>)filters[i]).Value != 2)
                    {
                        filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <int>)filters[i]).Value);
                    }
                    break;

                case "Location":
                    break;

                case "Expertise":
                    //ExpertiseEntityService expertiseService = new ExpertiseEntityService();
                    //IExpertise expertiseVal = await expertiseService.GetExpertiseById(((ValueSearchFilter<string>)filters[i]).Value);
                    //expertiseVal.ExpertiseName
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <string>)filters[i]).Value);
                    break;

                case "Reputation":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <int>)filters[i]).Value);
                    break;

                case "Showers":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <bool>)filters[i]).Value);
                    break;

                case "ParkingLot":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <bool>)filters[i]).Value);
                    break;
                }
            }
            else
            {
                filter = filter & builder.Lte(filters[i].FieldName, ((RangeSearchFilter)filters[i]).ToValue) &
                         builder.Gt(filters[i].FieldName, ((RangeSearchFilter)filters[i]).FromValue);
            }

            return(filter);
        }
Esempio n. 15
0
        public static string GetBsonDocumentsLte(string tenantid, string pointid, long endTimestamp)
        {
            //创建约束生成器
            FilterDefinitionBuilder <BsonDocument> builderFilter = Builders <BsonDocument> .Filter;
            //约束条件
            //FilterDefinition<BsonDocument> filter = builderFilter.Eq("name", "jack36");
            FilterDefinition <BsonDocument> filter = builderFilter.Eq("pointid", $"{pointid}") & builderFilter.Eq("tenantid", $"{pointid}");

            filter &= builderFilter.Lte("timestampclient", endTimestamp);
            //获取数据
            var tenantResult = _context.HistoryPointDatasBson($"{tenantid}.datas").Find <BsonDocument>(filter).Sort(Builders <BsonDocument> .Sort.Ascending("timestampclient")).Skip(0).Limit(2000);

            return(tenantResult.ToList().ToJson());
        }
Esempio n. 16
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));
        }
Esempio n. 17
0
        public Puzzle GetOneRandomly(List <int> excludedIds, string variant, int?userId, double nearRating = 1500)
        {
            FilterDefinitionBuilder <Puzzle> filterBuilder = Builders <Puzzle> .Filter;
            FilterDefinition <Puzzle>        filter        = filterBuilder.Nin("_id", excludedIds) & filterBuilder.Eq("inReview", false)
                                                             & filterBuilder.Eq("approved", true);

            if (variant != "Mixed")
            {
                filter &= filterBuilder.Eq("variant", variant);
            }
            if (userId.HasValue)
            {
                filter &= filterBuilder.Ne("author", userId.Value) & filterBuilder.Nin("reviewers", new int[] { userId.Value });
            }
            FilterDefinition <Puzzle> lteFilter = filter;
            FilterDefinition <Puzzle> gtFilter  = filter;
            bool higherRated = RandomBoolean();

            gtFilter  &= filterBuilder.Gt("rating.value", nearRating);
            lteFilter &= filterBuilder.Lte("rating.value", nearRating);
            var foundGt  = puzzleCollection.Find(gtFilter);
            var foundLte = puzzleCollection.Find(lteFilter);

            if (foundGt == null && foundLte == null)
            {
                return(null);
            }
            SortDefinitionBuilder <Puzzle> sortBuilder = Builders <Puzzle> .Sort;

            foundGt  = foundGt.Sort(sortBuilder.Ascending("rating.value")).Limit(1);
            foundLte = foundLte.Sort(sortBuilder.Descending("rating.value")).Limit(1);
            Puzzle oneGt  = foundGt.FirstOrDefault();
            Puzzle oneLte = foundLte.FirstOrDefault();

            if (oneGt == null)
            {
                return(oneLte);
            }
            else if (oneLte == null)
            {
                return(oneGt);
            }
            else
            {
                return(RandomBoolean() ? oneGt : oneLte);
            }
        }
Esempio n. 18
0
        /// <inheritdoc/>
        public async Task <CommittedAggregateEvents> FetchForAggregate(EventSourceId eventSource, ArtifactId aggregateRoot, CancellationToken cancellationToken)
        {
            try
            {
                using var session = await _streams.StartSessionAsync(cancellationToken : cancellationToken).ConfigureAwait(false);

                return(await session.WithTransactionAsync(
                           async (transaction, cancel) =>
                {
                    var version = await _aggregateRoots.FetchVersionFor(
                        transaction,
                        eventSource,
                        aggregateRoot,
                        cancel).ConfigureAwait(false);
                    if (version > AggregateRootVersion.Initial)
                    {
                        var filter = _eventFilter.Eq(_ => _.Aggregate.WasAppliedByAggregate, true)
                                     & _eventFilter.Eq(_ => _.Metadata.EventSource, eventSource.Value)
                                     & _eventFilter.Eq(_ => _.Aggregate.TypeId, aggregateRoot.Value)
                                     & _eventFilter.Lte(_ => _.Aggregate.Version, version.Value);
                        var events = await _streams.DefaultEventLog
                                     .Find(transaction, filter)
                                     .Sort(Builders <MongoDB.Events.Event> .Sort.Ascending(_ => _.Aggregate.Version))
                                     .Project(_ => _.ToCommittedAggregateEvent())
                                     .ToListAsync(cancel).ConfigureAwait(false);

                        return new CommittedAggregateEvents(
                            eventSource,
                            aggregateRoot,
                            events);
                    }
                    else
                    {
                        return new CommittedAggregateEvents(
                            eventSource,
                            aggregateRoot,
                            Array.Empty <CommittedAggregateEvent>());
                    }
                },
                           cancellationToken : cancellationToken).ConfigureAwait(false));
            }
            catch (MongoWaitQueueFullException ex)
            {
                throw new EventStoreUnavailable("Mongo wait queue is full", ex);
            }
        }
Esempio n. 19
0
        private static void CreateTimeFilter(HeatDataResultRequestDto input, FilterDefinitionBuilder <BsonDocument> builderFilter, List <FilterDefinition <BsonDocument> > filterDefinitions)
        {
            List <FilterDefinition <BsonDocument> > timeFilterDefinitions = new List <FilterDefinition <BsonDocument> >();

            input.Dates.ForEach(x =>
            {
                var date = x.ToLocalTime();
                timeFilterDefinitions.Add(builderFilter.And(new List <FilterDefinition <BsonDocument> >()
                {
                    builderFilter.Gte("updateTimeList.status1", new DateTime(date.Year, date.Month, date.Day, input.Times[0].Hour, input.Times[0].Minute, input.Times[0].Second, DateTimeKind.Local)),
                    builderFilter.Lte("updateTimeList.status1", new DateTime(date.Year, date.Month, date.Day, input.Times[1].Hour, input.Times[1].Minute, input.Times[1].Second, DateTimeKind.Local)),
                }));
            });
            if (timeFilterDefinitions.Count > 0)
            {
                filterDefinitions.Add(builderFilter.Or(timeFilterDefinitions));
            }
        }
Esempio n. 20
0
    async Task <CommittedAggregateEvents> DoFetchForAggregate(
        EventSourceId eventSource,
        ArtifactId aggregateRoot,
        Func <FilterDefinition <MongoDB.Events.Event>, FilterDefinition <MongoDB.Events.Event> > filterCallback,
        CancellationToken cancellationToken)
    {
        try
        {
            var version = await _aggregateRoots.FetchVersionFor(
                eventSource,
                aggregateRoot,
                cancellationToken).ConfigureAwait(false);

            if (version <= AggregateRootVersion.Initial)
            {
                return(new CommittedAggregateEvents(
                           eventSource,
                           aggregateRoot,
                           Array.Empty <CommittedAggregateEvent>()));
            }
            var defaultFilter = _eventFilter.Eq(_ => _.Aggregate.WasAppliedByAggregate, true)
                                & _eventFilter.EqStringOrGuid(_ => _.Metadata.EventSource, eventSource.Value)
                                & _eventFilter.Eq(_ => _.Aggregate.TypeId, aggregateRoot.Value)
                                & _eventFilter.Lte(_ => _.Aggregate.Version, version.Value);

            var filter = filterCallback(defaultFilter);

            var events = await _streams.DefaultEventLog
                         .Find(filter)
                         .Sort(Builders <MongoDB.Events.Event> .Sort.Ascending(_ => _.Aggregate.Version))
                         .ToListAsync(cancellationToken).ConfigureAwait(false);

            return(new CommittedAggregateEvents(
                       eventSource,
                       aggregateRoot,
                       events.Select(_ => _eventConverter.ToRuntimeStreamEvent(_))
                       .Select(_ => _.Event)
                       .Cast <CommittedAggregateEvent>().ToList()));
        }
        catch (Exception ex)
        {
            throw new EventStoreUnavailable("Mongo wait queue is full", ex);
        }
    }
Esempio n. 21
0
        static void Main(string[] args)
        {
            var client   = new MongoClient("mongodb+srv://ITDS_USER:[email protected]/sample_mflix?retryWrites=true&w=majority");
            var database = client.GetDatabase("sample_mflix");

            var filterBuilder = new FilterDefinitionBuilder <BsonDocument>();
            var filter        = filterBuilder.Lte("year", 1983);

            using (IAsyncCursor <BsonDocument> documents = database.GetCollection <BsonDocument>("movies").FindSync(filter))
            {
                while (documents.MoveNext())
                {
                    foreach (var doc in documents.Current)
                    {
                        Console.WriteLine(doc.ToJson());
                    }
                }
            }
        }
Esempio n. 22
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();
        }
        public static List <ProcessedLogInfo> GetAndProcessData(MongoConnectionClass db, long min = 0, long max = long.MaxValue)
        {
            FilterDefinitionBuilder <LogInfo> builder = Builders <LogInfo> .Filter;
            FilterDefinition <LogInfo>        filter  = builder.Gte("unix_timestamp", min)
                                                        & builder.Lte("unix_timestamp", max);

            IMongoCollection <LogInfo> logCollection = db.Database.GetCollection <LogInfo>("Copy_of_logs");

            try
            {
                //List<LogInfo> logList = logCollection.Find(new BsonDocument()).Limit(limit).ToList();
                List <LogInfo> logList = logCollection.Find(filter).ToList();
                return(PreprocessLogClass(logList));
            }
            catch (OutOfMemoryException)
            {
                Console.WriteLine("Can't load such big size of logs, try smaller time window");
                throw;
            }
        }
Esempio n. 24
0
        public async Task <IEnumerable <Phone> > GetPhones(int?minPrice, int?maxPrice, string name)
        {
            var builder = new FilterDefinitionBuilder <Phone>();
            var filter  = builder.Empty;

            if (!String.IsNullOrWhiteSpace(name))
            {
                filter = filter & builder.Regex("Name", new BsonRegularExpression(name));
            }
            if (minPrice.HasValue)
            {
                filter = filter & builder.Gte("Price", minPrice.Value);
            }
            if (maxPrice.HasValue)
            {
                filter = filter & builder.Lte("Price", maxPrice.Value);
            }

            return(await Phones.Find(filter).ToListAsync());
        }
Esempio n. 25
0
        public FilterDefinition <T> GetFromCompareType <T>(FilterCondition s)
        {
            FilterDefinitionBuilder <T> filter = Builders <T> .Filter;

            if (s.Value == null)
            {
                return(filter.Empty);
            }

            switch (s.CompareType)
            {
            case TableCompareType.EQ:
                return(filter.Eq(s.Key, s.Value));

            case TableCompareType.GT:
                return(filter.Gt(s.Key, s.Value));

            case TableCompareType.GTE:
                return(filter.Gte(s.Key, s.Value));

            case TableCompareType.LT:
                return(filter.Lt(s.Key, s.Value));

            case TableCompareType.LTE:
                return(filter.Lte(s.Key, s.Value));

            case TableCompareType.NE:
                return(filter.Ne(s.Key, s.Value));

            case TableCompareType.REGEX:
            {
                return(filter.Regex(s.Key, s.Value.ToString()));
            }

            case TableCompareType.TEXT:
                return(filter.Text(s.Value.ToString()));

            default:
                return(filter.Eq(s.Key, s.Value));
            }
        }
        // получаем все документы, используя критерии фальтрации
        public async Task <IEnumerable <Book> > GetProducts(int?minPrice, int?maxPrice, string name)
        {
            // строитель фильтров
            var builder = new FilterDefinitionBuilder <Book>();
            var filter  = builder.Empty; // фильтр для выборки всех документов

            // фильтр по имени
            if (!String.IsNullOrWhiteSpace(name))
            {
                filter = filter & builder.Regex("Name", new BsonRegularExpression(name));
            }
            if (minPrice.HasValue)  // фильтр по минимальной цене
            {
                filter = filter & builder.Gte("Price", minPrice.Value);
            }
            if (maxPrice.HasValue)  // фильтр по максимальной цене
            {
                filter = filter & builder.Lte("Price", maxPrice.Value);
            }
            return(await Books.Find(filter).ToListAsync());
        }
Esempio n. 27
0
        //we get all documents using falsification criteria
        public async Task <IEnumerable <Product> > GetProducts(int?minPrice, int?maxPrice, string name)
        {
            // filter builder
            var builder = new FilterDefinitionBuilder <Product>();
            var filter  = builder.Empty; //filter for selection of all documents

            // filter by name
            if (!String.IsNullOrWhiteSpace(name))
            {
                filter = filter & builder.Regex("Name", new BsonRegularExpression(name));
            }
            if (minPrice.HasValue)  //filter at the lowest price
            {
                filter = filter & builder.Gte("Price", minPrice.Value);
            }
            if (maxPrice.HasValue)  //filter at maximum price
            {
                filter = filter & builder.Lte("Price", maxPrice.Value);
            }

            return(await Products.Find(filter).ToListAsync());
        }
        public List <Place> Get(PlaceFilterInfo placeFilter)
        {
            var queryBuilder = new FilterDefinitionBuilder <Place>();
            var filters      = new List <FilterDefinition <Place> >();

            if (placeFilter.Name != null)
            {
                filters.Add(queryBuilder.Eq("Name", placeFilter.Name));
            }
            if (placeFilter.Address != null)
            {
                filters.Add(queryBuilder.Eq("Address", placeFilter.Address));
            }
            if (placeFilter.Description != null)
            {
                filters.Add(queryBuilder.Eq("Description", placeFilter.Description));
            }
            if (placeFilter.PriceMin != null)
            {
                filters.Add(queryBuilder.Gte("Price", placeFilter.PriceMin));
            }
            if (placeFilter.PriceMax != null)
            {
                filters.Add(queryBuilder.Lte("Price", placeFilter.PriceMax));
            }
            if (placeFilter.OwnerId != null)
            {
                filters.Add(queryBuilder.Eq("OwnerId", placeFilter.OwnerId));
            }
            if (filters.Count != 0)
            {
                return(places.Find(queryBuilder.And(filters)).ToList());
            }
            else
            {
                return(places.Find(x => true).ToList());
            }
        }
Esempio n. 29
0
        ///<inheritdoc/>
        public async Task <IrpfTax> GetActive(DateTime?date, CancellationToken cancellationToken = default)
        {
            FilterDefinitionBuilder <IrpfTax> builder = Builders <IrpfTax> .Filter;
            FilterDefinition <IrpfTax>        filter;

            if (date.HasValue)
            {
                filter =
                    builder.Lte(nameof(IrpfTax.DateStart).ToCamelCase(), date.Value)
                    & (
                        builder.Gte(nameof(IrpfTax.DateEnd).ToCamelCase(), date.Value)
                        | builder.Eq(nameof(IrpfTax.DateEnd).ToCamelCase(), BsonNull.Value)
                        );
            }
            else
            {
                filter = builder.Eq(nameof(IrpfTax.Inactive).ToCamelCase(), false);
            }

            IrpfTax result = await Collection.Find(filter).FirstOrDefaultAsync(cancellationToken);

            return(result);
        }
Esempio n. 30
0
        public override FilterDefinition <MongoContentEntity> Visit(BinaryOperatorNode nodeIn)
        {
            if (nodeIn.OperatorKind == BinaryOperatorKind.And)
            {
                return(Filter.And(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.Or)
            {
                return(Filter.Or(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual)
            {
                return(Filter.Ne(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.Equal)
            {
                return(Filter.Eq(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.LessThan)
            {
                return(Filter.Lt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.LessThanOrEqual)
            {
                return(Filter.Lte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThan)
            {
                return(Filter.Gt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual)
            {
                return(Filter.Gte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }

            throw new NotSupportedException();
        }
 private List<FilterDefinition<Flight>> CreateClauses(SearchCriteriaModel criteriaModel, FilterDefinitionBuilder<Flight> filterBuilder)
 {
     var clauses = new List<FilterDefinition<Flight>>();
     if (criteriaModel.FromDate != null)
     {
         var fromDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.FromDate), DateTimeKind.Utc);
         var clause = filterBuilder.Gte(f => f.FlightDate, fromDate);
         clauses.Add(clause);
     }
     if (criteriaModel.ToDate != null)
     {
         var toDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.ToDate), DateTimeKind.Utc);
         var clause = filterBuilder.Lte(f => f.FlightDate, toDate);
         clauses.Add(clause);
     }
     if (criteriaModel.AirlineId != null)
     {
         var clause = filterBuilder.Eq(f => f.AirlineId, criteriaModel.AirlineId.Value);
         clauses.Add(clause);
     }
     if (criteriaModel.OriginId != null)
     {
         var clause = filterBuilder.Eq(f => f.OriginAirportId, criteriaModel.OriginId.Value);
         clauses.Add(clause);
     }
     if (criteriaModel.DestinationId != null)
     {
         var clause = filterBuilder.Eq(f => f.DestinationAirportId, criteriaModel.DestinationId.Value);
         clauses.Add(clause);
     }
     return clauses;
 }