コード例 #1
0
ファイル: DataAccess.cs プロジェクト: waffle-iron/nequeo
 /// <summary>
 /// Counts the number of documents in this collection that match a query.
 /// </summary>
 /// <typeparam name="T">The default document type for this collection.</typeparam>
 /// <param name="collection">An instance of MongoCollection.</param>
 /// <param name="query">The query to execute.</param>
 /// <param name="limit">The number of items to return.</param>
 /// <param name="skip">The number of items to skip.</param>
 /// <returns>The number of documents in this collection that match the query.</returns>
 public async virtual Task <long> Count <T>(IMongoCollection <T> collection, FilterDefinition <T> query, int limit = -1, int skip = 0)
 {
     if (limit > -1 && skip > 0)
     {
         return(await collection.CountAsync(query, new CountOptions()
         {
             Limit = (long)limit, Skip = (long)skip
         }));
     }
     else if (skip > 0)
     {
         return(await collection.CountAsync(query, new CountOptions()
         {
             Skip = (long)skip
         }));
     }
     else if (limit > -1)
     {
         return(await collection.CountAsync(query, new CountOptions()
         {
             Limit = (long)limit
         }));
     }
     else
     {
         return(await collection.CountAsync(query));
     }
 }
コード例 #2
0
        public PagedResult <TEntity> GetModel(
            Expression <Func <TEntity, bool> > expression,
            Dictionary <Expression <Func <TEntity, object> >, bool> fields,
            int pageIndex,
            int pageSize)
        {
            SortDefinition <TEntity> sorts = new ObjectSortDefinition <TEntity>(new { });

            foreach (var item in fields)
            {
                if (item.Value)
                {
                    sorts = sorts.Ascending(item.Key);
                }
                else
                {
                    sorts = sorts.Descending(item.Key);
                }
            }
            var skip        = (pageIndex - 1) * pageSize;
            var limit       = pageSize;
            var recordCount = _table.CountAsync <TEntity>(expression).Result;

            return(new PagedResult <TEntity>(
                       recordCount,
                       (int)(recordCount + pageSize - 1) / pageSize,
                       pageSize,
                       pageIndex,
                       _table.Find(expression)
                       .Sort(sorts)
                       .Skip(skip)
                       .Limit(limit)
                       .ToListAsync().Result));
        }
コード例 #3
0
 public async Task <PatientPage> GetPatients(FindPatientModel model, int limit, int skip)
 {
     try
     {
         List <Patient> collection;
         if (!String.IsNullOrWhiteSpace(model.PatientId))
         {
             collection = await _patients.Find(p => p.PatientId == model.PatientId)
                          .Skip(skip)
                          .Limit(limit)
                          .ToListAsync();
         }
         else
         {
             collection = await _patients.Find(p => p.Name == model.Name).ToListAsync();
         }
         var patientPage = new PatientPage
         {
             Patients = collection.ConvertToDTOExtension().ToList(),
             Count    = Convert.ToInt32(await _patients.CountAsync(new BsonDocument()))
         };
         return(patientPage);
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.Message);
         return(null);
     }
 }
コード例 #4
0
        public async Task <IPagedList <TEntity> > GetPagedListAsync(
            FilterDefinition <TEntity> filter = null,
            SortDefinition <TEntity> sort     = null,
            ProjectionDefinition <TEntity, TEntity> projection = null,
            int?skip = null,
            int?take = null)
        {
            var page = skip ?? DefaultPage;
            var size = take ?? DefaultSize;

            filter = filter ?? Builders <TEntity> .Filter.Empty;
            var totalItems = await _collection.CountAsync(filter);

            if (totalItems == 0)
            {
                return(PagedList <TEntity> .Empty(page, size));
            }

            var totalPages = (int)Math.Ceiling(totalItems / (double)size);

            var options = new FindOptions <TEntity, TEntity>
            {
                Sort       = sort ?? Builders <TEntity> .Sort.Descending(e => e.Id),
                Projection = projection,
                Skip       = page <= 1 ? new int?() : (page - 1) * size,
                Limit      = size
            };

            var cursor = await _collection.FindAsync(filter, options);

            return(PagedList <TEntity> .Create(totalItems, await cursor.ToListAsync(), totalPages, page, size));
        }
