コード例 #1
0
        public List <T> Assert <T>(IMongoCollection <T> collection, Expression <Func <T, bool> > filter, int expectedCount, BsonDocument expectedFilter)
        {
            var serializer     = BsonSerializer.SerializerRegistry.GetSerializer <T>();
            var filterDocument = PredicateTranslator.Translate(filter, serializer, BsonSerializer.SerializerRegistry);

            var list = collection.FindSync(filterDocument).ToList();

            filterDocument.Should().Be(expectedFilter);
            list.Count.Should().Be(expectedCount);
            return(list);
        }
コード例 #2
0
        public IEnumerable <Certificate> GetAll()
        {
            var cursor = certificates.FindSync(x => true);
            var certs  = new List <Certificate>();

            while (cursor.MoveNext())
            {
                certs.AddRange(cursor.Current);
            }
            return(certs);
        }
コード例 #3
0
        private static void CreateCompositeKey(IMongoCollection <BsonDocument> jobGraph, Type type)
        {
            var documents = jobGraph.FindSync(new BsonDocument("_t", type.Name))
                            .ToEnumerable();

            foreach (var document in documents)
            {
                document["Key"] = $"{document["Key"].AsString}:{document["Value"].AsString}";
                jobGraph.ReplaceOne(new BsonDocument("_id", document["_id"]), document);
            }
        }
コード例 #4
0
 public User VerifyUserWithToken(string _id, string token)
 {
     try
     {
         User user = _users.FindSync <User>(user => user.Id == _id && user.Tokens.Contains <string>(token)).FirstOrDefault();
         return(user);
     } catch (Exception ex)
     {
         Console.WriteLine($"{ex.GetType()} :: {ex.Message}");
         return(null);
     }
 }
コード例 #5
0
        public List <StationMonthly> getMonthlySummaryFromDB()
        {
            //get the collection with summary names
            IMongoCollection <BsonDocument> names = db.GetCollection <BsonDocument>("summaryCollectionNames");
            var name = names.Find(new BsonDocument()).ToList();
            IMongoCollection <StationMonthly> collection = db.GetCollection <StationMonthly>("monthlyStationSummary_2018_9_14_7_15_28");

            var filter = FilterDefinition <StationMonthly> .Empty;
            var vms    = collection.FindSync(filter).ToList();

            return(vms);
        }
コード例 #6
0
ファイル: FindTest.cs プロジェクト: snoopy83101/Uzor001
 protected override List <BsonDocument> ExecuteAndGetResult(IMongoCollection <BsonDocument> collection, bool async)
 {
     if (async)
     {
         var cursor = collection.FindAsync(_filter, _options).GetAwaiter().GetResult();
         return(cursor.ToListAsync().GetAwaiter().GetResult());
     }
     else
     {
         return(collection.FindSync(_filter, _options).ToList());
     }
 }
コード例 #7
0
ファイル: FindTest.cs プロジェクト: RavenZZ/MDRelation
 protected override void Execute(IMongoCollection<BsonDocument> collection, bool async)
 {
     if (async)
     {
         var cursor = collection.FindAsync(_filter, _options).GetAwaiter().GetResult();
         cursor.ToListAsync().GetAwaiter().GetResult();
     }
     else
     {
         collection.FindSync(_filter, _options).ToList();
     }
 }
コード例 #8
0
 protected override void Execute(IMongoCollection <BsonDocument> collection, bool async)
 {
     if (async)
     {
         var cursor = collection.FindAsync(_filter, _options).GetAwaiter().GetResult();
         cursor.ToListAsync().GetAwaiter().GetResult();
     }
     else
     {
         collection.FindSync(_filter, _options).ToList();
     }
 }
コード例 #9
0
        public static ServiceResult <IEnumerable <Drink> > GetByCondition(this IMongoCollection <Drink> db, Drink drink)
        {
            var result = new ServiceResult <IEnumerable <Drink> >();

            try {
                result.Data = db.FindSync(GetByDrink(drink)).ToList();
            }
            catch (Exception ex) {
                result.AddError(ex.Message);
            }
            return(result);
        }
