public void TestDropDatabase()
        {
            _collection.Insert(new BsonDocument());
            var databaseNames = _server.GetDatabaseNames();

            Assert.IsTrue(databaseNames.Contains(_database.Name));

            var result = _server.DropDatabase(_database.Name);

            databaseNames = _server.GetDatabaseNames();
            Assert.IsFalse(databaseNames.Contains(_database.Name));
        }
        public void TestDropDatabase()
        {
            if (!_isMasterSlavePair)
            {
                _collection.Insert(new BsonDocument());
                var databaseNames = _server.GetDatabaseNames();
                Assert.IsTrue(databaseNames.Contains(_database.Name));

                _server.DropDatabase(_database.Name);
                databaseNames = _server.GetDatabaseNames();
                Assert.IsFalse(databaseNames.Contains(_database.Name));
            }
        }
示例#3
0
        public void TestDropDatabase()
        {
            var databaseNamespace = CoreTestConfiguration.GetDatabaseNamespaceForTestClass(typeof(MongoServerTests));
            var database          = __server.GetDatabase(databaseNamespace.DatabaseName);
            var collection        = database.GetCollection("test");

            collection.Insert(new BsonDocument());
            var databaseNames = __server.GetDatabaseNames();

            Assert.True(databaseNames.Contains(database.Name));

            __server.DropDatabase(database.Name);
            databaseNames = __server.GetDatabaseNames();
            Assert.False(databaseNames.Contains(database.Name));
        }
示例#4
0
        public void TestDropDatabase()
        {
            var databaseName = "onlinetests-temp";
            var database     = server[databaseName];
            var test         = database["test"];

            test.Insert(new BsonDocument());
            var databaseNames = server.GetDatabaseNames();

            Assert.IsTrue(databaseNames.Contains(databaseName));

            var result = server.DropDatabase(databaseName);

            databaseNames = server.GetDatabaseNames();
            Assert.IsFalse(databaseNames.Contains(databaseName));
        }
示例#5
0
        static void Main(string[] args)
        {
            var mongoServerAddress  = new MongoServerAddress("127.0.0.1", 27017);
            var mongoServerSettings = new MongoServerSettings();

            mongoServerSettings.Server = mongoServerAddress;
            var mongoServer = new MongoServer(mongoServerSettings);

            mongoServer.Connect();
            IEnumerable <string> databases = mongoServer.GetDatabaseNames();
            var mongoDatabase   = mongoServer.GetDatabase("classfrogdb");
            var classCollection = mongoDatabase.GetCollection("classes");

            classCollection.RemoveAll();
            var           documents = classCollection.FindAll();
            ClassInstance instance  = new ClassInstance();

            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            classCollection.Insert(instance.NewDocument());
            mongoServer.Disconnect();
        }
示例#6
0
        public ListRecord()
        {
            InitializeComponent();

            string CONNECTION_STRING = "mongodb://localhost:27017";

            MongoClient client = new MongoClient(CONNECTION_STRING);

#pragma warning disable CS0618                                               // Type or member is obsolete
            MongoServer server = client.GetServer();
#pragma warning restore CS0618                                               // Type or member is obsolete

            IEnumerable <string> databases   = server.GetDatabaseNames();    // here we can get list of all databases on server
            MongoDatabase        db          = server.GetDatabase("deneme"); // but we only need one.
            IEnumerable <string> collections = db.GetCollectionNames();      // get the collection we want to execute the query on.
            var collection = db.GetCollection <BsonDocument>("person");



            var                 jsonQuery = "{start:{ $firstname: malik}}";                                                  //sample json query as text;
            BsonDocument        doc       = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(jsonQuery); // creating bson doc out of the query text.
            QueryDocument       query     = new QueryDocument(doc);                                                          // create query doc out of the bson doc.
            var                 toReturn  = collection.Find(query);                                                          // execute the query - it's linq, nothing is sent to the server yet.
            List <BsonDocument> result    = toReturn.Take(100).ToList();                                                     // now it's here.

            DataTable dt = new DataTable();                                                                                  // Create empty datatable we will fill with data.

            foreach (BsonDocument obj in toReturn)                                                                           // Loop thru all Bson documents returned from the query.
            {
                DataRow dr = dt.NewRow();                                                                                    // Add new row to datatable.
                ExecuteFillDataTable(obj, dt, dr, string.Empty);                                                             // Recursuve method to loop thru al results json.
                dt.Rows.Add(dr);                                                                                             // Add the newly created datarow to the table
            }
        }
示例#7
0
        public ListRecord()
        {
            InitializeComponent();

            string CONNECTION_STRING = "mongodb://localhost:27017";

            MongoClient client = new MongoClient(CONNECTION_STRING);

#pragma warning disable CS0618                                          // Type or member is obsolete
            MongoServer server = client.GetServer();
#pragma warning restore CS0618                                          // Type or member is obsolete

            IEnumerable <string> databases = server.GetDatabaseNames(); // here we can get list of all databases on server

            MongoDatabase db = server.GetDatabase("deneme");            // but we only need one.

            IEnumerable <string> collections = db.GetCollectionNames(); // get the collection we want to execute the query on.

            var collection = db.GetCollection <BsonDocument>("person");

            var jsonQuery = "{start:{ $gte: 1395828292287}}";                                                   //sample json query as text;

            BsonDocument doc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(jsonQuery); // creating bson doc out of the query text.

            QueryDocument query = new QueryDocument(doc);                                                       // create query doc out of the bson doc.

            var toReturn = collection.Find(query);                                                              // execute the query - it's linq, nothing is sent to the server yet.

            List <BsonDocument> result = toReturn.Take(100).ToList();                                           // now it's here.
        }
        public bool InitMongoDB(string connectionString, string connectionString2 = null)
        {
            try
            {
                this.conn = connectionString;
                client    = new MongoClient(conn);
                server    = client.GetServer();
                server.Connect();
                DBNames = server.GetDatabaseNames().ToList();
                if (server.Instance.State != MongoServerState.Connected)
                {
                    //cons .Show("服务器连接失败");
                    Console.WriteLine("mongodb数据库连接失败");
                    return(false);
                }

                if (connectionString2 != null)
                {
                    clientTarget = new MongoClient(connectionString2);
                    serverTarget = clientTarget.GetServer();
                    serverTarget.Connect();
                    DBNamesTarget = serverTarget.GetDatabaseNames().ToList();
                    if (serverTarget.Instance.State != MongoServerState.Connected)
                    {
                        //cons .Show("服务器连接失败");
                        Console.WriteLine("mongodb数据库2连接失败");
                        clientTarget = null;
                    }
                }

                //var xxxx = client.GetDatabase("local");
                database = client.GetDatabase(dbName);



                //database.CreateCollectionAsync("test");
                //xxxx.CreateCollectionAsync("test");
                //var ll = xxxx.GetCollection<Entity>("test");
                //var lx = database.GetCollection<Entity>("test");
                //Entity ee = new Entity() { Name = "JHJ" };
                //ll.InsertOneAsync(ee);
                //lx.InsertOneAsync(ee);
                //var x = ee.Id;
                //ee.Name = "new";
                //ll.InsertOneAsync(ee);
                collection = database.GetCollection <Tiled>("Titles");//数据库表
                this.CollectionList.Add(dbName, collection);
                Console.WriteLine("mongodb数据库连接成功");
                Console.WriteLine(server.Instance.GetServerDescription().ToString());
            }
            catch (Exception)
            {
                Console.WriteLine("mongodb数据库连接失败");
                return(false);
            }


            return(true);
        }