コード例 #5
0
 public Task <long> CountAsync(
     FilterDefinition <T> filter,
     CountOptions?options = null,
     CancellationToken cancellationToken = default
     )
 {
     return(collection.CountAsync(filter, options, cancellationToken));
 }
コード例 #6
0
        public async Task <long> CountNewByUserIdAsync(string userId, DateTime lastChecked)
        {
            var ownerLogs = _logCollection.FindSync(x => x.UserId == userId).ToList().Select(x => x.LogId).ToList();

            var filter = Builders <Error> .Filter.In("LogId", ownerLogs)
                         & Builders <Error> .Filter.Gt("Time", lastChecked);

            return(await _collection.CountAsync(filter));
        }
コード例 #7
0
ファイル: MongoAccess.cs プロジェクト: youlin1210/MySample
        public async Task <long> CountAsync <TDocument>(string tableName, FilterDefinition <TDocument> filter = null, CountOptions options = null) where TDocument : class
        {
            IMongoCollection <TDocument> collection = db.GetCollection <TDocument>(tableName);

            if (filter == null)
            {
                return(await collection.CountAsync(new BsonDocument(), options));
            }
            return(await collection.CountAsync(filter, options));
        }
コード例 #8
0
        public void Should_tolerate_null_raw_property()
        {
            ILog target = GetConfiguredLog();

            ThreadContext.Properties["customProperty"] = null;

            target.Info("Finished");

            _collection.CountAsync(new BsonDocument()).ContinueWith(c => c.Result.Should().Be.EqualTo(1));
        }
コード例 #9
0
 public Task <long> CountAsync(Expression <Func <T, bool> > filter = null)
 {
     if (filter == null)
     {
         return(_collection.CountAsync(Builders <T> .Filter.Empty));
     }
     else
     {
         return(_collection.CountAsync(filter));
     }
 }
コード例 #10
0
        public Task <long> CountAsync(
            FilterDefinition <T> filter,
            CountOptions?options = null,
            CancellationToken cancellationToken = default)
        {
            if (TryGetSession(out IClientSessionHandle? session))
            {
                return(CountAsync(session, filter, options, cancellationToken));
            }

            return(_collection.CountAsync(filter, options, cancellationToken));
        }
コード例 #11
0
 public override Task<long> CountAsync(CancellationToken cancellationToken)
 {
     var options = CreateCountOptions();
     if (_session == null)
     {
         return _collection.CountAsync(_filter, options, cancellationToken);
     }
     else
     {
         return _collection.CountAsync(_session, _filter, options, cancellationToken);
     }
 }
コード例 #12
0
        protected override async Task <IPage <TEntity> > OnFindAsync(Expression <Func <TEntity, bool> > filter,
                                                                     IPageable <TEntity> pageable)
        {
            var count = await _collection.CountAsync(filter);

            if (count == 0)
            {
                return(new Page <TEntity>(new List <TEntity>(), pageable, count));
            }

            var find = _collection.Find(filter);

            var offset = pageable.PageNumber * pageable.PageSize;
            var limit  = pageable.PageSize;

            find = find.Skip(offset).Limit(limit);
            if (pageable.Sort?.OrderBy?.Count() > 0)
            {
                var isFirst = true;
                foreach (var item in pageable.Sort.OrderBy)
                {
                    if (isFirst)
                    {
                        isFirst = false;
                        find    = find.SortBy(item);
                    }
                    else
                    {
                        find = ((IOrderedFindFluent <TEntity, TEntity>)find).ThenBy(item);
                    }
                }
            }
            if (pageable.Sort?.OrderDescendingBy?.Count() > 0)
            {
                var isFirst = true;
                foreach (var item in pageable.Sort.OrderDescendingBy)
                {
                    if (isFirst)
                    {
                        isFirst = false;
                        find    = find.SortByDescending(item);
                    }
                    else
                    {
                        find = ((IOrderedFindFluent <TEntity, TEntity>)find).ThenByDescending(item);
                    }
                }
            }
            var content = await find.ToListAsync();

            return(new Page <TEntity>(content, pageable, count));
        }
