Connect() public method

public Connect ( ) : System.Boolean
return System.Boolean
        public IList<string> GetCollections(string server, string database, string port)
        {
            _db = new Mongo(string.Format("Server={0}:{1}", server, port));

            try
            {
                _db.Connect();
            }
            catch (SocketException ex)
            {
                throw new UnknownServerException(string.Format("Unknown server: {0}:{1}", server, port), ex);
            }

            IList<String> collectionNames = _db[database].GetCollectionNames();
            var filteredCollections = new List<string>();
            var hiddenCollectionCriteria = new string[] {"cubicle", "tmp.", ".$", "system.indexes"};

            foreach (string collectionName in collectionNames)
            {
                if (!hiddenCollectionCriteria.Any(criteria => collectionName.Contains(criteria)))
                {
                    int periodIndex = collectionName.IndexOf(".");
                    string collection = collectionName;

                    if (periodIndex >= 0 && periodIndex != (collectionName.Length - 1))
                        collection = collectionName.Substring(collectionName.IndexOf(".") + 1);

                    filteredCollections.Add(collection);
                }
            }

            return filteredCollections;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create a Nut for a specific application account and in a specific configuration container.
        /// </summary>
        /// <param name="account">The application account we are creating the nut for.</param>
        /// <param name="container">The container we are inserting the nut into (e.g. connectionstrings, endpoints, appconfig, etc).</param>
        /// <param name="nut">Busta nut.</param>
        /// <returns>True if the nut was added and false if it already exists, and therefore was not added/updated.</returns>
        public static bool CreateNut(string account, string container, Nut nut)
        {
            bool nutAdded = false;

            Mongo mongo = new Mongo();
            mongo.Connect();

            var db = mongo.GetDatabase(WellKnownDb.AppConfiguration);

            var collection = db.GetCollection(container);

            var doc = new Document();

            doc["account"] = account;
            doc["name"] = nut.Key;
            doc["value"] = nut.Value;

            if (nut.Properties != null)
            {
                foreach (var k in nut.Properties.Keys)
                {
                    doc.Add(k, nut.Properties[k]);
                }
            }

            if (collection.FindOne(doc) == null)
            {
                collection.Insert(doc);
                nutAdded = true;
            }

            return nutAdded;
        }
        public void ShouldReturnCollectionsFromDatabase()
        {
            //Given
            Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017"));
            db.Connect();
            IMongoCollection collection = db["test"]["folks"];
            Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } };
            Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            collection.Insert(doc1);
            collection.Insert(doc2);
            collection.Insert(doc3);
            var queryProvider = new MongoDbCSharpQuery();

            try
            {
                //When
                IList<string> collections = queryProvider.GetCollections("localhost", "test", "27017");

                //Then
                Assert.IsNotNull(collections.Where(c => c == "folks").SingleOrDefault());
            }
            finally
            {
                //Clean Up
                collection.Delete(doc1);
                collection.Delete(doc2);
                collection.Delete(doc3);
                queryProvider.Dispose();
            }
        }
        public void ShouldReturnAllDataFromCollection()
        {
            //Given
            Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017"));
            db.Connect();
            IMongoCollection collection = db["test"]["folks"];
            Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } };
            Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            collection.Insert(doc1);
            collection.Insert(doc2);
            collection.Insert(doc3);
            var queryProvider = new MongoDbCSharpQuery();

            try
            {
                //When
                IEnumerable data = queryProvider.RunQuery("localhost", "test", "27017", "folks");

                int numberOfRows = 0;
                foreach (var row in data) numberOfRows++;

                //Then
                Assert.AreEqual(3, numberOfRows);
            }
            finally
            {
                //Clean Up
                collection.Delete(doc1);
                collection.Delete(doc2);
                collection.Delete(doc3);
                queryProvider.Dispose();
            }
        }
 public void Connect()
 {
     using (Mongo mongo = new Mongo("Server=10.98.0.241:27017"))
     {
         mongo.Connect();
     }
 }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            SetupDocuments();

            Mongo m = new Mongo();
            m.Connect();
            Database db = m["benchmark"];

            db.MetaData.DropDatabase();
            Console.WriteLine("Starting Tests");

            RunEncodeTest("encode (small)",small);
            RunEncodeTest("encode (medium)", medium);
            RunEncodeTest("encode (large)", large);

            RunDecodeTest("decode (small)",small);
            RunDecodeTest("decode (medium)", medium);
            RunDecodeTest("decode (large)", large);

            db.MetaData.DropDatabase();
            RunInsertTest("insert (small, no index)", db, "small_none",small,false,false);
            RunInsertTest("insert (medium, no index)", db, "medium_none",medium,false,false);
            RunInsertTest("insert (large, no index)", db, "large_none",large,false,false);

            RunInsertTest("insert (small, indexed)", db, "small_index",small,true,false);
            RunInsertTest("insert (medium, indexed)", db, "medium_index",medium,true,false);
            RunInsertTest("insert (large, indexed)", db, "large_index",large,true,false);

            RunInsertTest("batch insert (small, no index)", db, "small_bulk",small,false,true);
            RunInsertTest("batch insert (medium, no index)", db, "medium_bulk",medium,false,true);
            RunInsertTest("batch insert (large, no index)", db, "large_bulk",large,false,true);

            Document fonespec = new Document().Append("x",perTrial/2);
            RunFindTest("find_one (small, no index)", db, "small_none",fonespec,false);
            RunFindTest("find_one (medium, no index)", db, "medium_none",fonespec,false);
            RunFindTest("find_one (large, no index)", db, "large_none",fonespec,false);

            RunFindTest("find_one (small, indexed)", db, "small_index",fonespec,false);
            RunFindTest("find_one (medium, indexed)", db, "medium_index",fonespec,false);
            RunFindTest("find_one (large, indexed)", db, "large_index",fonespec,false);

            RunFindTest("find (small, no index)", db, "small_none",fonespec,true);
            RunFindTest("find (medium, no index)", db, "medium_none",fonespec,true);
            RunFindTest("find (large, no index)", db, "large_none",fonespec,true);

            RunFindTest("find (small, indexed)", db, "small_index",fonespec,true);
            RunFindTest("find (medium, indexed)", db, "medium_index",fonespec,true);
            RunFindTest("find (large, indexed)", db, "large_index",fonespec,true);

            Document findRange = new Document().Append("x",new Document().Append("$gt",perTrial/2).Append("$lt", perTrial/2 + batchSize));
            RunFindTest("find range (small, indexed)", db, "small_index",findRange,true);
            RunFindTest("find range (medium, indexed)", db, "medium_index",findRange,true);
            RunFindTest("find range (large, indexed)", db, "large_index",findRange,true);

            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();
        }
