Ejemplo n.º 1
0
 private static FilterDefinition <BsonDocument> FilterByIsJobStartOrEndEvent(string jobType)
 {
     return(Query.And(FilterByClass(BackgrounderConstants.BackgrounderJobRunnerClass),
                      Query.Or(FilterBySeverity("INFO"),
                               FilterBySeverity("ERROR")),
                      Query.Or(FilterByIsJobStartEvent(jobType),
                               FilterByIsJobEndEvent(jobType))));
 }
Ejemplo n.º 2
0
 public override FilterDefinition <T> Visit(LogicalFilter <ClrValue> nodeIn, None args)
 {
     if (nodeIn.Type == LogicalFilterType.And)
     {
         return(Filter.And(nodeIn.Filters.Select(x => x.Accept(this, args))));
     }
     else
     {
         return(Filter.Or(nodeIn.Filters.Select(x => x.Accept(this, args))));
     }
 }
Ejemplo n.º 3
0
 public override FilterDefinition <T> Visit(FilterJunction nodeIn)
 {
     if (nodeIn.JunctionType == FilterJunctionType.And)
     {
         return(Filter.And(nodeIn.Operands.Select(x => x.Accept(this))));
     }
     else
     {
         return(Filter.Or(nodeIn.Operands.Select(x => x.Accept(this))));
     }
 }
Ejemplo n.º 4
0
        public static FilterDefinition <TDocument> NotDeactivated <TDocument, TItem>(FilterDefinitionBuilder <TDocument> builder, Expression <Func <TDocument, IEnumerable <TItem> > > acessor, DateTime?dateTime = null) where TItem : IActivationAware
        {
            var twoBuilder = new FilterDefinitionBuilder <TItem>();

            if (!dateTime.HasValue)
            {
                dateTime = DateTime.UtcNow;
            }
            return(builder.Or
                   (
                       builder.Not
                       (
                           builder.ElemMatch
                           (
                               acessor,
                               twoBuilder.Exists
                               (
                                   t => t.DeactivationDate
                               )
                           )
                       ),
                       builder.ElemMatch
                       (
                           acessor,
                           twoBuilder.Gt
                           (
                               t => t.DeactivationDate,
                               dateTime.Value
                           )
                       )
                   ));
        }
Ejemplo n.º 5
0
        public static IList <ResourceManagerAction> GetActions(int workerId, int pid, IMongoCollection <BsonDocument> collection)
        {
            IList <ResourceManagerAction> actions = new List <ResourceManagerAction>();

            string processName = GetProcessName(collection);

            var filter = Query.And(
                FilterMessagesByWorkerAndPid(workerId, pid),
                Query.Or(
                    Query.Regex("v", new BsonRegularExpression(ResourceManagerAction.CpuUsageExceededRegex)),
                    Query.Regex("v", new BsonRegularExpression(ResourceManagerAction.ProcessMemoryUsageExceededRegex)),
                    Query.Regex("v", new BsonRegularExpression(ResourceManagerAction.TotalMemoryUsageExceededRegex))
                    )
                );

            var memoryInfoDocuments = collection.Find(filter).ToList();

            foreach (var document in memoryInfoDocuments)
            {
                try
                {
                    ResourceManagerAction memoryInfo = new ResourceManagerAction(document, processName);
                    actions.Add(memoryInfo);
                }
                catch (Exception ex)
                {
                    Log.Error("Unable to parse memoryInfo from " + document, ex);
                }
            }

            return(actions);
        }