コード例 #13
0
        public IList <TEntity> GetPagedList(int page, int pageSize)
        {
            long count = 0;
            var  lst   = new List <TEntity>();
            int  skip  = (int)((page - 1) * pageSize);

            lst   = _collection.Find(new BsonDocument()).Skip(skip).Limit(pageSize).ToListAsync().Result;
            count = _collection.CountAsync(new BsonDocument()).Result;

            var pagedList = new PagedListHelper <TEntity>(lst, page, pageSize, count);

            return(pagedList);
        }
コード例 #14
0
        public async Task <long> CountAsync()
        {
            IMongoCollection <T> collection   = this.Collection;
            FilterDefinition <T> bsonDocument = new BsonDocument();

            return(await collection.CountAsync(bsonDocument, null, new CancellationToken()));
        }
コード例 #15
0
ファイル: AlertsJob.cs プロジェクト: LykkeCity/SolarCoinApi
        public async Task Execute()
        {
            await _log.WriteInfoAsync(_componentName, "", "", "Cycle started");


            var filterBuilder = Builders <TransactionMongoEntity> .Filter;
            var txesFilter    = filterBuilder.Eq(x => x.WasProcessed, false) | filterBuilder.Exists(x => x.WasProcessed, false);


            var numTxes = await _blockchainExplorer.CountAsync(txesFilter);

            if (numTxes < 100)
            {
                //await _emailNotifier.Notify("a", "bbb");
            }

            if (await _transitQueue.Count() > 100)
            {
                //await _emailNotifier.Notify("", "");
            }

            if (await _cashoutQueue.Count() > 5)
            {
                //await _emailNotifier.Notify("", "");
            }
        }
コード例 #16
0
        /// <summary>
        /// Retrieves a page of application errors from the log in
        /// descending order of logged time.
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="errorEntryList"></param>
        /// <returns></returns>
        public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
        {
            if (pageIndex < 0)
            {
                throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
            }
            if (pageSize < 0)
            {
                throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
            }

            // Need to force documents into descending date order
            var sort = Builders <BsonDocument> .Sort.Descending("time");

            var task = _collection.Find(new BsonDocument())
                       .Sort(sort)
                       .Skip(pageIndex * pageSize)
                       .Limit(pageSize).ToListAsync();

            task.Wait();
            var documents = task.Result;

            foreach (var document in documents)
            {
                var id    = document["_id"].AsObjectId.ToString();
                var error = BsonSerializer.Deserialize <Error>(document);
                error.Time = error.Time.ToLocalTime();
                errorEntryList.Add(new ErrorLogEntry(this, id, error));
            }

            var t = _collection.CountAsync(new BsonDocument());

            t.Wait();
            return((int)t.Result);
        }
コード例 #17
0
        public async Task <MongoExternalUser> AutoProvisionUser(string provider, string userId, List <Claim> claims)
        {
            var filter = Filters.Where(x => x.UsernameNormalized == userId.ToLowerInvariant().Normalize());
            var numberOfUsersWithUsername = await collection.CountAsync(filter);

            if (numberOfUsersWithUsername > 0)
            {
                throw new UserExistsException();
            }


            var nameClaim  = ClaimsFinder.ResolveNameClaim(userId, claims);
            var emailClaim = claims.ResolveEmailClaim();

            var user = new MongoExternalUser
            {
                ProviderId  = userId,
                Username    = nameClaim?.Value,
                Email       = emailClaim.Value,
                ProviderKey = provider,
                Claims      = claims.Select(x => new MongoClaim(x)).ToList()
            };

            user.SetMongoInternals();
            await collection.InsertOneAsync(user);

            return(user);
        }
コード例 #18
0
        public async Task <AuthenticatedUserUpdatedEvent> HandleAsync(UpdateAuthenticatedUserCommand command,
                                                                      CancellationToken cancellationToken)
        {
            var authenticatedUserId = _authenticatedUserAccessor.AuthenticatedUser.Id;

            if (await _usersCollection.CountAsync(
                    u => u.Id != authenticatedUserId && u.EmailAddress == command.EmailAddress,
                    cancellationToken: cancellationToken) > 0)
            {
                throw new EmailAddressAlreadyTakenException
                      (
                          command.EmailAddress
                      );
            }

            var filter = Builders <User> .Filter.Where(t => t.Id == authenticatedUserId);

            var update = Builders <User> .Update.Set(t => t.Name, command.Name)
                         .Set(t => t.EmailAddress, command.EmailAddress);

            await _usersCollection.UpdateOneAsync(filter, update, cancellationToken : cancellationToken);

            return(new AuthenticatedUserUpdatedEvent
                   (
                       command.Name,
                       command.EmailAddress
                   ));
        }