Ejemplo n.º 7
0
        public void FavoriteUpdate_Multiple()
        {
            string connstr = ConfigurationManager.AppSettings["mongoDBTest"];
            var mongo = new Mongo(connstr);
            mongo.Connect();

            var testDB = mongo.GetDatabase("myTest");
            UserFavorite fav = new UserFavorite(testDB, "lynn");

            fav.Update("q", 1, "t1,t2,t2");
        }
Ejemplo n.º 8
0
 public void Initialize()
 {
     should_not_already_be_initialized();
     lock (_syncRoot)
     {
         should_not_already_be_initialized();
         _mongo = new Mongo();
         _mongo.Connect();
         _db = _mongo.getDB("FubuDinner");
         _isInitialized = true;
     }
 }
Ejemplo n.º 9
0
        public static List<Nut> FindAllInContainer(string account, string container, IDictionary<string,string> properties)
        {
            List<Nut> nuts = new List<Nut>();

            Mongo mongo = new Mongo();
            mongo.Connect();

            var db = mongo.GetDatabase(WellKnownDb.AppConfiguration);

            var collection = db.GetCollection(container);

            var query = new Document();

            query["account"] = account;

            foreach (string k in properties.Keys)
            {

                var t = properties[k];

                if (k == "value")
                {
                    query["value"] = t as string;
                }
                else
                {
                    query[k] = properties[k];

                }
            }

            var result = collection.Find(query);

            foreach (var r in result.Documents)
            {

                var nut = new Nut { Database = WellKnownDb.AppConfiguration, Table = container, Key = r["name"] as string, Properties = new Dictionary<string, string>() };

                nut.Value = r["value"] as string;
                nut.Uri = string.Format("/{0}/{1}/{2}", account, container, r["name"]);

                foreach (var j in r.Keys)
                {
                    nut.Properties.Add(j, r[j] as string);
                }

                nuts.Add(nut);
            }

            return nuts;
        }
        public void SetUp()
        {
            using(var mongo = new Mongo(CreateConnectionStringBuilder().ToString()))
            {
                mongo.Connect();

                var testDatabase = mongo[testDatabaseName];
                if(testDatabase.MetaData.FindUser(testuser) == null)
                    testDatabase.MetaData.AddUser(testuser, testpass);

                var adminDatabase = mongo["admin"];
                if(adminDatabase.MetaData.FindUser(adminuser) == null)
                    adminDatabase.MetaData.AddUser(adminuser, adminpass);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Setup the collection and insert some data into it.
        /// </summary>
        public void Setup()
        {
            string connstr = ConfigurationManager.AppSettings["simple"];
            if(String.IsNullOrEmpty(connstr)) throw new ArgumentNullException("Connection string not found.");
            mongo = new Mongo(connstr);
            mongo.Connect();
            simple = mongo["simple"];
            categories = simple["categories"];
            Clean();

            var names = new string[]{"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"};
            foreach(string name in names){
                categories.Insert(new Document(){{"name", name}});
            }
        }
Ejemplo n.º 12
0
        public void TestSetAndGetFunction()
        {
            string connstr = ConfigurationManager.AppSettings["mongoDBTest"];
            var mongo = new Mongo(connstr);
            mongo.Connect();

            var testDB = mongo.GetDatabase("myTest");

            AdminParameters.DB = testDB;

            AdminParameters.Set(AdminParameters.SuggesttedTagsForUserFavorite, "hello");
            Assert.AreEqual(AdminParameters.Get(AdminParameters.SuggesttedTagsForUserFavorite), "hello");

            mongo.Disconnect();
        }
        public IEnumerable RunQuery(string server, string database, string port, string query)
        {
            if (database == string.Empty)
                throw new QueryValidationException("You must specify a non-empty database name");

            if (query == string.Empty)
                throw new QueryValidationException("You must specify a non-empty query");

            _db = new Mongo(string.Format("Server={0}:{1}", server, port));
            IList<DictionaryBase> documents = new List<DictionaryBase>();

            try
            {
                _db.Connect();
            }
            catch (SocketException ex)
            {
                throw new UnknownServerException(string.Format("Unknown server: {0}:{1}", server, port), ex);
            }

            string[] queryParts = query.Split(':');
            string collection = queryParts[0];

            if (queryParts.Length > 1)
            {
                Document spec = new Document();
                string where = queryParts[1];
                const string LIMIT_TEXT = " limit ";
                int limitIndex = where.IndexOf(LIMIT_TEXT);
                int limit = 0;

                if (limitIndex > -1)
                {
                    string limitText;

                    if (int.TryParse(where.Substring(limitIndex + LIMIT_TEXT.Length), out limit))
                        where = where.Substring(0, limitIndex);
                }

                spec.Append("$where", new Code(where));
                _cursor = _db[database][collection].Find(spec, limit, 0);
            }
            else
                _cursor = _db[database][collection].FindAll();

            return _cursor.Documents;
            //Document d = db[database].SendCommand("db.test.find();");
        }
Ejemplo n.º 14
0
        public void FavoriteAdd()
        {
            string connstr = ConfigurationManager.AppSettings["mongoDBTest"];
            var mongo = new Mongo(connstr);
            mongo.Connect();

            var testDB = mongo.GetDatabase("myTest");
            UserFavorite fav = new UserFavorite(testDB, "testUserName" + DateTime.Now.ToShortTimeString());

            fav.Update("question", 101, "tag1,tag2");
            fav.Update("question", 102, "tag3,tag4");
            fav.Update("question", 104, "tag3,tag4,tag5");
            fav.Update("question", 103, "tag1,tag2");
            fav.Update("k", 101, "tag1,tag2");
            fav.Update("k", 102, "tag2,tag7");
            fav.Update("k", 103, "tag1,tag5");
            fav.Update("k", 104, "tag1,tag5");
            fav.Update("k", 105, "tag1,tag5");
            fav.Update("k", 106, "tag1,tag5");

            Assert.IsTrue(Compare(fav.GetTags("k"), "tag1,tag2,tag7,tag5"));
            Assert.IsTrue(Compare(fav.GetTags("question"), "tag1,tag2,tag3,tag4,tag5"));
            Assert.AreEqual("tag1,tag5", fav.GetTags("k", 103));
            Assert.AreEqual("tag1,tag2", fav.GetTags("question", 103));

            Assert.IsTrue(fav.GetIDs("question", "tag1").Contains(101));
            Assert.IsTrue(fav.GetIDs("question", "tag1").Contains(103));

            Assert.AreEqual(5, fav.GetIDs("k", "tag1").Count);
            Assert.AreEqual(6, fav.GetIDs("k").Count);
            Assert.AreEqual(0, fav.GetIDs("foofoo").Count);
            Assert.AreEqual(4, fav.GetIDs("question").Count);

            Assert.IsTrue(fav.HasFavorite("question", 103));
            Assert.IsFalse(fav.HasFavorite("k", 203));

            fav.Remove("question", 103);

            Assert.IsFalse(fav.HasFavorite("question", 103));

            mongo.Disconnect();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">The args.</param>
        private static void Main( string[] args )
        {
            // Connect to the mongo instance.
            var mongo = new Mongo();
            mongo.Connect();

            // Use the myorders database.
            Database db = mongo.GetDatabase("myorders");

            // Get the orders collection.
            IMongoCollection orders = db.GetCollection("orders");

            DeleteAllDocumentsFromCollection(orders);
            CreateAndInsertDocumentIntoCollection(orders);

            QueryFromCollection( orders );

            Console.WriteLine("\nPress Enter to Exit.");
            Console.ReadLine();
        }
        public void ShouldGetDataFromLocalMongoDbServer()
        {
            //Given
            Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017"));
            db.Connect();
            IMongoCollection collection = db["test"]["folks"];
            Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } };
            Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } };
            Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } };
            collection.Insert(doc1);
            collection.Insert(doc2);
            collection.Insert(doc3);

            IMongoQuery query = new MongoDbCSharpQuery();
            IMongoQueryFactory factory = new MongoDbCSharpQueryFactory(query);

            MainViewModel viewModel = new MainViewModel(factory)
                                          {
                                              Server = "localhost",
                                              Database = "test",
                                              Port = "27017",
                                              Query = "folks:this.middle_initial == 'Q'"
                                          };

            try
            {
                //When
                viewModel.RunQueryCommand.Execute(null);

                //Then
                Assert.AreEqual(2, viewModel.Items.Count);
                Assert.AreEqual(6, viewModel.Headers.Count); //including _id
            }
            finally
            {
                //Clean Up
                collection.Delete(doc1);
                collection.Delete(doc2);
                collection.Delete(doc3);
            }
        }
        protected void CreateMongoDB(String dbName)
        {
            //mongod.exe must be running for this to work.
            var mongo = new Mongo();
            mongo.Connect();

            //if the database is not found in c:\data\db it will be created.
            var db = mongo.GetDatabase(dbName);

            //declare a new "table"
            var categories = db.GetCollection("categories");

            //create a new key value set
            var document = new Document();
            document["Name"] = "Product";
            document["Name"] = "Price";

            //create the "tabt"
            categories.Insert(document);
            mongo.Disconnect();
        }