Ejemplo n.º 6
0
        private static void CreateOrderTypeFilter(HeatDataResultRequestDto input, FilterDefinitionBuilder <BsonDocument> builderFilter, List <FilterDefinition <BsonDocument> > filterDefinitions)
        {
            List <FilterDefinition <BsonDocument> > orderTypeFilterDefinitions = new List <FilterDefinition <BsonDocument> >();

            input.OrderType.ForEach(x =>
            {
                switch (x)
                {
                case InputOrderType.TotalOrder:
                default:
                    break;

                case InputOrderType.ImmediateOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.Eq("orderType", OrderType.Immediate));
                    break;

                case InputOrderType.BookingOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.And(builderFilter.Eq("orderType", OrderType.Booking), builderFilter.Eq("orderType2", BookingOrderType.Normal)));
                    break;

                case InputOrderType.PickupOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.Eq("orderType2", BookingOrderType.Pickup));
                    break;

                case InputOrderType.DropoffOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.Eq("orderType2", BookingOrderType.Dropoff));
                    break;
                }
            });
            if (orderTypeFilterDefinitions.Count > 0)
            {
                filterDefinitions.Add(builderFilter.Or(orderTypeFilterDefinitions));
            }
        }
        public async Task <LockResponse> RetrieveLatestInCategoryAsync(
            IEnumerable <string> categoryNames,
            bool isReadonly)
        {
            var fb = new FilterDefinitionBuilder <Lockable>();

            var filter = fb.And(
                fb.All(l => l.Categories, categoryNames),
                fb.Or(
                    $"{{ \"Locks.IsShared\": {isReadonly.ToString().ToLower()} }}",
                    "{ Locks: { $size: 0 } }"));

            var lockable = await collection
                           .Find(filter)
                           .FirstOrDefaultAsync();

            if (lockable == null)
            {
                return(null);
            }

            var @lock = new Lock
            {
                IsShared     = isReadonly,
                MaxLeaseDate = DateTime.Now.AddHours(1),
                OwnerToken   = null,
                UnlockedAt   = default(DateTime)
            };

            var response = await LockAsync(lockable, @lock);

            return(response);
        }
Ejemplo n.º 8
0
        public long CountByPlayerId(int id)
        {
            FilterDefinitionBuilder <Game> filterBuilder = Builders <Game> .Filter;
            FilterDefinition <Game>        whiteEq       = filterBuilder.Eq("white.userId", id);
            FilterDefinition <Game>        blackEq       = filterBuilder.Eq("black.userId", id);

            return(gameCollection.Count(filterBuilder.Or(whiteEq, blackEq)));
        }
Ejemplo n.º 9
0
        public static IAsyncCursor <BsonDocument> GetErrorEventsCursor(IMongoCollection <BsonDocument> collection)
        {
            var filter = Query.Or(
                Query.Eq("sev", "ERROR"),
                Query.Eq("sev", "FATAL"));

            return(collection.Find(filter).ToCursor());
        }
        public async Task <long> CountByPlayerIdAsync(int id)
        {
            FilterDefinitionBuilder <Game> filterBuilder = Builders <Game> .Filter;
            FilterDefinition <Game>        whiteEq       = filterBuilder.Eq("white.userId", id);
            FilterDefinition <Game>        blackEq       = filterBuilder.Eq("black.userId", id);

            return(await gameCollection.CountAsync(filterBuilder.Or(whiteEq, blackEq)));
        }
Ejemplo n.º 11
0
        public void Or()
        {
            var fb     = new FilterDefinitionBuilder <BasicDocument>();
            var result = Find(fb.Or(fb.Eq(x => x.Id, _item.Id), fb.Eq(x => x.Id, _item2.Id)));

            result.Count.Should().Be(2);
            result.Should().Contain(x => x.Id == _item.Id);
            result.Should().Contain(x => x.Id == _item2.Id);
        }
Ejemplo n.º 12
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());
        }
        public async Task <List <Game> > GetByPlayerIdAsync(int id, int skip, int limit)
        {
            FilterDefinitionBuilder <Game> filterBuilder = Builders <Game> .Filter;
            FilterDefinition <Game>        whiteEq       = filterBuilder.Eq("white.userId", id);
            FilterDefinition <Game>        blackEq       = filterBuilder.Eq("black.userId", id);
            SortDefinition <Game>          sortDef       = Builders <Game> .Sort.Descending("startedUtc");

            return(await gameCollection.Find(filterBuilder.Or(whiteEq, blackEq)).Sort(sortDef).Skip(skip).Limit(limit).ToListAsync());
        }
Ejemplo n.º 14
0
        public async Task <FilterResult> Filter(FilterDescriptor filterDescriptor)
        {
            FilterDefinitionBuilder <BsonDocument> filterBuilder = Builders <BsonDocument> .Filter;

            IFindFluent <BsonDocument, BsonDocument> findFluent = null;

            if (filterDescriptor.Filters.Any())
            {
                FilterDefinition <BsonDocument> filterDefinition = null;
                switch (filterDescriptor.Logic)
                {
                case FilteringLogic.All:
                    filterDefinition = filterBuilder.And(filterDescriptor.Filters.Select(filter => ParseFilter(filter)));
                    break;

                case FilteringLogic.Any:
                    filterDefinition = filterBuilder.Or(filterDescriptor.Filters.Select(filter => ParseFilter(filter)));
                    break;

                default:
                    throw new NotSupportedException();
                }

                findFluent = _collection.Find(filterDefinition);
            }
            else
            {
                findFluent = _collection.Find(_ => true);
            }

            if (filterDescriptor.Limit.HasValue)
            {
                findFluent.Limit(filterDescriptor.Limit.Value);
            }

            if (filterDescriptor.Offset.HasValue)
            {
                findFluent.Skip(filterDescriptor.Offset.Value);
            }

            try
            {
                List <BsonDocument> result = await findFluent.ToListAsync();

                long total = await findFluent.CountAsync();

                return(new FilterResult(
                           result.Select(item => (DeviceDescriptor)_serializer.DeserializeObject(item.ToJson(jsonWriterSettings), typeof(DeviceDescriptor))).ToArray(),
                           total));
            }
            catch (Exception ex)
            {
                throw new DeviceRepositoryException("Cannot get devices from database.", ex);
            }
        }