コード例 #19
0
        public async Task <StaticPagedList <T> > PaginationAsync(int page, int total, SortDefinition <T> sortBy, Expression <Func <T, bool> > query = null)
        {
            StaticPagedList <T> staticPagedList;
            CancellationToken   cancellationToken;
            long num = (long)0;

            if (query != null)
            {
                IMongoCollection <T> collection       = this.Collection;
                FilterDefinition <T> filterDefinition = query;
                cancellationToken = new CancellationToken();
                num = await collection.CountAsync(filterDefinition, null, cancellationToken);

                IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, query, null).Skip(new int?((page - 1) * total)).Limit(new int?(total)).Sort(sortBy);
                cancellationToken = new CancellationToken();
                List <T> listAsync = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent, cancellationToken);

                staticPagedList = new StaticPagedList <T>(listAsync, page, total, (int)num);
            }
            else
            {
                IMongoCollection <T> mongoCollection = this.Collection;
                FilterDefinition <T> bsonDocument    = new BsonDocument();
                cancellationToken = new CancellationToken();
                num = await mongoCollection.CountAsync(bsonDocument, null, cancellationToken);

                IFindFluent <T, T> findFluent1 = IMongoCollectionExtensions.Find <T>(this.Collection, new BsonDocument(), null).Skip(new int?((page - 1) * total)).Limit(new int?(total)).Sort(sortBy);
                cancellationToken = new CancellationToken();
                List <T> ts = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent1, cancellationToken);

                staticPagedList = new StaticPagedList <T>(ts, page, total, (int)num);
            }
            return(staticPagedList);
        }
コード例 #20
0
        public async Task <IActionResult> Get()
        {
            var resp = new MongoResponseModel();

            try
            {
                await _mongoDb.RunCommandAsync((Command <BsonDocument>) "{ping:1}");

                resp.MongoTxesCount = (int)await _collection.CountAsync(x => true);

                resp.MongoIsAlive = true;

                return(Json(resp));
            }
            catch (Exception e) when(e is MongoConnectionException || e is TimeoutException)
            {
                resp.MongoTxesCount = -1;
                resp.MongoIsAlive   = false;

                return(Json(resp));
            }
            catch (Exception e)
            {
                await _logger.WriteErrorAsync("SolarCoinApi.Monitoring.MongoController", "", "", e);

                return(StatusCode(500));
            }
        }
コード例 #21
0
        public static bool Exists(MongoConnection connection)
        {
            IMongoCollection <Config> configs = connection.Database.GetCollection <Config>(typeof(Config).Name);
            Task <long> configFind            = configs.CountAsync(config => true);

            return(configFind.Result > 0);
        }
コード例 #22
0
        /// <summary>
        /// Counts the number of documents in the collection.
        /// </summary>
        /// <typeparam name="TDocument">The type of the document.</typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="options">The options.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The number of documents in the collection.
        /// </returns>
        public static Task <long> CountAsync <TDocument>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, CountOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(collection, "collection");
            Ensure.IsNotNull(filter, "filter");

            return(collection.CountAsync(new ExpressionFilterDefinition <TDocument>(filter), options, cancellationToken));
        }
コード例 #23
0
        public static bool Exists(MongoConnection connection, string urlName)
        {
            IMongoCollection <UrlLogin> urlLoginCollection = connection.Database.GetCollection <UrlLogin>(typeof(UrlLogin).Name);
            Task <long> urlLoginTask = urlLoginCollection.CountAsync(urlLogin => urlLogin.UrlName == urlName);

            return(urlLoginTask.Result > 0);
        }