Ejemplo n.º 18
0
        public static void GenerateMongoDB ()
        {
            var json = new MongoJson();
            var mongo = new Mongo();

            mongo.Connect();

            //Create clean database and collection for Notes
            var db = mongo["SupermarkertsDB"];
            db.SendCommand("dropDatabase");
            var products = db["Products"];

            List<int> ids;
            var jsonData = GenerateJSONReports.ExatractJsonData(out ids);
            foreach (var item in jsonData)
            {
                var jsonDocument = json.DocumentFrom(item);
                products.Insert(jsonDocument);
            }           
            
            mongo.Disconnect();
        }
Ejemplo n.º 19
0
        //[Test]
        public void TestMultiThreadedReads()
        {
            Mongo db = new Mongo();

            db.Connect();

            List <string> colnames = new List <string> {
                "smallreads", "smallreads", "smallreads", "smallreads"
            };
            List <Thread> threads    = new List <Thread>();
            List <Reader> readers    = new List <Reader>();
            int           iterations = 50;

            foreach (string colname in colnames)
            {
                Reader r = new Reader {
                    Iterations = iterations, Collection = db["tests"][colname]
                };
                readers.Add(r);
                ThreadStart ts     = new ThreadStart(r.DoReads);
                Thread      thread = new Thread(ts);
                threads.Add(thread);
            }
            RunAndWait(threads);

            try{
                //Connection still alive?
                db["tests"]["smallreads"].Count();
            }catch (Exception e) {
                Assert.Fail(e.Message);
            }
            foreach (Reader r in readers)
            {
                Assert.AreEqual(iterations, r.Count, "A reader did not read everytime.");
            }
        }
        protected String GetMongoDBResults(String dbName)
        {
            //mongod.exe must be running for this to work.
            var mongo = new Mongo();
            mongo.Connect();

            //if the database is not found in c:\data\db it will be created.
            var db = mongo.GetDatabase(dbName);

            //declare a new "table"
            var categories = db.GetCollection("categories");

            //get the categories table
            var category = categories.FindOne(new Document() { { "Name","Price" } });
            //alternatively you can get all documents in the database
            var documents = categories.FindAll().Documents;
            String res = category["Name"].ToString();

            //diconnect
            mongo.Disconnect();

            //return results in a EF friendly shapre just because that's what I'm working with mostly nowadays
            return res;
        }
 public MongoDbWr()
 {
     mongo = new Mongo();
     mongo.Connect();
 }
Ejemplo n.º 22
0
 public void Init()
 {
     db.Connect();
     cleanDB();
 }
        // database
        private void ConnectToDatabase()
        {
            db_server = new MongoDB.Driver.Mongo(_connectionString);

            db_server.Connect();

            MongoDB.Driver.IMongoDatabase db = db_server.GetDatabase("MongoBlog");

            collection = db.GetCollection("blogposts");

            return;
        }
        public void TestUnauthenticatedInsert()
        {
            using(var mongo = new Mongo(CreateConnectionStringBuilder().ToString()))
            {
                mongo.Connect();

                TryInsertData(mongo);
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Подключаемся к БД
 /// </summary>
 /// <returns>Результат попытки подключения</returns>
 private static bool ConnectToMongo()
 {
     db = new Mongo();
     try
     {
         ///Делаем попытку подключения
         db.Connect();
         ///если все ок,возвращаем true
         return true;
     }
     catch(Exception)
     {
         ///иначе -false
         ///для промтоты сделана
         ///такая "тупая" обработка
         ///ошибки
         return false;
     }
 }
Ejemplo n.º 26
0
 public void TestExplicitConnection()
 {
     Mongo m = new Mongo();
     Assert.IsTrue(m.Connect());
 }
Ejemplo n.º 27
0
        public virtual object DoCheck()
        {
            Document commandResults = null;
            Mongo mongo = null;

            try
            {
                mongo = new Mongo(_connectionString);
                mongo.Connect();

                // In the Linux agent, we get all database names and use the first
                // one found, but no such functionality exists with this .NET
                // MongoDB library.
                Database database = mongo.GetDatabase(DatabaseName);
                commandResults = database.SendCommand("serverStatus");
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
            finally
            {

                if (mongo != null)
                {
                    mongo.Disconnect();
                }

            }

            if (commandResults == null)
            {
                Log.Warn("MongoDB returned no results for serverStatus command.");
                Log.Warn("This is possible on older versions of MongoDB.");
                return null;
            }

            Document indexCounters = (Document)commandResults["indexCounters"];
            Document btree = null;

            // Index counters are currently not supported on Windows.
            if (indexCounters["note"] == null)
            {
                btree = (Document)indexCounters["btree"];
            }
            else
            {
                // We add a blank document, since the server is expecting
                // these btree index values to be present.
                btree = new Document();
                indexCounters.Add("btree", btree);
                btree.Add("accesses", 0);
                btree.Add("accessesPS", 0);
                btree.Add("hits", 0);
                btree.Add("hitsPS", 0);
                btree.Add("misses", 0);
                btree.Add("missesPS", 0);
                btree.Add("missRatio", 0D);
                btree.Add("missRatioPS", 0);
            }

            Document opCounters = (Document)commandResults["opcounters"];
            Document asserts = (Document)commandResults["asserts"];

            if (_mongoDBStore == null)
            {
                Log.Debug("No cached data, so storing for the first time.");

                btree["accessesPS"] = 0;
                btree["hitsPS"] = 0;
                btree["missesPS"] = 0;
                btree["missRatioPS"] = 0;

                opCounters.Add("insertPS", 0);
                opCounters.Add("queryPS", 0);
                opCounters.Add("updatePS", 0);
                opCounters.Add("deletePS", 0);
                opCounters.Add("getmorePS", 0);
                opCounters.Add("commandPS", 0);

                asserts.Add("regularPS", 0);
                asserts.Add("warningPS", 0);
                asserts.Add("msgPS", 0);
                asserts.Add("userPS", 0);
                asserts.Add("rolloversPS", 0);
            }
            else
            {
                Log.Debug("Cached data exists, so calculating per sec metrics.");

                Document cachedBtree = (Document)((Document)_mongoDBStore["indexCounters"])["btree"];
                Document cachedOpCounters = (Document)_mongoDBStore["opcounters"];
                Document cachedAsserts = (Document)commandResults["asserts"];

                btree["accessesPS"] = (float)(((int)btree["accesses"] - (int)cachedBtree["accesses"]) / 60);
                btree["hitsPS"] = (float)(((int)btree["hits"] - (int)cachedBtree["hits"]) / 60);
                btree["missesPS"] = (float)(((int)btree["misses"] - (int)cachedBtree["misses"]) / 60);
                btree["missRatioPS"] = (float)(((double)btree["missRatio"] - (double)cachedBtree["missRatio"]) / 60);

                opCounters.Add("insertPS", (float)(((int)opCounters["insert"] - (int)cachedOpCounters["insert"]) / 60));
                opCounters.Add("queryPS", (float)(((int)opCounters["query"] - (int)cachedOpCounters["query"]) / 60));
                opCounters.Add("updatePS", (float)(((int)opCounters["update"] - (int)cachedOpCounters["update"]) / 60));
                opCounters.Add("deletePS", (float)(((int)opCounters["delete"] - (int)cachedOpCounters["delete"]) / 60));
                opCounters.Add("getmorePS", (float)(((int)opCounters["getmore"] - (int)cachedOpCounters["getmore"]) / 60));
                opCounters.Add("commandPS", (float)(((int)opCounters["command"] - (int)cachedOpCounters["command"]) / 60));

                asserts.Add("regularPS", (float)(((int)asserts["regular"] - (int)cachedAsserts["regular"]) / 60));
                asserts.Add("warningPS", (float)(((int)asserts["warning"] - (int)cachedAsserts["warning"]) / 60));
                asserts.Add("msgPS", (float)(((int)asserts["msg"] - (int)cachedAsserts["msg"]) / 60));
                asserts.Add("userPS", (float)(((int)asserts["user"] - (int)cachedAsserts["user"]) / 60));
                asserts.Add("rolloversPS", (float)(((int)asserts["rollovers"] - (int)cachedAsserts["rollovers"]) / 60));
            }

            _mongoDBStore = commandResults;

            return _mongoDBStore;
        }
Ejemplo n.º 28
0
 public void Init()
 {
     mongo.Connect();
     db = mongo["tests"];
     cleanDB();
 }
Ejemplo n.º 29
0
        //[Test]
        public void TestMultiThreadedReads()
        {
            Mongo db = new Mongo();
            db.Connect();

            List<string> colnames = new List<string>{"smallreads", "smallreads", "smallreads", "smallreads"};
            List<Thread> threads = new List<Thread>();
            List<Reader> readers = new List<Reader>();
            int iterations = 50;
            foreach(string colname in colnames){
                Reader r = new Reader{Iterations = iterations, Collection = db["tests"][colname]};
                readers.Add(r);
                ThreadStart ts = new ThreadStart(r.DoReads);
                Thread thread = new Thread(ts);
                threads.Add(thread);
            }
            RunAndWait(threads);

            try{
                //Connection still alive?
                db["tests"]["smallreads"].Count();
            }catch(Exception e){
                Assert.Fail(e.Message);
            }
            foreach(Reader r in readers){
                Assert.AreEqual(iterations, r.Count, "A reader did not read everytime.");
            }
        }
Ejemplo n.º 30
0
        public static Nut FindNut(string account, string container, string name, IDictionary<string,string> properties)
        {
            Nut nut = null;

            Mongo mongo = new Mongo();
            mongo.Connect();

            var db = mongo.GetDatabase(WellKnownDb.AppConfiguration);

            var collection = db.GetCollection(container);

            var query = new Document();

            query["name"] = name;
            query["account"] = account;

            foreach (string k in properties.Keys)
            {
                query[k] = properties[k];
            }

            var result = collection.FindOne(query);

            if (result != null)
            {

                nut = new Nut { Database = WellKnownDb.AppConfiguration, Table = container, Key = name, Properties = new Dictionary<string, string>() };

                nut.Value = result["value"] as string;
                nut.Uri = string.Format("/{0}/{1}/{2}", account, container, name);

                foreach (var j in result.Keys)
                {
                    nut.Properties.Add(j, result[j] as string);
                }

            }

            return nut;
        }
Ejemplo n.º 31
0
        public void TestMultiThreadedReadsAndWrites()
        {
            Mongo db = new Mongo();
            db.Connect();

            IMongoCollection col = db["tests"]["threadreadinserts"];

            List<string> identifiers = new List<string>{"A", "B", "C", "D"};
            List<string> colnames = new List<string>{"smallreads", "smallreads", "smallreads", "smallreads"};
            List<Thread> threads = new List<Thread>();
            List<Reader> readers = new List<Reader>();
            int writeiterations = 100;
            int readiterations = 50;
            foreach(string identifier in identifiers){
                Inserter ins = new Inserter {Iterations = writeiterations, Identifier = identifier, Collection = col};
                ThreadStart ts = new ThreadStart(ins.DoInserts);
                Thread thread = new Thread(ts);
                threads.Add(thread);
            }
            foreach(string colname in colnames){
                Reader r = new Reader{Iterations = readiterations, Collection = db["tests"][colname]};
                readers.Add(r);
                ThreadStart ts = new ThreadStart(r.DoReads);
                Thread thread = new Thread(ts);
                threads.Add(thread);
            }

            RunAndWait(threads);
            try{
                Assert.AreEqual(identifiers.Count * writeiterations, col.Count());
            }catch(Exception e){
                Assert.Fail(e.Message);
            }
            foreach(Reader r in readers){
                Assert.AreEqual(readiterations, r.Count, "A reader did not read everytime.");
            }
        }
Ejemplo n.º 32
0
        //[Test]
        public void TestMultiThreadedWrites()
        {
            Mongo db = new Mongo();
            db.Connect();

            IMongoCollection col = db["tests"]["threadinserts"];

            List<string> identifiers = new List<string>{"A", "B", "C", "D"};
            List<Thread> threads = new List<Thread>();
            int iterations = 100;

            foreach(string identifier in identifiers){
                Inserter ins = new Inserter {Iterations = iterations, Identifier = identifier, Collection = col};
                ThreadStart ts = new ThreadStart(ins.DoInserts);
                Thread thread = new Thread(ts);
                threads.Add(thread);
            }

            RunAndWait(threads);

            try{
                Assert.AreEqual(identifiers.Count * iterations, col.Count());
            }catch(Exception e){
                Assert.Fail(e.Message);
            }
        }
Ejemplo n.º 33
0
        public void TestExplicitConnection()
        {
            Mongo m = new Mongo();

            Assert.IsTrue(m.Connect());
        }
 public void Init()
 {
     db.Connect();
     initDB();
 }
 public void GlobalSetup()
 {
     Debug.WriteLine("initiallizing connection");
     mongo = AppSettingsFactory.CreateMongo();
     mongo.Connect();
 }