Ejemplo n.º 15
0
        public PagedList <dynamic> GetSharedNodes(Guid userId, int pageNumber = 1, int pageSize = 20, bool isPublicOnly = false)
        {
            var filter = _filterBase & _builder.Eq("OwnedBy", userId) & _builder.Or(
                _builder.Eq("AccessPermissions.IsPublic", true),
                _builder.Not(_builder.Size("AccessPermissions.Users", 0)),
                _builder.Not(_builder.Size("AccessPermissions.Groups", 0))
                );

            if (isPublicOnly)
            {
                filter = filter & _builder.Eq("AccessPermissions.IsPublic", true);
            }

            var nodes = _nodes.Aggregate()
                        .Lookup <BsonDocument, BsonDocument>(nameof(AccessPermissions), "_id", "_id", nameof(AccessPermissions))
                        .Unwind <dynamic>(nameof(AccessPermissions))
                        .Match(filter.Render(_nodes.DocumentSerializer, _nodes.Settings.SerializerRegistry));

            return(PagedList(nodes, pageNumber, pageSize));
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
0
 public static FilterDefinition <TDocument> NotDeactivated <TDocument>(FilterDefinitionBuilder <TDocument> builder, DateTime?dateTime = null) where TDocument : IActivationAware
 {
     if (!dateTime.HasValue)
     {
         dateTime = DateTime.UtcNow;
     }
     return(builder.Or(
                builder.Not(
                    builder.Exists(doc => doc.DeactivationDate)
                    ),
                builder.Gt(doc => doc.DeactivationDate, dateTime.Value)
                ));
 }
Ejemplo n.º 18
0
        public async Task FindUsingForEachAsync(IMongoCollection <ClubMember> collection)
        {
            Console.WriteLine("Starting FindUsingForEachAsync");
            FilterDefinitionBuilder <ClubMember> builder = Builders <ClubMember> .Filter;
            FilterDefinition <ClubMember>        filter  = builder.Or(
                Builders <ClubMember> .Filter.Eq("Lastname", "Rees"),
                Builders <ClubMember> .Filter.Eq("Lastname", "Jones"));
            await collection.Find(filter)
            //the async read of each item is awaited in sequence
            //the 'action' delegate runs on a threadpool thread
            .ForEachAsync(c => DoSomeAction(c));

            Console.WriteLine(" Finished FindUsingForEachAsync");
        }
Ejemplo n.º 19
0
        public List <BsonDocument> GetRoleWithFilter(string searchKey)
        {
            var filter = Builder.Or(
                Builder.Where(x => x.RoleCode.ToLower().Contains(searchKey)),
                Builder.Where(x => x.RoleName.ToLower().Contains(searchKey))
                );

            var data = _Role.Aggregate()
                       .Match(filter)
                       .Lookup("Permission", "PermissionId", "_id", "Permission")
                       .ToList();

            return(data);
        }
Ejemplo n.º 20
0
        public static FilterDefinition <MongoAssetEntity> BuildFilter(this ClrQuery query, Guid appId, Guid?parentId)
        {
            var filters = new List <FilterDefinition <MongoAssetEntity> >
            {
                Filter.Eq(x => x.IndexedAppId, appId),
                Filter.Eq(x => x.IsDeleted, false)
            };

            if (parentId.HasValue)
            {
                if (parentId == Guid.Empty)
                {
                    filters.Add(
                        Filter.Or(
                            Filter.Exists(x => x.ParentId, false),
                            Filter.Eq(x => x.ParentId, Guid.Empty)));
                }
                else
                {
                    filters.Add(Filter.Eq(x => x.ParentId, parentId.Value));
                }
            }

            var(filter, last) = query.BuildFilter <MongoAssetEntity>(false);

            if (filter != null)
            {
                if (last)
                {
                    filters.Add(filter);
                }
                else
                {
                    filters.Insert(0, filter);
                }
            }

            if (filters.Count > 1)
            {
                return(Filter.And(filters));
            }
            else if (filters.Count == 1)
            {
                return(filters[0]);
            }
            else
            {
                return(new BsonDocument());
            }
        }
Ejemplo n.º 21
0
 public static FilterDefinition <TDocument> NotDeactivated <TDocument, TItem>(FilterDefinitionBuilder <TDocument> builder, Expression <Func <TDocument, TItem> > acessor, DateTime?dateTime = null) where TItem : IActivationAware
 {
     if (!dateTime.HasValue)
     {
         dateTime = DateTime.UtcNow;
     }
     return(builder.Or
            (
                builder.Not
                (
                    builder.Exists
                    (
                        Expression.Lambda <Func <TDocument, object> >
                        (
                            Expression.Convert
                            (
                                Expression.Property
                                (
                                    acessor.Body,
                                    nameof(IActivationAware.DeactivationDate)
                                ),
                                typeof(object)
                            ),
                            acessor.Parameters
                        )
                    )
                ),
                builder.Gt
                (
                    Expression.Lambda <Func <TDocument, DateTime> >
                    (
                        Expression.Convert
                        (
                            Expression.Property
                            (
                                acessor.Body,
                                nameof(IActivationAware.DeactivationDate)
                            ),
                            typeof(DateTime)
                        ),
                        acessor.Parameters
                    ),
                    dateTime.Value
                )
            ));
 }
Ejemplo n.º 22
0
        public static FilterDefinition <MongoAssetEntity> BuildFilter(this ClrQuery query, DomainId appId, DomainId?parentId)
        {
            var filters = new List <FilterDefinition <MongoAssetEntity> >
            {
                Filter.Exists(x => x.LastModified),
                Filter.Exists(x => x.Id),
                Filter.Eq(x => x.IndexedAppId, appId)
            };

            if (!query.HasFilterField("IsDeleted"))
            {
                filters.Add(Filter.Eq(x => x.IsDeleted, false));
            }

            if (parentId != null)
            {
                if (parentId == DomainId.Empty)
                {
                    filters.Add(
                        Filter.Or(
                            Filter.Exists(x => x.ParentId, false),
                            Filter.Eq(x => x.ParentId, DomainId.Empty)));
                }
                else
                {
                    filters.Add(Filter.Eq(x => x.ParentId, parentId.Value));
                }
            }

            var(filter, last) = query.BuildFilter <MongoAssetEntity>(false);

            if (filter != null)
            {
                if (last)
                {
                    filters.Add(filter);
                }
                else
                {
                    filters.Insert(0, filter);
                }
            }

            return(Filter.And(filters));
        }
Ejemplo n.º 23
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));
            }
        }
Ejemplo n.º 24
0
        private static void CreateOrderStatusFilter(HeatDataResultRequestDto input, FilterDefinitionBuilder <BsonDocument> builderFilter, List <FilterDefinition <BsonDocument> > filterDefinitions)
        {
            List <FilterDefinition <BsonDocument> > orderStatusFilterDefinitions = new List <FilterDefinition <BsonDocument> >();

            input.OrderStatus.ForEach(x =>
            {
                switch (x)
                {
                case InputOrderStatus.TotalStatus:
                default:
                    break;

                case InputOrderStatus.CancelPlaceOrder:
                    orderStatusFilterDefinitions.Add(builderFilter.And(builderFilter.In("orderStatus", new List <int>()
                    {
                        30, 40, 45
                    }), builderFilter.Exists("updateTimeList.status5", false)));
                    break;

                case InputOrderStatus.CancelAcceptOrder:
                    orderStatusFilterDefinitions.Add(builderFilter.And(builderFilter.In("orderStatus", new List <int>()
                    {
                        30, 40, 45
                    }), builderFilter.Exists("updateTimeList.status5", true)));
                    break;

                case InputOrderStatus.CompletedOrder:
                    orderStatusFilterDefinitions.Add(builderFilter.Exists("updateTimeList.status20", true));
                    break;

                case InputOrderStatus.ToBeCompletedOrder:
                    orderStatusFilterDefinitions.Add(builderFilter.And(builderFilter.Exists("updateTimeList.status20", false), builderFilter.Not(builderFilter.In("orderStatus", new List <int>()
                    {
                        30, 40, 45
                    }))));
                    break;
                }
            });
            if (orderStatusFilterDefinitions.Count > 0)
            {
                filterDefinitions.Add(builderFilter.Or(orderStatusFilterDefinitions));
            }
        }