コード例 #24
0
        private static void FillEnumeratorValues(Type enumeratorType, string collectionName)
        {
            // get the current collection of data avaliable in the states data base
            IMongoCollection <BsonDocument> documentInDatabase = _mongodbDatabase.GetCollection <BsonDocument>(collectionName);

            // get the total number of ducuments currently present in the database
            Task <long> countTask = documentInDatabase.CountAsync(new BsonDocument());

            countTask.Wait();

            // check whether there are any documents returned from the database
            if (countTask.Result == 0)
            {
                Console.WriteLine("No '" + collectionName + "' data is avaliable.");
                Console.WriteLine("Inserting state data");

                List <BsonDocument> documents = new List <BsonDocument>();

                foreach (var enumItem in Enum.GetValues(enumeratorType))
                {
                    Dictionary <string, object> documentValues = new Dictionary <string, object>();
                    documentValues["Name"]  = enumItem.ToString();
                    documentValues["Value"] = (int)enumItem;

                    documents.Add(new BsonDocument(documentValues));
                }

                documentInDatabase.InsertManyAsync(documents);

                Console.WriteLine("Completed adding the " + collectionName + " details to the database");
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: onfjp/dd-trace-dotnet
        public static async Task RunAsync(IMongoCollection <BsonDocument> collection, BsonDocument newDocument)
        {
            var allFilter = new BsonDocument();

            using (var asyncScope = Tracer.Instance.StartActive("async-calls", serviceName: "Samples.MongoDB"))
            {
                await collection.DeleteManyAsync(allFilter);

                await collection.InsertOneAsync(newDocument);

#if MONGODB_2_7
                var count = await collection.CountDocumentsAsync(new BsonDocument());
#else
                var count = await collection.CountAsync(new BsonDocument());
#endif

                Console.WriteLine($"Documents: {count}");

                var find = await collection.FindAsync(allFilter);

                var allDocuments = await find.ToListAsync();

                Console.WriteLine(allDocuments.FirstOrDefault());
            }
        }
コード例 #26
0
        public static bool Exists(MongoConnection connection, string ip)
        {
            IMongoCollection <Server> serverCollection = connection.Database.GetCollection <Server>(typeof(Server).Name);
            Task <long> serverTask = serverCollection.CountAsync(server => server.Ip == ip);

            return(serverTask.Result > 0);
        }
コード例 #27
0
        public List <T> GetMany(FilterDefinition <T> filter, SortDefinition <T> sorter, ProjectionDefinition <T> projection, ref PagerInfo pagerInfo)
        {
            IMongoCollection <T> myCollection = GetCollection();

            AggregateOptions opts = new AggregateOptions()
            {
                AllowDiskUse = true,
                BatchSize    = int.MaxValue,
                MaxTime      = TimeSpan.FromMinutes(10)
            };

            IAggregateFluent <T> aggregate = GetAggregateFluent(opts);

            if (filter == null)
            {
                filter = Builders <T> .Filter.Empty;
            }
            aggregate = aggregate.Match(filter);

            if (sorter != null)
            {
                aggregate.Sort(sorter);
            }
            if (projection != null)
            {
                aggregate = aggregate.Project <T>(projection);
            }

            pagerInfo.Total = myCollection.CountAsync(filter).GetAwaiter().GetResult();

            List <T> result = aggregate.Match(filter).Sort(sorter).Skip(pagerInfo.Page).Limit(pagerInfo.PageSize)
                              .ToListAsync <T>().GetAwaiter().GetResult();

            return(result);
        }
コード例 #28
0
        public static void IncreaseSignal(MongoConnection connection, string option, SignalTypeEnum signalType, double strength)
        {
            IMongoCollection <Signal> signalsCollection = connection.Database.GetCollection <Signal>(typeof(Signal).Name);

            FilterDefinition <Signal> filter =
                Builders <Signal> .Filter.Eq(signal => signal.Option, option) &
                Builders <Signal> .Filter.Eq(signal => signal.SignalType, signalType);

            long signalCount = signalsCollection.CountAsync(filter).Result;

            if (signalCount == 0)
            {
                Signal signal = new Signal()
                {
                    Option     = option,
                    SignalType = signalType,
                    Strength   = strength,
                };

                Task insertTask = signalsCollection.InsertOneAsync(signal);

                insertTask.Wait();
            }
            else
            {
                UpdateDefinition <Signal> update = Builders <Signal> .Update.Inc(signal => signal.Strength, strength);

                Task updateTask = signalsCollection.UpdateOneAsync(filter, update);

                updateTask.Wait();
            }
        }
コード例 #29
0
        public async Task <BigInteger> GetSyncedBlocksCountAsync()
        {
            var        filterBuilder = Builders <BlockEntity> .Filter;
            BigInteger result        = await _collection.CountAsync(filterBuilder.Empty);

            return(result);
        }
コード例 #30
0
 public async Task EnsureAdminUser()
 {
     if (await Users.CountAsync(_ => true) == 0)
     {
         await CreateUser(AdminName, AdminPassword, AdminRoles);
     }
 }
コード例 #31
0
ファイル: ConnectionInfo.cs プロジェクト: magicdict/MongoCola
 public static long GetCollectionCnt(IMongoCollection<BsonDocument> col)
 {
     long colCount = 0;
     Expression<Func<BsonDocument, bool>> countfun = x => true;
     var task = Task.Run(
         async () => { colCount = await col.CountAsync(countfun); }
         );
     task.Wait();
     return colCount;
 }
コード例 #32
0
ファイル: CountTest.cs プロジェクト: RavenZZ/MDRelation
 protected override void Execute(IMongoCollection<BsonDocument> collection, bool async)
 {
     if (async)
     {
         collection.CountAsync(_filter, _options).GetAwaiter().GetResult();
     }
     else
     {
         collection.Count(_filter, _options);
     }
 }
コード例 #33
0
        /// <summary>
        ///     将数据集放入Node
        /// </summary>
        /// <param name="col"></param>
        /// <param name="mongoConnSvrKey"></param>
        /// <returns></returns>
        public static TreeNode FillCollectionInfoToTreeNode(IMongoCollection<BsonDocument> col, string mongoConnSvrKey)
        {
            var strShowColName = col.CollectionNamespace.CollectionName;
            var databaseName = col.CollectionNamespace.DatabaseNamespace.DatabaseName;
            if (!GuiConfig.IsUseDefaultLanguage)
            {
                switch (strShowColName)
                {
                    case "chunks":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameChunks) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "collections":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameCollections) + "(" + strShowColName + ")";
                        }
                        break;
                    case "changelog":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameChangelog) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "databases":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameDatabases) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "lockpings":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameLockpings) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "locks":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameLocks) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "mongos":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameMongos) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "settings":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameSettings) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "shards":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameShards) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "tags":
                        //ADD: 2013/01/04 Mongo2.2.2开始支持ShardTag了 
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameTags) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "version":
                        if (databaseName == "config")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameVersion) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "me":
                        if (databaseName == "local")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameMe) + "(" +
                                strShowColName + ")";
                        }
                        break;
                    case "sources":
                        if (databaseName == "local")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameSources) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case "slaves":
                        if (databaseName == "local")
                        {
                            strShowColName =
                                GuiConfig.GetText(
                                    TextType.SystemcColnameSlaves) +
                                "(" + strShowColName + ")";
                        }
                        break;
                    case ConstMgr.CollectionNameGfsChunks:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameGfsChunks) +
                            "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameGfsFiles:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameGfsFiles) +
                            "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameOperationLog:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameOperationLog) +
                            "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameSystemIndexes:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameSystemIndexes) +
                            "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameJavascript:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameJavascript) +
                            "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameSystemReplset:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameSystemReplset) +
                            "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameReplsetMinvalid:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameReplsetMinvalid) + "(" + strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameUser:
                        strShowColName =
                            GuiConfig.GetText(TextType.CollectionNameUser) +
                            "(" +
                            strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameRole:
                        //New From 2.6 
                        strShowColName =
                            GuiConfig.GetText(TextType.CollectionNameRole) +
                            "(" +
                            strShowColName + ")";
                        break;
                    case ConstMgr.CollectionNameSystemProfile:
                        strShowColName =
                            GuiConfig.GetText(
                                TextType.CollectionNameSystemProfile) +
                            "(" + strShowColName + ")";
                        break;
                }
            }
            //Collection件数的表示
            long colCount = 0;
            Expression<Func<BsonDocument, bool>> countfun = x => true;
            var task = Task.Run(
                async () => { colCount = await col.CountAsync(countfun); }
                );
            task.Wait();
            strShowColName = strShowColName + "(" + colCount + ")";
            var mongoColNode = new TreeNode(strShowColName);
            switch (col.CollectionNamespace.CollectionName)
            {
                case ConstMgr.CollectionNameGfsFiles:
                    mongoColNode.Tag = ConstMgr.GridFileSystemTag + ":" + mongoConnSvrKey + "/" + databaseName + "/" +
                                       col.CollectionNamespace.CollectionName;
                    break;
                case ConstMgr.CollectionNameUser:
                    mongoColNode.Tag = ConstMgr.UserListTag + ":" + mongoConnSvrKey + "/" + databaseName + "/" +
                                       col.CollectionNamespace.CollectionName;
                    break;
                default:
                    mongoColNode.Tag = TagInfo.CreateTagInfo(mongoConnSvrKey, databaseName,
                        col.CollectionNamespace.CollectionName);
                    break;
            }

            //MongoCollection mongoCol = mongoDB.GetCollection(strColName);

            ////Start ListIndex
            //var mongoIndexes = new TreeNode("Indexes");
            //var indexList = mongoCol.GetIndexes();
            IAsyncCursor<BsonDocument> indexCursor = null;
            task = Task.Run(
                async () => { indexCursor = await col.Indexes.ListAsync(); }
                );
            task.Wait();
            List<BsonDocument> indexDocs = null;
            task = Task.Run(
                async () => { indexDocs = await indexCursor.ToListAsync(); }
                );
            task.Wait();
            foreach (var indexDoc in indexDocs)
            {
                var mongoIndexes = new TreeNode {Text = indexDoc.GetElement("name").Value.ToString()};
                foreach (var item in indexDoc.Elements)
                {
                    mongoIndexes.Nodes.Add(string.Empty, item.Name + ":" + item.Value,
                        (int) GetSystemIcon.MainTreeImageType.KeyInfo,
                        (int) GetSystemIcon.MainTreeImageType.KeyInfo);
                }
                mongoIndexes.ImageIndex = (int) GetSystemIcon.MainTreeImageType.Keys;
                mongoIndexes.SelectedImageIndex = (int) GetSystemIcon.MainTreeImageType.Keys;
                mongoIndexes.Tag = ConstMgr.IndexesTag + ":" + mongoConnSvrKey + "/" + databaseName + "/" +
                                   col.CollectionNamespace.CollectionName;
                mongoColNode.Nodes.Add(mongoIndexes);
            }

            #region Legacy

            //foreach (var indexDoc in indexList.ToList())
            //{
            //    var mongoIndex = new TreeNode();
            //    if (!GUIConfig.IsUseDefaultLanguage)
            //    {
            //        mongoIndex.Text =
            //            (GUIConfig.MStringResource.GetText(TextType.Index_Name) + ":" +
            //             indexDoc.Name);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_Keys) + ":" +
            //            GetKeyString(indexDoc.Key), (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_RepeatDel) + ":" +
            //            indexDoc.DroppedDups, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_Background) + ":" +
            //            indexDoc.IsBackground, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_Sparse) + ":" +
            //            indexDoc.IsSparse, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_Unify) + ":" +
            //            indexDoc.IsUnique, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_NameSpace) + ":" +
            //            indexDoc.Namespace, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty,
            //            GUIConfig.MStringResource.GetText(TextType.Index_Version) + ":" +
            //            indexDoc.Version, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        if (indexDoc.TimeToLive == TimeSpan.MaxValue)
            //        {
            //            mongoIndex.Nodes.Add(string.Empty,
            //                GUIConfig.MStringResource.GetText(TextType.Index_ExpireData) +
            //                ":Not Set",
            //                (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        }
            //        else
            //        {
            //            mongoIndex.Nodes.Add(string.Empty,
            //                GUIConfig.MStringResource.GetText(TextType.Index_ExpireData) +
            //                ":" +
            //                indexDoc.TimeToLive.TotalSeconds, (int) GetSystemIcon.MainTreeImageType.KeyInfo,
            //                (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        }
            //    }
            //    else
            //    {
            //        mongoIndex.Text = "IndexName:" + indexDoc.Name;
            //        mongoIndex.Nodes.Add(string.Empty, "Keys:" + GetKeyString(indexDoc.Key),
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "DroppedDups :" + indexDoc.DroppedDups,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "IsBackground:" + indexDoc.IsBackground,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "IsSparse:" + indexDoc.IsSparse,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "IsUnique:" + indexDoc.IsUnique,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "NameSpace:" + indexDoc.Namespace,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "Version:" + indexDoc.Version,
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        if (indexDoc.TimeToLive == TimeSpan.MaxValue)
            //        {
            //            mongoIndex.Nodes.Add(string.Empty, "Expire Data:Not Set",
            //                (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        }
            //        else
            //        {
            //            mongoIndex.Nodes.Add(string.Empty, "Expire Data(sec):" + indexDoc.TimeToLive.TotalSeconds,
            //                (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        }
            //    }
            //    if (indexDoc.RawDocument.Contains("default_language"))
            //    {
            //        //TextIndex
            //        mongoIndex.Nodes.Add(string.Empty, "weights:" + indexDoc.RawDocument["weights"],
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "default_language:" + indexDoc.RawDocument["default_language"],
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "language_override:" + indexDoc.RawDocument["language_override"],
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //        mongoIndex.Nodes.Add(string.Empty, "textIndexVersion:" + indexDoc.RawDocument["textIndexVersion"],
            //            (int) GetSystemIcon.MainTreeImageType.KeyInfo, (int) GetSystemIcon.MainTreeImageType.KeyInfo);
            //    }
            //    mongoIndex.ImageIndex = (int) GetSystemIcon.MainTreeImageType.DBKey;
            //    mongoIndex.SelectedImageIndex = (int) GetSystemIcon.MainTreeImageType.DBKey;
            //    mongoIndex.Tag = ConstMgr.INDEX_TAG + ":" + mongoConnSvrKey + "/" + DatabaseName + "/" + strColName +
            //                     "/" +
            //                     indexDoc.Name;
            //    mongoIndexes.Nodes.Add(mongoIndex);
            //}
            //mongoIndexes.ImageIndex = (int) GetSystemIcon.MainTreeImageType.Keys;
            //mongoIndexes.SelectedImageIndex = (int) GetSystemIcon.MainTreeImageType.Keys;
            //mongoIndexes.Tag = ConstMgr.INDEXES_TAG + ":" + mongoConnSvrKey + "/" + DatabaseName + "/" + strColName;
            //mongoColNode.Nodes.Add(mongoIndexes);
            ////End ListIndex

            //mongoColNode.ToolTipText = strColName + Environment.NewLine;
            //mongoColNode.ToolTipText += "IsCapped:" + mongoCol.GetStats().IsCapped;

            #endregion

            if (col.CollectionNamespace.CollectionName == ConstMgr.CollectionNameUser)
            {
                mongoColNode.ImageIndex = (int) GetSystemIcon.MainTreeImageType.UserIcon;
                mongoColNode.SelectedImageIndex = (int) GetSystemIcon.MainTreeImageType.UserIcon;
            }
            else
            {
                mongoColNode.ImageIndex = (int) GetSystemIcon.MainTreeImageType.Collection;
                mongoColNode.SelectedImageIndex = (int) GetSystemIcon.MainTreeImageType.Collection;
            }
            //End Data
            return mongoColNode;
        }
コード例 #34
0
ファイル: Program.cs プロジェクト: sshev4enko/tandd
 /// <summary>
 /// Count documents (SQL=rows) in the collection (SQL=table).
 /// </summary>
 private static async Task CountAsync(IMongoCollection<BsonDocument> collection)
 {
     long count = await collection.CountAsync(new BsonDocument());
     Console.WriteLine("\n[DB]{0}.[Collection]{1} : collection.Count = {2}", collection.Database.DatabaseNamespace.DatabaseName, collection.CollectionNamespace.CollectionName, count);
 }
コード例 #35
0
 protected override Task ExecuteAsync(IMongoCollection<BsonDocument> collection)
 {
     return collection.CountAsync(_filter, _options);
 }
コード例 #36
0
		private async Task CreateAdmin(IMongoCollection<UserModel> users)
		{
 			await users.Indexes.CreateOneAsync(
				Builders<UserModel>.IndexKeys.Ascending(u => u.Name),
				new CreateIndexOptions { Unique = true, });

			if (await users.CountAsync(_ => true) == 0)
			{
				await users
					.InsertOneAsync(
					new UserModel
					{
						Name = AdminName,
						Password = AdminPassword,
						Roles = AdminRoles
					});
			}
		}