コード例 #10
0
        public async Task <List <TEntity> > GetAll()
        {
            try{
                FilterDefinition <TEntity> filter = FilterDefinition <TEntity> .Empty;
                var results = await _dbCollection.FindSync(filter).ToListAsync();

                return(results);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #11
0
        /// <summary>
        /// Loads all the items from the database into the list.
        /// </summary>
        /// <param name="itemsRead">The items retrieved from the database.</param>
        private void LoadAllItemsFromDatabase(IMongoCollection <T> itemsRead)
        {
            LoadedItems.Clear();

            using (IAsyncCursor <T> cursor = itemsRead.FindSync(Filter))
            {
                List <T> itemList = cursor.ToList();
                foreach (T item in itemList)
                {
                    LoadedItems.Add(item);
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Loads all the items from the database into the list.
        /// </summary>
        /// <param name="itemsRead">The items retrieved from the database.</param>
        private void LoadAllItemsFromDatabase(IMongoCollection <T> itemsRead)
        {
            LoadedItems.Clear();

            using (var cursor = itemsRead.FindSync(Filter))
            {
                var countryList = cursor.ToList();
                foreach (var country in countryList)
                {
                    LoadedItems.Add(country);
                }
            }
        }
コード例 #13
0
            public async Task ApplyConvention_CtorWithDefault_SerializeSuccessful()
            {
                // Arrange
                IMongoCollection <C> collection = _context.GetCollection <C>();

                // Act
                await collection.InsertOneAsync(new C("a", "b"));

                // Assert
                C result = await collection.FindSync(FilterDefinition <C> .Empty).FirstAsync();

                result.MatchSnapshot();
            }
コード例 #14
0
            public async Task ApplyConvention_SerializeSuccessful()
            {
                // Arrange
                IMongoCollection <IA> collection = _context.CreateCollection <IA>();

                // Act
                await collection.InsertOneAsync(new A("a"));

                // Assert
                A result = await collection.FindSync(FilterDefinition <IA> .Empty).FirstAsync() as A;

                result.MatchSnapshot();
            }
コード例 #15
0
ファイル: Legend.cs プロジェクト: legend-plus/LegendSharp
        public BsonDocument GetUserData(String id)
        {
            List <BsonDocument> list = userCollection.FindSync(new BsonDocument("user", id)).ToList();

            if (list.Count > 0)
            {
                return(list[0]);
            }
            else
            {
                return(null);
            }
        }
コード例 #16
0
        public CardDocument FindCardAtIndex(uint cardIndex)
        {
            if (cardIndex == 0)
            {
                cardIndex = 1;
            }

            var WordFilter = Builders <CardDocument> .Filter.Eq("_id", cardIndex);

            var card = wordsCollection.FindSync <CardDocument>(WordFilter);

            return(card.FirstOrDefault());
        }
コード例 #17
0
        public override Response <User, Error> Handle(EnrolUserRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.TenantName))
            {
                return(UserError.TenantNameInvalid);
            }

            if (string.IsNullOrWhiteSpace(request.Username))
            {
                return(UserError.UsernameInvalid);
            }

            var account = Thread.CurrentPrincipal.ToAccount();

            if (_userCollection.FindSync(x => x.Accounts.Contains(account)).Any())
            {
                return(UserError.UserAlreadyEnrolled);
            }

            var tenant = new Tenant {
                Name  = request.TenantName,
                Users = new List <UserSummary>(new[]
                {
                    new UserSummary
                    {
                        Accounts = new List <Account>(new [] { account }),
                        Username = request.Username
                    }
                }),
                Accounts = new List <Account>(new[] { account }),
            };

            _tenantCollection.InsertOne(tenant);

            User user = new User
            {
                Username = request.Username,
                Accounts = new List <Account> {
                    account
                },
                Tenants = new List <TenantSummary> {
                    new TenantSummary(tenant.Name, tenant.Id)
                },
                MarketingPreference = request.OptInToMarketing,
                Id = Guid.NewGuid()
            };

            _userCollection.InsertOne(user);

            return(user);
        }
コード例 #18
0
        public OperationResult Execute(CancellationToken cancellationToken)
        {
            try
            {
                var cursor = _collection.FindSync(_filter, _options, cancellationToken);
                var result = cursor.ToList();

                return(OperationResult.FromResult(new BsonArray(result)));
            }
            catch (Exception exception)
            {
                return(OperationResult.FromException(exception));
            }
        }
コード例 #19
0
        /// <summary>
        /// 获取Top多少条数据
        /// </summary>
        /// <param name="limit">条数</param>
        /// <param name="sortDic">排序字典</param>
        /// <param name="expression">条件</param>
        /// <returns></returns>
        public List <T> GetList(int limit, Dictionary <string, string> sortDic, Expression <Func <T, bool> > expression)
        {
            List <T> list = new List <T>();

            try
            {
                var filters = new List <FilterDefinition <T> >();
                filters.Add(GetAction(expression));
                FilterDefinition <T> filter = Builders <T> .Filter.And(filters);

                var sort = Builders <T> .Sort;
                SortDefinition <T> sortDefinition = null;
                foreach (var item in sortDic)
                {
                    if (null == sortDefinition)
                    {
                        if (item.Value == "d")
                        {
                            sortDefinition = sort.Descending(item.Key);
                        }
                        else
                        {
                            sortDefinition = sort.Ascending(item.Key);
                        }
                    }
                    else
                    {
                        if (item.Value == "d")
                        {
                            sortDefinition = sortDefinition.Descending(item.Key);
                        }
                        else
                        {
                            sortDefinition = sortDefinition.Ascending(item.Key);
                        }
                    }
                }
                FindOptions <T, T> findOptions = new FindOptions <T, T>();
                findOptions.Limit = limit;
                findOptions.Sort  = sortDefinition;
                //Pageable pageable = PageRequest.of(pageNUmber, pageSize);
                var fullCollectioin = collection.FindSync(filter, findOptions);
                list = fullCollectioin.ToList();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
            return(list);
        }
コード例 #20
0
        public T Get <T>(object id) where T : DataEntityBase
        {
            IMongoCollection <T> collection = GetCollection <T>();

            using (IAsyncCursor <T> cursor = collection.FindSync(o => Equals(id, o.Id)))
            {
                cursor.MoveNext();
                Logger.Trace($"{nameof(MongoStore)}.{nameof(Get)}",
                             new LogItem("Event", "Get entity"),
                             new LogItem("Type", typeof(T).ToString),
                             new LogItem("Id", id.ToString));
                return(cursor.Current.FirstOrDefault());
            }
        }
コード例 #21
0
        protected override CompletedExtractJobInfo GetCompletedJobInfoImpl(Guid jobId)
        {
            MongoCompletedExtractJobDoc jobDoc =
                _completedJobCollection
                .FindSync(Builders <MongoCompletedExtractJobDoc> .Filter.Eq(x => x.ExtractionJobIdentifier, jobId))
                .SingleOrDefault();

            if (jobDoc == null)
            {
                throw new ApplicationException($"No completed document for job {jobId}");
            }

            return(jobDoc.ToExtractJobInfo());
        }
コード例 #22
0
 public IEnumerable <IReadOnlyList <IDomainEvent> > LoadAll(int batchSize = 10000)
 {
     using (var cursor = _mongoCollection.FindSync(Filter.Empty, FindOptionsFor(batchSize)))
     {
         cursor.MoveNextAsync().Wait();
         Task <bool> cursorTask;
         do
         {
             var events = cursor.Current;
             cursorTask = cursor.MoveNextAsync();
             yield return(events.AsParallel().SelectMany(e => e.ToDomainEvents()).ToList());
         } while (cursorTask.Result);
     }
 }
コード例 #23
0
        /// <summary>
        /// Updates user async
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <User> UpdateUserAsync(User user)
        {
            var dbUser = (await _users.FindSync(Builders <DbUser> .Filter.Eq(d => d.Id, user.Id.ToString()),
                                                new FindOptions <DbUser> {
                Limit = 1
            }).ToListAsync()).GetOne();

            if (!user.HashPassword.IsNullOrEmpty())
            {
                dbUser.HashPassword = user.HashPassword;
            }
            if (!user.Salt.IsNullOrEmpty())
            {
                dbUser.Salt = user.Salt;
            }
            if (!user.PhoneNumber.IsNullOrEmpty())
            {
                dbUser.PhoneNumber = user.PhoneNumber;
            }
            if (!user.PhotoUrl.IsNullOrEmpty())
            {
                dbUser.PhotoUrl = user.PhotoUrl;
            }
            dbUser.DefaultLanguage = user.Language;

            return((await _users.FindOneAndUpdateAsync(Builders <DbUser> .Filter.Where(u => u.Id == user.Id.ToString()),
                                                       Builders <DbUser> .Update
                                                       .Set(f => f.HashPassword, dbUser.HashPassword)
                                                       .Set(f => f.Salt, dbUser.Salt)
                                                       .Set(f => f.PhoneNumber, dbUser.PhoneNumber)
                                                       .Set(f => f.DefaultLanguage, dbUser.DefaultLanguage)
                                                       .Set(f => f.PhotoUrl, dbUser.PhotoUrl),
                                                       new FindOneAndUpdateOptions <DbUser>
            {
                ReturnDocument = ReturnDocument.After
            })).ToUser());
        }
コード例 #24
0
        public async Task <List <RecordVote> > GetRecordVoteList(string hash)
        {
            List <RecordVote> result = null;

            try
            {
                var filter = new FilterDefinitionBuilder <RecordVote>().Eq <string>(vote => vote.hash, hash);
                result = await collection.FindSync <RecordVote>(filter).ToListAsync();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceWarning($"EXCEPTION: {ex.Message}. STACKTRACE: {ex.StackTrace}");
            }
            return(result);
        }
コード例 #25
0
        public IEnumerable <T> Get <T>(Expression <Func <T, bool> > filter, Collation collation = null)
            where T : DataEntityBase
        {
            IMongoCollection <T> collection = GetCollection <T>();

            FindOptions <T, T> findOptions = new FindOptions <T, T> {
                Collation = collation
            };

            using (IAsyncCursor <T> cursor = collection.FindSync(filter, findOptions))
                foreach (T p in IterateCursor(cursor))
                {
                    yield return(p);
                }
        }
コード例 #26
0
        /// <summary>
        ///     Adds a user to the `sessions` collection
        /// </summary>
        /// <param name="user">The User to add.</param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns></returns>
        public async Task <UserResponse> LoginUserAsync(User user, CancellationToken cancellationToken = default)
        {
            try
            {
                var storedUser = await GetUserAsync(user.Email, cancellationToken);

                if (storedUser == null)
                {
                    return(new UserResponse(false, "No user found. Please check the email address."));
                }
                if (user.HashedPassword != null && user.HashedPassword != storedUser.HashedPassword)
                {
                    return(new UserResponse(false, "The hashed password provided is not valid"));
                }
                if (user.HashedPassword == null && !PasswordHashOMatic.Verify(user.Password, storedUser.HashedPassword))
                {
                    return(new UserResponse(false, "The password provided is not valid"));
                }

                // TODO Ticket: User Management
                // Locate the session object in the `sessions` collection by
                // matching the "user_id" field with the email passed to this function.
                // Then update the Session.UserId and Session.Jwt properties,
                // setting the former to the email and the latter to the
                // user.AuthToken that is passed in from the Controller.
                //
                // If the session doesn't exist, allow MongoDB to create a
                // new one by passing the IsUpsert update option.
                //  await _sessionsCollection.UpdateOneAsync(
                //  new BsonDocument(...),
                //  Builders<Session>.Update.Set(...).Set(...),
                //  new UpdateOptions(...));
                var filter = Builders <Session> .Filter.Eq(s => s.UserId, storedUser.Email);

                Session s = await _sessionsCollection.FindSync(filter).FirstOrDefaultAsync(cancellationToken);

                await _sessionsCollection.UpdateOneAsync(filter,
                                                         Builders <Session> .Update.Set(z => z.UserId, user.Email).Set(z => z.Jwt, user.AuthToken),
                                                         new UpdateOptions { IsUpsert = true });

                storedUser.AuthToken = user.AuthToken;
                return(new UserResponse(storedUser));
            }
            catch (Exception ex)
            {
                return(new UserResponse(false, ex.Message));
            }
        }
コード例 #27
0
        public void Listen(CancellationToken cancellationToken)
        {
            var options = new FindOptions <SignalDto>
            {
                // Our cursor is a tailable cursor and informs the server to await
                CursorType = CursorType.TailableAwait,
                // Make sure to time out once in a while to avoid complete blocking operation
                MaxAwaitTime = TimeSpan.FromMinutes(1),
            };

            var filterBuilder = Builders <SignalDto> .Filter;
            var filter        = filterBuilder.Eq(s => s.Signaled, true);

            using (var cursor = _signalCollection.FindSync(filter, options, cancellationToken))
            {
                Logger.Debug($@"*** LISTEN ({Thread.CurrentThread.ManagedThreadId})");
                cancellationToken.ThrowIfCancellationRequested();
                var updateSignaled = Builders <SignalDto> .Update.Set(s => s.Signaled, false);

                cursor.ForEachAsync(document =>
                {
                    var signalDto = _signalCollection.FindOneAndUpdate(
                        s => s.Id == document.Id,
                        updateSignaled,
                        null,
                        cancellationToken);
                    if (signalDto == null)
                    {
                        Logger.Debug($@"*** TRIGGERED ({Thread.CurrentThread.ManagedThreadId})");
                    }
                    else
                    {
                        Logger.Debug($@"*** OWNED: {signalDto.Name} ({Thread.CurrentThread.ManagedThreadId})");
                    }
                    EventWaitHandles
                    .GetOrAdd(document.Name, n => new EventWaitHandle(false, EventResetMode.AutoReset))
                    .Set();
                }, cancellationToken).ContinueWith(t =>
                {
                    // TODO: Log if canceled?
                    if (t.IsFaulted)
                    {
                        var messages = string.Join(Environment.NewLine, t.Exception.InnerExceptions.Select(e => e.Message));
                        Logger.Debug($@"*** FAULT: {messages} ({Thread.CurrentThread.ManagedThreadId})");
                    }
                }).Wait(cancellationToken);
            }
        }
コード例 #28
0
        public List <AccessKey> GetAccessKeys(int organisationID)
        {
            List <AccessKey> result   = new List <AccessKey>();
            IMongoDatabase   database = GetDatabase(DATABASE_NAME, false);
            IMongoCollection <BsonDocument> collection  = database.GetCollection <BsonDocument>("AccessKey");
            IAsyncCursor <BsonDocument>     mongoCursor = collection.FindSync(Builders <BsonDocument> .Filter.Eq("OrganisationID", organisationID));

            while (mongoCursor.MoveNext())
            {
                foreach (BsonDocument item in mongoCursor.Current)
                {
                    result.Add(LoadAccessKey(item));
                }
            }
            return(result);
        }
コード例 #29
0
            public async Task ApplyConvention_WithoutValueInDb_SerializeSuccessful()
            {
                // Arrange
                IMongoCollection <A> collectionTyped =
                    _context.Database.GetCollection <A>("test");
                IMongoCollection <BsonDocument> collectionUntyped =
                    _context.Database.GetCollection <BsonDocument>("test");

                // Act
                await collectionUntyped.InsertOneAsync(new BsonDocument { { "_A", "a" } });

                // Assert
                A result = await collectionTyped.FindSync(FilterDefinition <A> .Empty).FirstAsync();

                result.MatchSnapshot();
            }
コード例 #30
0
        public async Task <IEnumerable <Topic> > Search(string words)
        {
            var filter = new BsonDocument {
                {
                    "Title",
                    new BsonDocument {
                        { "$regex", words },
                        { "$options", "i" }
                    }
                }
            };

            var queryResult = topicCollection.FindSync(filter);

            return(await queryResult.ToListAsync());
        }
コード例 #31
0
        public async Task <List <ToDoItem> > QueryAsync(string description, bool?done)
        {
            IEnumerable <ToDoItem> models = _items.FindSync(i => true).ToEnumerable();

            if (!string.IsNullOrEmpty(description))
            {
                models = models.Where(v => v.Description?.IndexOf(description, StringComparison.OrdinalIgnoreCase) >= 0);
            }

            if (done != null)
            {
                models = models.Where(v => v.Done == done.Value);
            }

            return(models.ToList());
        }
コード例 #32
0
ファイル: GridFSTestBase.cs プロジェクト: RavenZZ/MDRelation
 private List<BsonDocument> GetCollectionDocuments(IMongoCollection<BsonDocument> collection)
 {
     return collection.FindSync(new BsonDocument()).ToList();
 }