Ejemplo n.º 25
0
        public List <BsonDocument> GetUserWithFilter(string searchKey)
        {
            AggregateUnwindOptions <Role> unwindOptions = new AggregateUnwindOptions <Role>()
            {
                PreserveNullAndEmptyArrays = true
            };
            var filter = Builder.Or(
                Builder.Where(x => x.UserName.ToLower().Contains(searchKey)),
                Builder.Where(x => x.Name.ToLower().Contains(searchKey)),
                Builder.Where(x => x.Email.ToLower().Contains(searchKey)),
                Builder.Where(x => x.Address.ToLower().Contains(searchKey))
                );

            var data = _Users.Aggregate()
                       .Match(filter)
                       .Lookup("Role", "RoleId", "_id", "Role")
                       .Unwind("Role", unwindOptions)
                       .Lookup("Permission", "Role.PermissionId", "_id", "Role.Permission")
                       .ToList();

            return(data);
        }
Ejemplo n.º 26
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();
        }
Ejemplo n.º 27
0
        public async Task FindUsingFilterDefinitionBuilder2Async(IMongoCollection <ClubMember> collection)
        {
            Console.WriteLine("Starting FindUsingFilterDefinitionBuilder2Async");
            FilterDefinitionBuilder <ClubMember> builder = Builders <ClubMember> .Filter;
            //An 'Or' filter. Selects where Lastname ==Rees Or Lastname==Jones
            FilterDefinition <ClubMember> filter = builder.Or(
                Builders <ClubMember> .Filter.Eq("Lastname", "Rees"),
                Builders <ClubMember> .Filter.Eq("Lastname", "Jones"));
            IEnumerable <ClubMember> jonesReesList =
                await
                collection.Find(filter)
                .SortBy(c => c.Lastname)
                .ThenBy(c => c.Forename)
                .ThenByDescending(c => c.Age)
                .ToListAsync();

            Console.WriteLine("Finished FindUsingFilterDefinitionBuilder2Async");
            Console.WriteLine("Members named Jones or Rees ...");
            foreach (ClubMember clubMember in jonesReesList)
            {
                ConsoleHelper.PrintClubMemberToConsole(clubMember);
            }
            Console.WriteLine("...........");
        }
Ejemplo n.º 28
0
        private async Task <bool> TryUpdate(TimeSpan lifetime, Guid acquireId)
        {
            try
            {
                var update = new UpdateDefinitionBuilder <LockAcquire <T> >()
                             .Set(x => x.Acquired, true)
                             .Set(x => x.ExpiresIn, DateTime.UtcNow + lifetime)
                             .Set(x => x.AcquireId, acquireId)
                             .SetOnInsert(x => x.Id, _id);

                FilterDefinition <LockAcquire <T> > filter = _builder.And(
                    _builder.Eq(x => x.Id, _id),
                    _builder.Or(
                        _builder.Eq(x => x.Acquired, false),
                        _builder.Lte(x => x.ExpiresIn, DateTime.UtcNow)
                        )
                    );

                var updateResult = await _locks.UpdateOneAsync(
                    filter : filter, // x => x.Id == _id && (!x.Acquired || x.ExpiresIn <= DateTime.UtcNow),
                    update : update, options : new UpdateOptions {
                    IsUpsert = true
                });

                return(updateResult.IsAcknowledged);
            }
            catch (MongoWriteException ex) // E11000
            {
                if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
                {
                    return(false);
                }

                throw;
            }
        }
Ejemplo n.º 29
0
 public object Or(params object[] filters)
 {
     return(InternalBuilder.Or(AsMongoFilters(filters)));
 }
Ejemplo 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.Left is SingleValueFunctionCallNode functionNode)
            {
                var regexFilter = Visit(functionNode);

                var value = BuildValue(nodeIn.Right);

                if (value is bool booleanRight)
                {
                    if ((nodeIn.OperatorKind == BinaryOperatorKind.Equal && !booleanRight) ||
                        (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual && booleanRight))
                    {
                        regexFilter = Filter.Not(regexFilter);
                    }

                    return(regexFilter);
                }
            }
            else
            {
                if (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual)
                {
                    var field = BuildFieldDefinition(nodeIn.Left);

                    return(Filter.Or(
                               Filter.Not(Filter.Exists(field)),
                               Filter.Ne(field, 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();
        }