示例#9
0
        /// <summary>
        ///     将数据Opr放入ListView
        /// </summary>
        /// <param name="lstSrvOpr"></param>
        public static void FillCurrentOprToList(ListView lstSrvOpr)
        {
            lstSrvOpr.Clear();
            lstSrvOpr.Columns.Add("Name");
            lstSrvOpr.Columns.Add("opid");
            lstSrvOpr.Columns.Add("active");
            lstSrvOpr.Columns.Add("lockType");
            lstSrvOpr.Columns.Add("waitingForLock");
            lstSrvOpr.Columns.Add("secs_running");
            lstSrvOpr.Columns.Add("op");
            lstSrvOpr.Columns.Add("ns");
            lstSrvOpr.Columns.Add("query");
            lstSrvOpr.Columns.Add("client");
            lstSrvOpr.Columns.Add("desc");
            lstSrvOpr.Columns.Add("connectionId");
            lstSrvOpr.Columns.Add("numYields");

            foreach (String mongoSvrKey in _mongoConnSvrLst.Keys)
            {
                try
                {
                    MongoServer mongoSvr = _mongoConnSvrLst[mongoSvrKey];
                    //感谢 魏琼东 的Bug信息,一些命令必须以Admin执行
                    if (!SystemManager.GetCurrentServerConfig(mongoSvrKey).Health ||
                        !SystemManager.GetCurrentServerConfig(mongoSvrKey).LoginAsAdmin)
                    {
                        continue;
                    }
                    List <String> databaseNameList = mongoSvr.GetDatabaseNames().ToList();
                    foreach (String strDBName in databaseNameList)
                    {
                        try
                        {
                            MongoDatabase mongoDB  = mongoSvr.GetDatabase(strDBName);
                            BsonDocument  dbStatus = mongoDB.GetCurrentOp();
                            BsonArray     doc      = dbStatus.GetValue("inprog").AsBsonArray;
                            foreach (BsonDocument item in doc)
                            {
                                var lst = new ListViewItem(mongoSvrKey + "." + strDBName);
                                foreach (String itemName in item.Names)
                                {
                                    lst.SubItems.Add(item.GetValue(itemName).ToString());
                                }
                                lstSrvOpr.Items.Add(lst);
                            }
                        }
                        catch (Exception ex)
                        {
                            SystemManager.ExceptionDeal(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    SystemManager.ExceptionDeal(ex);
                }
            }
            lstSrvOpr.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
        public void TestDropDatabase()
        {
            if (!_isMasterSlavePair)
            {
                var databaseNamespace = CoreTestConfiguration.GetDatabaseNamespaceForTestFixture();
                var database          = _server.GetDatabase(databaseNamespace.DatabaseName);
                var collection        = database.GetCollection("test");

                collection.Insert(new BsonDocument());
                var databaseNames = _server.GetDatabaseNames();
                Assert.IsTrue(databaseNames.Contains(database.Name));

                _server.DropDatabase(database.Name);
                databaseNames = _server.GetDatabaseNames();
                Assert.IsFalse(databaseNames.Contains(database.Name));
            }
        }
        private void GetDatabases()
        {
            IEnumerable <string> dbs = (_serv.GetDatabaseNames());

            foreach (string db in dbs)
            {
                Children.Add(new DatabaseExplorerDatabaseViewModel(_serv.GetDatabase(db)));
            }
        }
示例#12
0
 /// <summary>
 /// Filling combobox with database names that server stores.
 /// </summary>
 /// <param name="server">MongoDB.Driver.MongoServer instance to connect to.</param>
 private void FillComboboxWithDatabaseNames(MongoServer server)
 {
     cbDatabases.Items.Clear();
     cbDatabases.Items.AddRange(server.GetDatabaseNames().ToArray());
     if (cbDatabases.Items.Count > 0)
     {
         cbDatabases.SelectedIndex = 0;
     }
 }
示例#13
0
 public void Connect()
 {
     mClient = new MongoClient(CONNECTION_STRING);
     mServer = mClient.GetServer();
     foreach (string databaseName in mServer.GetDatabaseNames())
     {
         Console.WriteLine("Found database = {0}", databaseName);
     }
 }
示例#14
0
 /// <summary>
 /// Filling combobox with database names that server stores.
 /// </summary>
 /// <param name="server">MongoDB.Driver.MongoServer instance to connect to.</param>
 private void FillComboboxWithDatabaseNames(MongoServer server)
 {
     cbDatabases.Items.Clear();
     cbDatabases.Items.AddRange(server.GetDatabaseNames().ToArray());
     if(cbDatabases.Items.Count > 0)
     {
         cbDatabases.SelectedIndex = 0;
     }
 }
示例#15
0
        /// <summary>
        /// Tests the connection to the mongod instance at the host
        /// and gets the databases information at the instance
        /// </summary>
        /// <param name="param"></param>
        void testConnection(object param)
        {
            MongoServer server = null;

            try
            {
                if (string.IsNullOrEmpty(_host))
                {
                    throw new Exception("Host name required");
                }
                else if (_port == 0)
                {
                    throw new Exception("Port required");
                }
                else
                {
                    var crediantial = MongoCredential.CreateMongoCRCredential("admin", _dbUserName, _dbPassword);
                    server = new MongoServer(new MongoServerSettings
                    {
                        Server      = new MongoServerAddress(_host, _port),
                        Credentials = new MongoCredential[] { crediantial }
                    });
                    MainVM.Instance.AddToLog(string.Format("Try to connect {0}:{1}", _host, _port));
                    server.Connect();
                    MainVM.Instance.AddToLog("Connection success, getting databases");
                    var databaseNames = server.GetDatabaseNames();
                    if (databaseNames != null)
                    {
                        var databases = databaseNames.Select(d => new DatabaseVM
                        {
                            Name        = d,
                            CreatedDate = DateTime.Now,
                            IsSelected  = true
                        });
                        DataBases = new ObservableCollection <DatabaseVM>(databases);
                        MainVM.Instance.AddToLog(string.Format("{0} database found in the {1}", databaseNames.Count(), _host));
                    }
                    else
                    {
                        MainVM.Instance.AddToLog(string.Format("No database found in the {0}", databaseNames.Count()));
                    }
                }
            }
            catch (Exception ex)
            {
                MainVM.Instance.AddToLog(string.Format("Error in Connection: {0}", ex.Message));
            }
            finally
            {
                if (server != null)
                {
                    server.Disconnect();
                    MainVM.Instance.AddToLog(string.Format("Disconnected to the host: {0}", _host));
                }
            }
        }
示例#16
0
        public List <string> GPGetAppNames(string catname, string subcatname)
        {
            var pre   = string.Format("{0}__{1}__", catname, subcatname);
            var names = serverGeneralPerformance.GetDatabaseNames().Where(n => n.StartsWith(pre)).Select(
                name =>
            {
                var a = name.Substring(pre.Length);
                return(a.Substring(0, a.IndexOf("__")));
            });

            return(names.Distinct().ToList());
        }
 public bool GetSourceDBNames()
 {
     if (server != null && server.Instance.State == MongoServerState.Connected)
     {
         DBNames = server.GetDatabaseNames().ToList();
         if (DBNames != null)
         {
             return(true);
         }
     }
     return(false);
 }
 public bool GetTargetDBNames()
 {
     if (serverTarget != null && serverTarget.Instance.State == MongoServerState.Connected)
     {
         DBNamesTarget = serverTarget.GetDatabaseNames().ToList();
         if (DBNamesTarget != null)
         {
             return(true);
         }
     }
     return(false);
 }
示例#19
0
        public List <string> GetDbNamesForConnection()
        {
            VerifyConnected();
            List <string> dbs = new List <string>();

            foreach (string dbName in _mongoServer.GetDatabaseNames())
            {
                dbs.Add(dbName);
            }

            return(dbs);
        }
示例#20
0
        static void Main(string[] args)
        {
            // Azure Cosmos DB connection string
            string connectionString = "mongodb://*****:*****@7fdb806e-0ee0-4-231-b9ee.documents.azure.com:10255/?ssl=true&replicaSet=globaldb";

            // MongoDB database connection string
            //string connectionString = "mongodb://207.246.126.73:27017";

            string databaseName   = "azuredemo";
            string collectionName = "myCollection";

            var         client = new MongoClient(connectionString);
            MongoServer server = client.GetServer();

            server.Connect();

            var databaseList = server.GetDatabaseNames().ToList();

            MongoDatabase database    = server.GetDatabase(databaseName);
            var           collections = database.GetCollectionNames().ToList();

            if (!collections.Contains(collectionName))
            {
                database.CreateCollection(collectionName);
            }

            // Prepare data
            var sampleData = new Dictionary <string, object>();

            sampleData.Add("Id", "ALFKI");
            sampleData.Add("CompanyName", "Microsoft");
            sampleData.Add("ContactName", "Maria Anders");
            sampleData.Add("ContactTitle", "Sales Representative");
            sampleData.Add("Address", "Obere Str. 57");
            sampleData.Add("City", "Berlin");
            sampleData.Add("PostalCode", "12209");
            sampleData.Add("Country", "Germany");
            sampleData.Add("Phone", "030-0074321");
            sampleData.Add("Fax", "030-0076545");

            // Insert data
            //database.GetCollection(collectionName).Insert(new BsonDocument(sampleData));

            // Read data
            IMongoDatabase database1  = client.GetDatabase(databaseName);
            var            collection = database1.GetCollection <BsonDocument>(collectionName);

            collection.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X));

            Console.WriteLine("Demo completed");
            Console.ReadLine();
            //GetAtlasData();
        }
示例#21
0
 private static bool IsMongoDBReady()
 {
     try
     {
         // use mongo db to test if it is ready
         MongoServer mongo = MongoServer.Create("mongodb://127.0.0.1:10319/?connectTimeoutMS=10000");
         mongo.GetDatabaseNames();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
示例#22
0
        /// <summary>
        /// Connects to the given Mongo server and trims the list of databases and collections based
        /// on what collections actually exist currently in the DB.
        /// </summary>
        /// <param name="mongo">The MongoServer instance to connect to.</param>
        /// <param name="dbMappings">The list of existing DB mappings.</param>
        public static void TrimDatabaseMappings(this MongoServer mongo, Dictionary <String, HashSet <CollectionTypeMapping> > dbMappings)
        {
            HashSet <string> seenDBs = new HashSet <string>();

            //Load up each database by name, retrieving the current collection mappings.
            foreach (string name in mongo.GetDatabaseNames())
            {
                seenDBs.Add(name);

                HashSet <CollectionTypeMapping> mappings = null;
                if (!dbMappings.TryGetValue(name, out mappings))
                {
                    mappings         = new HashSet <CollectionTypeMapping>();
                    dbMappings[name] = mappings;
                }

                var mappingLookup = mappings.ToDictionary(x => x.CollectionName);
                HashSet <string> seenCollections = new HashSet <string>();

                MongoDatabase db = mongo.GetDatabase(name);
                foreach (string collectionName in db.GetCollectionNames())
                {
                    seenCollections.Add(collectionName);

                    CollectionTypeMapping mapping = null;
                    if (!mappingLookup.TryGetValue(collectionName, out mapping))
                    {
                        mapping = new CollectionTypeMapping
                        {
                            CollectionName = collectionName
                        };
                        mappings.Add(mapping);
                    }
                }

                //trim collections that don't exist in the DB
                mappings.RemoveWhere(x => !seenCollections.Contains(x.CollectionName));
            }

            //trim all DB's that don't exist in the connection
            foreach (string dbName in dbMappings.Keys.ToArray())
            {
                if (!seenDBs.Contains(dbName))
                {
                    dbMappings.Remove(dbName);
                }
            }
        }
        public static List <string> GetServerDataBases(MDTServer server)
        {
            List <string> result      = new List <string>();
            MongoClient   client      = new MongoClient(server.ConnectionString);
            MongoServer   mongoserver = client.GetServer();

            try
            {
                result = mongoserver.GetDatabaseNames().ToList();
            }
            catch
            {
            }

            //MongoDatabase database = server.GetDatabase("RUF");
            return(result);
        }
示例#24
0
        public bool InitMongoDB(string connectionString)
        {
            try
            {
                this.con = connectionString;
                client   = new MongoClient(con);
                server   = client.GetServer();
                server.Connect();
                DBNames = server.GetDatabaseNames().ToList();
                if (server.Instance.State != MongoServerState.Connected)
                {
                    Console.WriteLine("mongodb数据库连接失败");
                    return(false);
                }

                Console.WriteLine("mongodb数据库连接成功");
                //Console.WriteLine(server.Instance.GetServerDescription().ToString());
                foreach (string db in DBNames)
                {
                    Console.WriteLine("");
                    Console.WriteLine("DB:  " + db);
                    this.database = this.server.GetDatabase(db);
                    List <string> cols = this.database.GetCollectionNames().ToList();
                    foreach (string col in cols)
                    {
                        Console.WriteLine("\t " + col);
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("mongodb数据库连接失败");
                return(false);
            }


            return(true);
        }
示例#25
0
 static void Main(string[] args)
 {
     var mongoServerAddress = new MongoServerAddress("127.0.0.1", 27017);
     var mongoServerSettings = new MongoServerSettings();
     mongoServerSettings.Server = mongoServerAddress;
     var mongoServer = new MongoServer(mongoServerSettings);
     mongoServer.Connect();
     IEnumerable<string> databases = mongoServer.GetDatabaseNames();
     var mongoDatabase = mongoServer.GetDatabase("classfrogdb");
     var classCollection = mongoDatabase.GetCollection("classes");
     classCollection.RemoveAll();
     var documents = classCollection.FindAll();
     ClassInstance instance = new ClassInstance();
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     classCollection.Insert(instance.NewDocument());
     mongoServer.Disconnect();
 }
示例#26
0
        static void GetAtlasData()
        {
            //MongoClient client = new MongoClient(new MongoClientSettings()
            //{
            //    Server = new MongoServerAddress("207.246.126.73", 27017)
            //});

            MongoClient client = new MongoClient("mongodb://207.246.126.73:27017");
            MongoServer server = client.GetServer();

            server.Connect();
            var databaseList = server.GetDatabaseNames().ToList();

            //db creation

            MongoDatabase database = server.GetDatabase("test1");

            //create collection

            //database.CreateCollection("myCollection");

            //Insert collection

            Dictionary <string, object> dataValue = new Dictionary <string, object>();

            dataValue.Add("Id", "ALFKI");
            dataValue.Add("CompanyName", "Alfreds Futterkiste");
            dataValue.Add("ContactName", "Maria Anders");
            dataValue.Add("ContactTitle", "Sales Representative");
            dataValue.Add("Address", "Obere Str. 57");
            dataValue.Add("City", "Berlin");
            dataValue.Add("PostalCode", "12209");
            dataValue.Add("Country", "Germany");
            dataValue.Add("Phone", "030-0074321");
            dataValue.Add("Fax", "030-0076545");

            //database.GetCollection("myCollection").Insert(new BsonDocument(dataValue));

            IMongoDatabase database1  = client.GetDatabase("test1");
            var            collection = database1.GetCollection <BsonDocument>("myCollection");

            collection.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X));
            var collectionList = database1.ListCollections().ToListAsync().Result.Select(a => a.First()).Select(b => b.Value.ToString()).ToList();
            var cursor         = collection.Find(FilterDefinition <BsonDocument> .Empty).ToCursorAsync();

            cursor.Result.MoveNext();
            List <BsonDocument> resultSet = cursor.Result.Current.ToList();

            ///// Filter operations.

            //IMongoCollection<BsonDocument> myCollection  = database.GetCollection<BsonDocument>("mycollection");
            //AggregateOptions aggregateOptions = new AggregateOptions();
            //aggregateOptions.BatchSize = 10000;
            //IAggregateFluent<BsonDocument> aggregateCollection = myCollection.Aggregate(aggregateOptions);
            //var filterCursor = aggregateCollection.Match(Builders<BsonDocument>.Filter.Eq("Age", 25)).ToCursorAsync();
            //filterCursor.Result.MoveNext();
            //List<BsonDocument> queryResult = filterCursor.Result.Current.ToList();

            //Builders<BsonDocument>.Filter.Eq("Age", 25)
            //Builders<BsonDocument>.Filter.Ne("Age", 25)
            //Builders<BsonDocument>.Filter.Lt("Age", 25)
            //Builders<BsonDocument>.Filter.Lte("Age", 25)
            //Builders<BsonDocument>.Filter.Gt("Age", 25)
            //Builders<BsonDocument>.Filter.Gte("Age", 25)
            //Builders<BsonDocument>.Filter.In("Age", 25)

            Console.WriteLine("Data printed");
            Console.ReadLine();
        }
示例#27
0
        public bool Connected()
        {
            string msString = sPreMs + Server;
            ms = MongoServer.Create(msString);

            ms.Connect();
            //while (true)
            //{
            //    if (ms.State!= MongoServerState.Connecting)
            //    {
            //        break;
            //    }
            //    System.Threading.Thread.Sleep(1000);
            //}
            if (ms.State == MongoServerState.Connected)
            {
                 foreach(string s in ms.GetDatabaseNames())
                 {
                     Dbs.Add(ms.GetDatabase(s));
                 }

                return true;
            }
            return false;
        }
 /// <summary>
 /// 获取实例节点
 /// </summary>
 /// <param name="mongoConnKey"></param>
 /// <param name="config">由于是结构体,必须ref</param>
 /// <param name="mongoConn"></param>
 /// <param name="mMasterServerInstace"></param>
 /// <param name="mServer"></param>
 /// <param name="UserList"></param>
 /// <returns></returns>
 private static TreeNode GetInstanceNode(String mongoConnKey,
                                         ref ConfigHelper.MongoConnectionConfig config,
                                         MongoServer mongoConn,
                                         MongoServerInstance mMasterServerInstace,
                                         MongoServer mServer,
                                         EachDatabaseUser UserList)
 {
     Boolean isReplsetMasterServer = false;
     //无论如何,都改为主要服务器读优先
     if (mMasterServerInstace == null)
     {
         isReplsetMasterServer = true;
     }
     TreeNode SvrInstanceNode = new TreeNode();
     String ConnSvrKey;
     if (isReplsetMasterServer)
     {
         ConnSvrKey = mongoConnKey + "/" + mongoConnKey;
     }
     else
     {
         ConnSvrKey = mongoConnKey + "/" + mMasterServerInstace.Address.ToString().Replace(":", "@");
     }
     SvrInstanceNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.WebServer;
     SvrInstanceNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.WebServer;
     if (isReplsetMasterServer)
     {
         SvrInstanceNode.Text = "Connection";
     }
     else
     {
         SvrInstanceNode.Text = "Server[" + mMasterServerInstace.Address.ToString() + "]";
     }
     if ((!String.IsNullOrEmpty(config.UserName)) & (!String.IsNullOrEmpty(config.Password)))
     {
         //是否是认证模式,应该取决于服务器!
         config.AuthMode = true;
     }
     //获取ReadOnly
     config.IsReadOnly = false;
     List<String> databaseNameList = new List<String>();
     if (!String.IsNullOrEmpty(config.DataBaseName))
     {
         //单数据库模式
         TreeNode mongoSingleDBNode;
         if (isReplsetMasterServer)
         {
             mongoSingleDBNode = FillDataBaseInfoToTreeNode(config.DataBaseName, mServer, mongoConnKey + "/" + mongoConnKey);
         }
         else
         {
             mongoSingleDBNode = FillDataBaseInfoToTreeNode(config.DataBaseName, mServer, mongoConnKey + "/" + mMasterServerInstace.Address.ToString());
         }
         mongoSingleDBNode.Tag = SINGLE_DATABASE_TAG + ":" + ConnSvrKey + "/" + config.DataBaseName;
         mongoSingleDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
         mongoSingleDBNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
         SvrInstanceNode.Nodes.Add(mongoSingleDBNode);
         SvrInstanceNode.Tag = SINGLE_DB_SERVER_TAG + ":" + ConnSvrKey;
         ///获取User信息
         if (config.AuthMode)
         {
             try
             {
                 ///尝试添加用户信息
                 UserList.AddUser(mongoConn.GetDatabase(config.DataBaseName), config.UserName);
             }
             catch (Exception)
             {
                 //可能出现没有权限的问题,这里就认为无法取得权限
             }
         }
     }
     else
     {
         MongoServer InstantSrv;
         if (isReplsetMasterServer)
         {
             InstantSrv = mServer;
             databaseNameList = mServer.GetDatabaseNames().ToList<String>();
         }
         else
         {
             MongoClientSettings setting = CreateMongoClientSettingsByConfig(ref config);
             setting.ConnectionMode = ConnectionMode.Direct;
             //When Replset Case,Application need to read admin DB information
             //if Primary,there will be exception
             setting.ReadPreference = ReadPreference.PrimaryPreferred;
             setting.Server = mMasterServerInstace.Address;
             InstantSrv = new MongoClient(setting).GetServer();
             databaseNameList = InstantSrv.GetDatabaseNames().ToList<String>();
         }
         foreach (String strDBName in databaseNameList)
         {
             TreeNode mongoDBNode;
             try
             {
                 mongoDBNode = FillDataBaseInfoToTreeNode(strDBName, InstantSrv, ConnSvrKey);
                 mongoDBNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 mongoDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 SvrInstanceNode.Nodes.Add(mongoDBNode);
                 if (config.AuthMode)
                 {
                     try
                     {
                         ///尝试添加用户信息
                         UserList.AddUser(mongoConn.GetDatabase(strDBName), config.UserName);
                     }
                     catch (Exception)
                     {
                         //可能出现没有权限的问题,这里就认为无法取得权限
                     }
                 }
             }
             catch (Exception ex)
             {
                 SystemManager.ExceptionDeal(ex, strDBName + "Exception", strDBName + "Exception");
                 mongoDBNode = new TreeNode(strDBName + " (Exception)");
                 mongoDBNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 mongoDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 SvrInstanceNode.Nodes.Add(mongoDBNode);
             }
         }
         if (isReplsetMasterServer)
         {
             SvrInstanceNode.Tag = SERVER_TAG + ":" + mongoConnKey + "/" + mongoConnKey;
         }
         else
         {
             if (mongoConn.ReplicaSetName != null)
             {
                 SvrInstanceNode.Tag = SERVER_REPLSET_MEMBER_TAG + ":" + mongoConnKey + "/" + mMasterServerInstace.Address.ToString().Replace(":", "@");
             }
         }
     }
     if (_mongoInstanceLst.ContainsKey(ConnSvrKey))
     {
         _mongoInstanceLst.Remove(ConnSvrKey);
     }
     if (!isReplsetMasterServer)
     {
         _mongoInstanceLst.Add(ConnSvrKey, mMasterServerInstace);
     }
     return SvrInstanceNode;
 }
示例#29
0
 /// <summary>
 /// Fill Database status to ListView
 /// </summary>
 /// <param name="lstSvr"></param>
 public static void FillDataBaseStatusToList(ListView lstSvr)
 {
     lstSvr.Clear();
     if (SystemManager.IsUseDefaultLanguage)
     {
         lstSvr.Columns.Add("DataBaseName");
         lstSvr.Columns.Add("CollectionCount");
         lstSvr.Columns.Add("DataSize");
         lstSvr.Columns.Add("FileSize");
         lstSvr.Columns.Add("IndexCount");
         lstSvr.Columns.Add("IndexSize");
         lstSvr.Columns.Add("ObjectCount");
         lstSvr.Columns.Add("StorageSize");
     }
     else
     {
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_DataBaseName));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_CollectionCount));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_DataSize));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_FileSize));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_IndexCount));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_IndexSize));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_ObjectCount));
         lstSvr.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.DataBase_Status_StorageSize));
     }
     foreach (String mongoSvrKey in _mongoConnSvrLst.Keys)
     {
         try
         {
             MongoServer mongoSvr = _mongoConnSvrLst[mongoSvrKey];
             //感谢 魏琼东 的Bug信息,一些命令必须以Admin执行
             if (!SystemManager.GetCurrentServerConfig(mongoSvrKey).Health ||
                 !SystemManager.GetCurrentServerConfig(mongoSvrKey).LoginAsAdmin)
             {
                 continue;
             }
             List <String> databaseNameList = mongoSvr.GetDatabaseNames().ToList <String>();
             foreach (String strDBName in databaseNameList)
             {
                 MongoDatabase       mongoDB  = mongoSvr.GetDatabase(strDBName);
                 DatabaseStatsResult dbStatus = mongoDB.GetStats();
                 ListViewItem        lst      = new ListViewItem(mongoSvrKey + "." + strDBName);
                 try
                 {
                     lst.SubItems.Add(dbStatus.CollectionCount.ToString());
                 }
                 catch (Exception)
                 {
                     lst.SubItems.Add("0");
                 }
                 lst.SubItems.Add(GetSize(dbStatus.DataSize));
                 lst.SubItems.Add(GetSize(dbStatus.FileSize));
                 lst.SubItems.Add(dbStatus.IndexCount.ToString());
                 lst.SubItems.Add(GetSize(dbStatus.IndexSize));
                 lst.SubItems.Add(dbStatus.ObjectCount.ToString());
                 lst.SubItems.Add(GetSize(dbStatus.StorageSize));
                 lstSvr.Items.Add(lst);
             }
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
示例#30
0
        /// <summary>
        /// fill Collection status to ListView
        /// </summary>
        /// <param name="lstData"></param>
        public static void FillCollectionStatusToList(ListView lstData)
        {
            lstData.Clear();

            if (SystemManager.IsUseDefaultLanguage)
            {
                lstData.Columns.Add("CollectionName");
                lstData.Columns.Add("ObjectCount");
                lstData.Columns.Add("DataSize");
                lstData.Columns.Add("LastExtentSize");
                lstData.Columns.Add("StorageSize");
                lstData.Columns.Add("TotalIndexSize");

                //2012-3-6
                lstData.Columns.Add("IsCapped");
                lstData.Columns.Add("MaxDocuments");

                lstData.Columns.Add("AverageObjectSize");
                lstData.Columns.Add("PaddingFactor");
            }
            else
            {
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_CollectionName));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_ObjectCount));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_DataSize));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_LastExtentSize));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_StorageSize));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_TotalIndexSize));

                //2012-3-6
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_IsCapped));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_MaxDocuments));


                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_AverageObjectSize));
                lstData.Columns.Add(SystemManager.mStringResource.GetText(StringResource.TextType.Collection_Status_PaddingFactor));
            }
            foreach (String mongoSvrKey in _mongoConnSvrLst.Keys)
            {
                try
                {
                    MongoServer mongoSvr = _mongoConnSvrLst[mongoSvrKey];
                    //感谢 魏琼东 的Bug信息,一些命令必须以Admin执行
                    if (!SystemManager.GetCurrentServerConfig(mongoSvrKey).Health ||
                        !SystemManager.GetCurrentServerConfig(mongoSvrKey).LoginAsAdmin)
                    {
                        continue;
                    }
                    List <String> databaseNameList = mongoSvr.GetDatabaseNames().ToList <String>();
                    foreach (String strDBName in databaseNameList)
                    {
                        MongoDatabase mongoDB = mongoSvr.GetDatabase(strDBName);

                        List <String> colNameList = mongoDB.GetCollectionNames().ToList <String>();
                        foreach (String strColName in colNameList)
                        {
                            try
                            {
                                CollectionStatsResult CollectionStatus = mongoDB.GetCollection(strColName).GetStats();
                                ListViewItem          lst = new ListViewItem(mongoSvrKey + "." + strDBName + "." + strColName);
                                lst.SubItems.Add(CollectionStatus.ObjectCount.ToString());
                                lst.SubItems.Add(GetSize(CollectionStatus.DataSize));
                                lst.SubItems.Add(GetSize(CollectionStatus.LastExtentSize));
                                lst.SubItems.Add(GetSize(CollectionStatus.StorageSize));
                                lst.SubItems.Add(GetSize(CollectionStatus.TotalIndexSize));

                                //2012-3-6
                                lst.SubItems.Add(CollectionStatus.IsCapped.ToString());
                                lst.SubItems.Add(CollectionStatus.MaxDocuments.ToString());

                                if (CollectionStatus.ObjectCount != 0)
                                {
                                    //在某些条件下,这个值会抛出异常,IndexKeyNotFound
                                    //同时发现,这个时候Count = 0,TryCatch可能会消耗时间,所以改为条件判断
                                    lst.SubItems.Add(GetSize((long)CollectionStatus.AverageObjectSize));
                                }
                                else
                                {
                                    lst.SubItems.Add("0");
                                }

                                try
                                {
                                    //在某些条件下,这个值会抛出异常,IndexKeyNotFound
                                    lst.SubItems.Add(CollectionStatus.PaddingFactor.ToString());
                                }
                                catch (Exception)
                                {
                                    lst.SubItems.Add("0");
                                }
                                lstData.Items.Add(lst);
                            }
                            catch (Exception)
                            {
                                //throw;
                                //TODO:排序时候会发生错误,所以暂时不对应
                                //lstData.Items.Add(new ListViewItem(strColName + "[Exception]"));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
示例#31
0
        static IEnumerable <Tuple <MongoDatabase, MongoDatabase> > ListDatabases(MongoServer sourceServer, MongoServer targetServer, List <string> sourceDatabases, List <string> targetDatabases)
        {
            if (sourceDatabases == null)
            {
                yield break;
            }
            if (targetDatabases == null || targetDatabases.Count == 0)
            {
                targetDatabases = null;
            }

            // check if we are on the same server!
            bool sameServer = ServersAreEqual(sourceServer, targetServer);

            // prepare available databases list
            var databases          = sourceServer.GetDatabaseNames().ToList();
            var availableDatabases = new HashSet <string> (databases, StringComparer.Ordinal);

            // create mappings
            if (targetDatabases == null)
            {
                for (int i = 0; i < sourceDatabases.Count; i++)
                {
                    string k = sourceDatabases[i];
                    if (k.IndexOf('=') > 0)
                    {
                        var split = k.Split('=');
                        k = split[0];
                        var db = availableDatabases.Contains(k) ? k : databases.FirstOrDefault(name => k.Equals(name, StringComparison.OrdinalIgnoreCase));
                        // check if database was found
                        if (String.IsNullOrEmpty(db) || String.IsNullOrEmpty(split[1]))
                        {
                            continue;
                        }
                        yield return(Tuple.Create(sourceServer.GetDatabase(db), targetServer.GetDatabase(split[1])));
                    }
                    else
                    {
                        foreach (var db in databases.Where(name => SharedMethods.WildcardIsMatch(k, name, true)))
                        {
                            yield return(Tuple.Create(sourceServer.GetDatabase(db), targetServer.GetDatabase(db)));
                        }
                    }
                }
            }
            else
            {
                // match
                for (int i = 0; i < sourceDatabases.Count; i++)
                {
                    string k  = sourceDatabases[i];
                    var    db = availableDatabases.Contains(k) ? k : databases.FirstOrDefault(name => k.Equals(name, StringComparison.OrdinalIgnoreCase));
                    // check if database was found
                    if (String.IsNullOrEmpty(db) || String.IsNullOrEmpty(targetDatabases[i]))
                    {
                        continue;
                    }
                    yield return(Tuple.Create(sourceServer.GetDatabase(db), targetServer.GetDatabase(targetDatabases[i])));
                }
            }
        }
        /// <summary>
        ///     获取实例节点
        /// </summary>
        /// <param name="mongoConnKey"></param>
        /// <param name="config">由于是结构体,必须ref</param>
        /// <param name="mongoConn"></param>
        /// <param name="mMasterServerInstace"></param>
        /// <param name="mServer"></param>
        /// <param name="UserList"></param>
        /// <returns></returns>
        private static TreeNode GetInstanceNode(String mongoConnKey,
                                                ref ConfigHelper.MongoConnectionConfig config,
                                                MongoServer mongoConn,
                                                MongoServerInstance mMasterServerInstace,
                                                MongoServer mServer,
                                                EachDatabaseUser UserList)
        {
            bool isReplsetMasterServer = mMasterServerInstace == null;
            //无论如何,都改为主要服务器读优先
            var    svrInstanceNode = new TreeNode();
            String connSvrKey;

            connSvrKey = isReplsetMasterServer
                ? mongoConnKey + "/" + mongoConnKey
                : mongoConnKey + "/" + mMasterServerInstace.Address.ToString().Replace(":", "@");
            svrInstanceNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.WebServer;
            svrInstanceNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.WebServer;
            svrInstanceNode.Text = isReplsetMasterServer ? "Connection" : "Server[" + mMasterServerInstace.Address + "]";
            if (!String.IsNullOrEmpty(config.UserName) & (!String.IsNullOrEmpty(config.Password)))
            {
                //是否是认证模式,应该取决于服务器!
                config.AuthMode = true;
            }
            //获取ReadOnly
            config.IsReadOnly = false;
            List <string> databaseNameList;

            if (!String.IsNullOrEmpty(config.DataBaseName))
            {
                //单数据库模式
                TreeNode mongoSingleDbNode;
                mongoSingleDbNode = isReplsetMasterServer
                    ? FillDataBaseInfoToTreeNode(config.DataBaseName, mServer,
                                                 mongoConnKey + "/" + mongoConnKey)
                    : FillDataBaseInfoToTreeNode(config.DataBaseName, mServer,
                                                 mongoConnKey + "/" + mMasterServerInstace.Address);
                mongoSingleDbNode.Tag = MongoDbHelper.SINGLE_DATABASE_TAG + ":" + connSvrKey + "/" + config.DataBaseName;
                mongoSingleDbNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                mongoSingleDbNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database;
                svrInstanceNode.Nodes.Add(mongoSingleDbNode);
                svrInstanceNode.Tag = MongoDbHelper.SINGLE_DB_SERVER_TAG + ":" + connSvrKey;
                //获取User信息
                if (config.AuthMode)
                {
                    try
                    {
                        //尝试添加用户信息
                        UserList.AddUser(mongoConn.GetDatabase(config.DataBaseName), config.UserName);
                    }
                    catch
                    {
                        //可能出现没有权限的问题,这里就认为无法取得权限
                    }
                }
            }
            else
            {
                MongoServer instantSrv;
                if (isReplsetMasterServer)
                {
                    instantSrv       = mServer;
                    databaseNameList = mServer.GetDatabaseNames().ToList();
                }
                else
                {
                    MongoClientSettings setting = MongoDbHelper.CreateMongoClientSettingsByConfig(ref config);
                    setting.ConnectionMode = ConnectionMode.Direct;
                    //When Replset Case,Application need to read admin DB information
                    //if Primary,there will be exception
                    setting.ReadPreference = ReadPreference.PrimaryPreferred;
                    setting.Server         = mMasterServerInstace.Address;
                    instantSrv             = new MongoClient(setting).GetServer();
                    databaseNameList       = instantSrv.GetDatabaseNames().ToList();
                }
                foreach (String strDbName in databaseNameList)
                {
                    TreeNode mongoDbNode;
                    try
                    {
                        mongoDbNode                    = FillDataBaseInfoToTreeNode(strDbName, instantSrv, connSvrKey);
                        mongoDbNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database;
                        mongoDbNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                        svrInstanceNode.Nodes.Add(mongoDbNode);
                        if (config.AuthMode)
                        {
                            try
                            {
                                //尝试添加用户信息
                                UserList.AddUser(mongoConn.GetDatabase(strDbName), config.UserName);
                            }
                            catch
                            {
                                //可能出现没有权限的问题,这里就认为无法取得权限
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        SystemManager.ExceptionDeal(ex, strDbName + "Exception", strDbName + "Exception");
                        mongoDbNode = new TreeNode(strDbName + " (Exception)")
                        {
                            ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database,
                            SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database
                        };
                        svrInstanceNode.Nodes.Add(mongoDbNode);
                    }
                }
                if (isReplsetMasterServer)
                {
                    svrInstanceNode.Tag = MongoDbHelper.SERVER_TAG + ":" + mongoConnKey + "/" + mongoConnKey;
                }
                else
                {
                    if (mongoConn.ReplicaSetName != null)
                    {
                        svrInstanceNode.Tag = MongoDbHelper.SERVER_REPLSET_MEMBER_TAG + ":" + mongoConnKey + "/" +
                                              mMasterServerInstace.Address.ToString().Replace(":", "@");
                    }
                }
            }
            if (MongoDbHelper._mongoInstanceLst.ContainsKey(connSvrKey))
            {
                MongoDbHelper._mongoInstanceLst.Remove(connSvrKey);
            }
            if (!isReplsetMasterServer)
            {
                MongoDbHelper._mongoInstanceLst.Add(connSvrKey, mMasterServerInstace);
            }
            return(svrInstanceNode);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="mongoConnKey"></param>
 /// <param name="config"></param>
 /// <param name="mongoConn"></param>
 /// <param name="mServerInstace"></param>
 /// <param name="mServer"></param>
 /// <returns></returns>
 private static TreeNode GetInstanceNode(String mongoConnKey, ConfigHelper.MongoConnectionConfig config,
                                         MongoServer mongoConn, MongoServerInstance mServerInstace, MongoServer mServer)
 {
     Boolean isServer = false;
     if (mServerInstace == null)
     {
         isServer = true;
     }
     TreeNode SvrInstanceNode = new TreeNode();
     String ConnSvrKey;
     if (isServer)
     {
         ConnSvrKey = mongoConnKey + "/" + mongoConnKey;
     }
     else
     {
         ConnSvrKey = mongoConnKey + "/" + mServerInstace.Address.ToString().Replace(":", "@");
     }
     SvrInstanceNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.WebServer;
     SvrInstanceNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.WebServer;
     if (isServer)
     {
         SvrInstanceNode.Text = "Connection";
     }
     else
     {
         SvrInstanceNode.Text = "Server[" + mServerInstace.Address.ToString() + "]";
     }
     if ((!String.IsNullOrEmpty(config.UserName)) & (!String.IsNullOrEmpty(config.Password)))
     {
         config.AuthMode = true;
     }
     //获取ReadOnly
     config.IsReadOnly = false;
     List<String> databaseNameList = new List<String>();
     if (!String.IsNullOrEmpty(config.DataBaseName))
     {
         //单数据库模式
         TreeNode mongoSingleDBNode;
         if (isServer)
         {
             mongoSingleDBNode = FillDataBaseInfoToTreeNode(config.DataBaseName, mServer, mongoConnKey + "/" + mongoConnKey);
         }
         else
         {
             mongoSingleDBNode = FillDataBaseInfoToTreeNode(config.DataBaseName, mServerInstace.Server, mongoConnKey + "/" + mServerInstace.Address.ToString());
         }
         mongoSingleDBNode.Tag = SINGLE_DATABASE_TAG + ":" + ConnSvrKey + "/" + config.DataBaseName;
         mongoSingleDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
         mongoSingleDBNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
         SvrInstanceNode.Nodes.Add(mongoSingleDBNode);
         SvrInstanceNode.Tag = SINGLE_DB_SERVER_TAG + ":" + ConnSvrKey;
         if (config.AuthMode)
         {
             config.IsReadOnly = mongoConn.GetDatabase(config.DataBaseName).FindUser(config.UserName).IsReadOnly;
         }
     }
     else
     {
         MongoServer InstantSrv;
         if (isServer)
         {
             InstantSrv = mServer;
             databaseNameList = mServer.GetDatabaseNames().ToList<String>();
         }
         else
         {
             MongoServerSettings setting = mongoConn.Settings.Clone();
             setting.ConnectionMode = ConnectionMode.Direct;
             //When Replset Case,Application need to read admin DB information
             //if Primary,there will be exception
             setting.ReadPreference = ReadPreference.PrimaryPreferred;
             setting.Server = mServerInstace.Address;
             InstantSrv = new MongoServer(setting);
             databaseNameList = InstantSrv.GetDatabaseNames().ToList<String>();
         }
         foreach (String strDBName in databaseNameList)
         {
             TreeNode mongoDBNode;
             try
             {
                 mongoDBNode = FillDataBaseInfoToTreeNode(strDBName, InstantSrv, ConnSvrKey);
                 mongoDBNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 mongoDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 SvrInstanceNode.Nodes.Add(mongoDBNode);
                 if (strDBName == MongoDBHelper.DATABASE_NAME_ADMIN)
                 {
                     if (config.AuthMode)
                     {
                         config.IsReadOnly = mongoConn.GetDatabase(strDBName).FindUser(config.UserName).IsReadOnly;
                     }
                 }
             }
             catch (Exception ex)
             {
                 MyMessageBox.ShowMessage(strDBName + "Exception", strDBName + "Exception", ex.ToString());
                 mongoDBNode = new TreeNode(strDBName + " (Exception)");
                 mongoDBNode.ImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 mongoDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                 SvrInstanceNode.Nodes.Add(mongoDBNode);
             }
         }
         if (isServer)
         {
             SvrInstanceNode.Tag = SERVER_TAG + ":" + mongoConnKey + "/" + mongoConnKey;
         }
         else
         {
             if (mongoConn.ReplicaSetName != null)
             {
                 SvrInstanceNode.Tag = SERVER_REPLSET_MEMBER_TAG + ":" + mongoConnKey + "/" + mServerInstace.Address.ToString().Replace(":", "@");
             }
         }
     }
     if (_mongoInstanceLst.ContainsKey(ConnSvrKey))
     {
         _mongoInstanceLst.Remove(ConnSvrKey);
     }
     if (!isServer)
     {
         _mongoInstanceLst.Add(ConnSvrKey, mServerInstace);
     }
     return SvrInstanceNode;
 }
示例#34
0
 public IEnumerable <string> getDatabases()
 {
     return(_server.GetDatabaseNames());
 }
示例#35
0
        /// <summary>
        ///     fill Collection status to ListView
        /// </summary>
        /// <param name="lstData"></param>
        public static void FillCollectionStatusToList(ListView lstData)
        {
            lstData.Clear();

            if (SystemManager.IsUseDefaultLanguage)
            {
                lstData.Columns.Add("CollectionName");
                lstData.Columns.Add("ObjectCount");
                lstData.Columns.Add("DataSize");
                lstData.Columns.Add("LastExtentSize");
                lstData.Columns.Add("StorageSize");
                lstData.Columns.Add("TotalIndexSize");

                //2012-3-6
                lstData.Columns.Add("IsCapped");
                lstData.Columns.Add("MaxDocuments");

                lstData.Columns.Add("AverageObjectSize");
                lstData.Columns.Add("PaddingFactor");
            }
            else
            {
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_CollectionName));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_ObjectCount));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_DataSize));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_LastExtentSize));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_StorageSize));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_TotalIndexSize));

                //2012-3-6
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_IsCapped));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_MaxDocuments));


                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_AverageObjectSize));
                lstData.Columns.Add(
                    SystemManager.MStringResource.GetText(StringResource.TextType.Collection_Status_PaddingFactor));
            }
            foreach (String mongoSvrKey in _mongoConnSvrLst.Keys)
            {
                try
                {
                    MongoServer mongoSvr = _mongoConnSvrLst[mongoSvrKey];
                    //感谢 魏琼东 的Bug信息,一些命令必须以Admin执行
                    if (!SystemManager.GetCurrentServerConfig(mongoSvrKey).Health ||
                        !SystemManager.GetCurrentServerConfig(mongoSvrKey).LoginAsAdmin)
                    {
                        continue;
                    }
                    List <String> databaseNameList = mongoSvr.GetDatabaseNames().ToList();
                    foreach (String strDBName in databaseNameList)
                    {
                        MongoDatabase mongoDB = mongoSvr.GetDatabase(strDBName);

                        List <String> colNameList = mongoDB.GetCollectionNames().ToList();
                        foreach (String strColName in colNameList)
                        {
                            try
                            {
                                CollectionStatsResult CollectionStatus = mongoDB.GetCollection(strColName).GetStats();
                                var lst = new ListViewItem(mongoSvrKey + "." + strDBName + "." + strColName);
                                lst.SubItems.Add(CollectionStatus.ObjectCount.ToString());
                                lst.SubItems.Add(GetSize(CollectionStatus.DataSize));
                                lst.SubItems.Add(GetSize(CollectionStatus.LastExtentSize));
                                lst.SubItems.Add(GetSize(CollectionStatus.StorageSize));
                                lst.SubItems.Add(GetSize(CollectionStatus.TotalIndexSize));

                                //2012-3-6
                                lst.SubItems.Add(CollectionStatus.IsCapped.ToString());
                                //https://jira.mongodb.org/browse/CSHARP-665
                                try
                                {
                                    //注意:这个MaxDocuments只是在CappedCollection时候有效
                                    lst.SubItems.Add(CollectionStatus.MaxDocuments.ToString());
                                }
                                catch (Exception ex)
                                {
                                    //溢出
                                    lst.SubItems.Add(Int32.MaxValue.ToString());
                                    SystemManager.ExceptionLog(ex);
                                }

                                lst.SubItems.Add(CollectionStatus.ObjectCount != 0
                                    ? GetSize((long)CollectionStatus.AverageObjectSize)
                                    : "0");

                                try
                                {
                                    //在某些条件下,这个值会抛出异常,IndexKeyNotFound
                                    lst.SubItems.Add(CollectionStatus.PaddingFactor.ToString());
                                }
                                catch (Exception)
                                {
                                    lst.SubItems.Add("0");
                                }
                                lstData.Items.Add(lst);
                            }
                            catch (Exception ex)
                            {
                                //throw;
                                //TODO:排序时候会发生错误,所以暂时不对应
                                //lstData.Items.Add(new ListViewItem(strColName + "[Exception]"));
                                SystemManager.ExceptionDeal(ex);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    SystemManager.ExceptionDeal(ex);
                }
            }
            lstData.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }