//[Test] public void TestMultiThreadedWrites (){ Mongo db = new Mongo(); db.Connect(); IMongoCollection col = DB["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); } }
//[Test] public void TestMultiThreadedReads(){ Mongo db = new Mongo(); db.Connect(); List<string> colnames = new List<string>{"threadsmallreads", "threadsmallreads", "threadsmallreads", "threadsmallreads"}; 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[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["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."); } }
public void TestUnauthenticatedInsert(){ using(var mongo = new Mongo(_connectionString)) { mongo.Connect(); TryInsertData(mongo); } }
public static void Main(string[] args) { SetupDocuments(); var m = new Mongo(); m.Connect(); var 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); var fonespec = new Document().Add("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); var findRange = new Document().Add("x", new Document().Add("$gt", perTrial/2).Add("$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); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public void TestGetDatabasesReturnsSomething() { using(var m = new Mongo(_connectionString)) { m.Connect(); var databaseCount = m.GetDatabases().Count(); Assert.Greater(databaseCount, 1); } }
public static void SelectOne() { using (var mg = new Mongo(DBcon._connectionString)) { mg.Connect(); var db = mg.GetDatabase(DBcon._database); var list = db.GetCollection <NewModel>(); var newlist = list.FindOne(new Document() { { "Name", "柏建峰2" } }); Console.WriteLine(newlist.Age + "," + newlist.Name); } }
/// <summary> /// 获取一条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static T GetOne <T>(string collectionName, Document query) where T : class { T result = default(T); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection <T> collection = friends.GetCollection <T>(collectionName); result = collection.FindOne(query); mongo.Disconnect(); } return(result); }
/// <summary> /// 获取一条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static T GetFirst <T>(string collectionName, Document query, Document fields) where T : class { T result = default(T); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection <T> collection = friends.GetCollection <T>(collectionName); result = collection.Find(query, fields).Skip(0).Limit(1).Documents.First(); mongo.Disconnect(); } return(result); }
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); MainViewModel viewModel = new MainViewModel() { 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); } }
public static void AddVedio() { using (var mg = new Mongo(DBcon._connectionString)) { mg.Connect(); var db = mg.GetDatabase(DBcon._database); var list = db.GetCollection <NewModel>(); var model = new NewModel() { Age = 2, Name = "柏建峰2" }; list.Insert(model); } }
public IEnumerable <DomainEvent> GetEvents(Guid aggregateRootId, int startSequence) { using (var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var eventsCollection = database.GetCollection <DomainEvent>("events").Linq(); return((from domainEvent in eventsCollection where domainEvent.AggregateRootId == aggregateRootId where domainEvent.Sequence > startSequence select domainEvent).ToList()); } }
public void Insert(Session session) { Document newSession = new Document() { { "SessionId", session.SessionID }, { "ApplicationName", session.ApplicationName }, { "Created", session.Created }, { "Expires", session.Expires }, { "LockDate", session.LockDate }, { "LockId", session.LockID }, { "Timeout", session.Timeout }, { "Locked", session.Locked }, { "SessionItems", session.SessionItems }, { "SessionItemsCount", session.SessionItemsCount }, { "Flags", session.Flags } }; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Insert(newSession); } }
public void SetUp() { using(var mongo = new Mongo(_connectionString)) { 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); } }
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 Connect2Mongo(string ip, string port, string database) { try { var connstr = @"Server=" + ip + ":" + port; //外网地址 //var connstr = @"Server=localhost:27017"; _gMongo = new Mongo(connstr); _gMongo.Connect(); _gTest = _gMongo[database]; } catch (Exception ex) { MessageBox.Show(ex.Message, "异常信息"); } }
public static List <VEHICLE> GetVehiclesByMarketMakeModel(string market, string make, string model, string pricerange) { List <VEHICLE> retval = null; using (Mongo mongo = new Mongo(config.BuildConfiguration())) { mongo.Connect(); var db = mongo.GetDatabase(VehicleRecords.VEHICLE_DB.DataBaseName); IMongoCollection <Document> collPriceRange = db.GetCollection <Document>(PRICERANGE.TableName); Document qPriceRange = new Document(); qPriceRange["VALUENAME"] = pricerange; Document docPriceRange = collPriceRange.FindOne(qPriceRange); PRICERANGE pr = PRICERANGE.GetPRICERANGEFromDocument(docPriceRange); IMongoCollection <Document> collVehicles = db.GetCollection <Document>(VEHICLE.TableName); Document qVehicles = new Document(); qVehicles["MARKET"] = market; if (make.Length > 0 && make != "All") { qVehicles["MAKE"] = make; } if (model.Length > 0 && model != "All") { qVehicles["MODEL"] = model; } qVehicles["STILL_FOR_SALE"] = "YES"; string where = $"(this.CURRENT_PRICE >= {pr.LOWBOUND} && this.CURRENT_PRICE <= {pr.HIGHBOUND})"; qVehicles.Add("$where", new Code(where)); VEHICLE[] foundvehicles = VEHICLE.GetVEHICLEsFromQueryDocument(collVehicles, qVehicles); if (foundvehicles != null && foundvehicles.Count <VEHICLE>() > 0) { retval = foundvehicles.ToList <VEHICLE>(); } mongo.Disconnect(); } return(retval); }
public void EvictExpiredSession(string id, string applicationName) { Document selector = new Document() { { "SessionId", id }, { "ApplicationName", applicationName }, { "Expires", new Document() { { "$lt", DateTime.Now } } } }; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Remove(selector); } }
/// <summary> /// 获取列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <param name="fields"></param> /// <param name="sort"></param> /// <param name="pageindex"></param> /// <param name="pagesize"></param> /// <returns></returns> public static List <T> GetList <T>(string collectionName, object query, object fields, Document sort, int pageindex, int pagesize) where T : class { List <T> result = new List <T>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection <T> collection = friends.GetCollection <T>(collectionName); foreach (T entity in collection.Find(query, fields).Sort(sort).Skip((pageindex - 1) * pagesize).Limit(pagesize).Documents) { result.Add(entity); } mongo.Disconnect(); } return(result); }
public static void Main(string[] args) { SetupDocuments(); Mongo m = new Mongo(); m.Connect(); Database db = m["benchmark"]; db.MetaData.DropDatabase(); runInsertTest("insert (small, no index)", db, "small_none",small,false); runInsertTest("insert (medium, no index)", db, "medium_none",medium,false); runInsertTest("insert (large, no index)", db, "large_none",large,false); runInsertTest("insert (small, indexed)", db, "small_index",small,true); runInsertTest("insert (medium, indexed)", db, "medium_index",medium,true); runInsertTest("insert (large, indexed)", db, "large_index",large,true); }
/// <summary> /// 构造函数。根据指定连接字符串和数据库名 /// </summary> /// <param name="connectionString">连接字符串</param> /// <param name="dbName">数据库名,可为空,但必须在任何操作数据库之前要调用UseDb()方法</param> public MongoDBHelper(string connectionString, string dbName) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("connectionString"); } _mongo = new Mongo(connectionString); // 立即连接 MongoDB _mongo.Connect(); if (!string.IsNullOrEmpty(dbName)) { _db = _mongo.GetDatabase(dbName); } }
public void TestCode() { //链接字符串 string connectionString = "mongodb://localhost"; //数据库名 string databaseName = "myDatabase"; //集合名 string collectionName = "myCollection"; //定义Mongo服务 Mongo mongo = new Mongo(connectionString); //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection <T> mongoCollection = mongoDatabase.GetCollection <T>(collectionName) as MongoCollection <T>; //链接数据库 mongo.Connect(); try { //定义一个文档对象,存入两个键值对 T doc = new T(); doc["ID"] = 1; doc["Msg"] = "Hello World!"; //将这个文档对象插入集合 mongoCollection.Insert(doc); //在集合中查找键值对为ID=1的文档对象 T docFind = mongoCollection.FindOne(new T { { "ID", 1 } }); //输出查找到的文档对象中键“Msg”对应的值,并输出 Console.WriteLine(Convert.ToString(docFind["Msg"])); } finally { //关闭链接 mongo.Disconnect(); } }
public static void UpdateVehicleRecord(VEHICLE veh) { using (Mongo mongo = new Mongo(config.BuildConfiguration())) { mongo.Connect(); var db = mongo.GetDatabase(VehicleRecords.VEHICLE_DB.DataBaseName); IMongoCollection <Document> collVehicles; collVehicles = db.GetCollection <Document>(VEHICLE.TableName); Document qVeh = new Document(); qVeh["VIN"] = veh.VIN; collVehicles.Remove(qVeh); VEHICLE.InsertDocumentFromMEMBER(collVehicles, veh); mongo.Disconnect(); } }
/// <summary> /// 获取一个通过查询条件的集合下所有数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static List <T> GetList <T>(string collectionName, object query) where T : class { List <T> result = new List <T>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection <T> collection = friends.GetCollection <T>(collectionName); foreach (T entity in collection.Find(query).Documents) { result.Add(entity); } mongo.Disconnect(); } return(result); }
/// <summary> /// 获取所有产品信息 /// </summary> /// <returns></returns> public static List <Products> ProductList() { try { using (Mongo mongo = new Mongo(_connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(_dbName); var collection = db.GetCollection <Products>(); return(collection.FindAll().Documents.ToList()); } } catch (Exception ex) { log.Error(ex); throw; } }
public static void Update() { using (var mg = new Mongo(DBcon._connectionString)) { var model = new NewModel() { Age = 1, Name = "修改过" }; mg.Connect(); var db = mg.GetDatabase(DBcon._database); var list = db.GetCollection <NewModel>(); list.Update(model, new Document() { { "Age", model.Age } }); } }
//构造 public MongoDBUtility(string ConnString, string databaseName) { //根据 MongoConfiguration 实例化一个 mongodb-csharp Mongo核心类 mongo = new Mongo(InitMongoBuilder(ConnString)); //打开数据库连接 mongo.Connect(); try { //根据指定字符串获取mongodb对应的数据库 simple = mongo.GetDatabase(databaseName); } catch (Exception e) { //异常 释放当前对象 Dispose(); throw e; } }
/// <summary> /// 获取所有员工客户信息 /// </summary> /// <returns></returns> public static List <StaffCustomer> StaffCustomerList() { try { using (Mongo mongo = new Mongo(_connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(_dbName); var collection = db.GetCollection <StaffCustomer>(); return(collection.FindAll().Documents.ToList()); } } catch (Exception ex) { log.Error(ex); return(new List <StaffCustomer>()); } }
/// <summary> /// 删除操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Delete(Expression <Func <TEntity, bool> > func) { try { mongoSelect.Connect(); var db = mongoSelect.GetDatabase(databaseName); var collection = db.GetCollection <TEntity>(collectionName); //这个地方要注意,一定要加上T参数,否则会当作object类型处理 collection.Remove <TEntity>(func); } catch (Exception ex) { throw ex; } }
public IEnumerable <DomainEvent> GetEventsByEventTypes(IEnumerable <Type> domainEventTypes) { using (var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var selector = new Document { { "_t", new Document { { "$in", domainEventTypes.Select(t => t.Name).ToArray() } } } }; var cursor = database.GetCollection <DomainEvent>("events").Find(selector); return(cursor.Documents.ToList()); } }
public void Should_return_an_empty_list() { var SearchTags = new List<string> { "test" }; using (var mongo = new Mongo()) { mongo.Connect(); var db = mongo.GetDatabase("posts"); var posts = db.GetCollection<Post>(); posts.Remove(x => true); posts.Insert(new Post() { Tags = new List<string> { "test", "funny" } }); var result = SearchTags .Aggregate(posts.Linq(), (current, tag) => current.Where(x => x.Tags.Contains(tag))) .OrderByDescending(x => x.LastAccess) .ToList(); Assert.AreEqual(1, result.Count); } }
/// <summary> /// Подключаемся к БД /// </summary> /// <returns>Результат попытки подключения</returns> private static bool ConnectToMongo() { db = new Mongo(); try { ///Делаем попытку подключения db.Connect(); ///если все ок,возвращаем true return(true); } catch (Exception) { ///иначе -false ///для промтоты сделана ///такая "тупая" обработка ///ошибки return(false); } }
/// <summary> /// 更新实体 /// </summary> /// <param name="user"></param> public static void Update(Staff user) { try { using (Mongo mongo = new Mongo(_connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(_dbName); var collection = db.GetCollection <Staff>(); // 更新对象 collection.Update(user, item => item.Id == user.Id); } } catch (Exception ex) { log.Error(ex); } }
public void GetMongoDBData() { var mongo = new Mongo(); mongo.Connect(); //Get the blog database. If it doesn't exist, that's ok because MongoDB will create it //for us when we first use it. Awesome!!! var db = mongo.GetDatabase("blog"); //Get the Post collection. By default, we'll use //the name of the class as the collection name. Again, //if it doesn't exist, MongoDB will create it when we first use it. var collection = db.GetCollection <Post>(); //this deletes everything out of the collection so we can run this over and over again. collection.Remove(p => true); //Create a Post to enter into the database. var post = new Post() { Title = "My First Post", Body = "This isn't a very long post.", CharCount = 27, Comments = new List <Comment> { { new Comment() { TimePosted = new DateTime(2010, 1, 1), Email = "*****@*****.**", Body = "This article is too short!" } }, { new Comment() { TimePosted = new DateTime(2010, 1, 2), Email = "*****@*****.**", Body = "I agree with Bob." } } } }; collection.Save(post); }
public void SetUp() { using (var mongo = new Mongo(_connectionString)) { 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); } } }
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(); } }
private void button4_Click(object sender, EventArgs e) { //链接字符串 string connectionString = "mongodb://localhost"; //数据库名 string databaseName = "myDatabase"; //集合名 string collectionName = "myCollection"; //定义Mongo服务 Mongo mongo = new Mongo(connectionString); //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection <Document> mongoCollection = mongoDatabase.GetCollection <Document>(collectionName) as MongoCollection <Document>; //链接数据库 mongo.Connect(); try { //定义一个文档对象,存入两个键值对 Document doc = new Document(); doc["ID"] = 1; doc["Msg"] = "Hello World!"; //将这个文档对象插入集合 mongoCollection.Insert(doc); //在集合中查找键值对为ID=1的文档对象 Document docFind = mongoCollection.FindOne(new Document { { "ID", 1 } }); //输出查找到的文档对象中键“Msg”对应的值,并输出 //Console.WriteLine(Convert.ToString(docFind["Msg"])); MessageBox.Show(Convert.ToString(docFind["Msg"])); } finally { //关闭链接 mongo.Disconnect(); } }
public void UpdateSessionExpiration(string id, string applicationName, double timeout) { Document selector = new Document() { { "SessionId", id }, { "ApplicationName", applicationName } }; Document sessionUpdate = new Document() { { "$set", new Document() { { "Expires", DateTime.Now.AddMinutes(timeout) } } } }; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Update(sessionUpdate, selector, 0, false); } }
public void UpdateSession(string id, int timeout, Binary sessionItems, string applicationName, int sessionItemsCount, object lockId) { Document selector = new Document() { { "SessionId", id }, { "ApplicationName", applicationName }, { "LockId", lockId } }; Document session = new Document() { { "$set", new Document() { { "Expires", DateTime.Now.AddMinutes((double)timeout) }, { "Timeout", timeout }, { "Locked", false }, { "SessionItems", sessionItems }, { "SessionItemsCount", sessionItemsCount } } } }; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Update(session, selector, 0, false); } }
private Mongo ConnectAndAuthenticatedMongo(string username,string password) { var builder = new MongoConnectionStringBuilder(_connectionString) { Username = username, Password = password }; var mongo = new Mongo(builder.ToString()); mongo.Connect(); return mongo; }
public void TestMultiThreadedReadsAndWrites(){ Mongo db = new Mongo(); db.Connect(); IMongoCollection col = DB["threadreadinserts"]; List<string> identifiers = new List<string>{"A", "B", "C", "D"}; List<string> colnames = new List<string>{"threadsmallreads", "threadsmallreads", "threadsmallreads", "threadsmallreads"}; 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[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."); } }
public void TestConnectThrowIfConnectionFailed(){ using(var m = new Mongo("Server=notexists")) m.Connect(); }
public static void MongoConnection() { string connstr = @"Server=" + MongoXml.GetConfig()[0] + ":" + MongoXml.GetConfig()[1]; _gMongo = new Mongo(connstr); _gMongo.Connect(); }