public void BeforeEachTest() { var client = new MongoClient("mongodb://localhost:27017"); Database = client.GetServer().GetDatabase("identity-testing"); Users = Database.GetCollection<IdentityUser>("users"); Roles = Database.GetCollection<IdentityRole>("roles"); IdentityContext = new IdentityContext(Users, Roles); Database.DropCollection("users"); Database.DropCollection("roles"); }
private void PrepareDatabase() { var collectionNames = _database.GetCollectionNames().ToList().FindAll(x => x != "system.indexes" && x != "system.users"); collectionNames.ForEach(c => _database.DropCollection(c)); _database.DropCollection(Collection1); _database.DropCollection(Collection2); _database.CreateCollection(Collection1); _database.CreateCollection(Collection2); }
public void BeforeEachTest() { var client = new MongoClient("mongodb://localhost:27017"); Database = client.GetServer().GetDatabase("identity-testing"); Users = Database.GetCollection <IdentityUser>("users"); Roles = Database.GetCollection <IdentityRole>("roles"); IdentityContext = new IdentityContext(Users, Roles); Database.DropCollection("users"); Database.DropCollection("roles"); }
public void Wipe() { string databaseName = MongoUrl.Create(ConnectionString).DatabaseName; MongoClient client = new MongoClient(ConnectionString); MongoServer server = client.GetServer(); MongoDatabase database = server.GetDatabase(databaseName); database.DropCollection(typeof(PageContent).Name); database.DropCollection(typeof(Page).Name); database.DropCollection(typeof(User).Name); database.DropCollection(typeof(SiteConfigurationEntity).Name); }
public void TestDropCollection() { var collectionName = "testdropcollection"; Assert.False(_database.CollectionExists(collectionName)); _database.GetCollection(collectionName).Insert(new BsonDocument()); Assert.True(_database.CollectionExists(collectionName)); _database.DropCollection(collectionName); Assert.False(_database.CollectionExists(collectionName)); }
public void Install(DataStoreType dataStoreType, string connectionString, bool enableCache) { string databaseName = MongoUrl.Create(connectionString).DatabaseName; MongoClient client = new MongoClient(connectionString); MongoServer server = client.GetServer(); MongoDatabase database = server.GetDatabase(databaseName); database.DropCollection("Page"); database.DropCollection("PageContent"); database.DropCollection("User"); database.DropCollection("SiteConfiguration"); }
public void TestFixture_Setup() { _server = new MongoServer(); _db = _server.GetDatabase("TestSuiteDatabase"); DroppedCollectionResponse collResponse = _db.DropCollection("TestClasses"); _coll = _db.GetCollection<TestClass>("TestClasses"); }
public void setUp() { wammerDb = mongodb.GetDatabase("wammer"); if (wammerDb.CollectionExists("attachments")) { wammerDb.DropCollection("attachments"); } wammerDb.CreateCollection("attachments"); objectId1 = Guid.NewGuid().ToString(); doc = new Attachment { object_id = objectId1, title = "title1", description = "description1" }; AttachmentCollection.Instance.Save(doc); handler = new AttachmentGetHandler(); server = new HttpServer(8080); server.AddHandler("/api/get/", handler); server.Start(); //host = new WebServiceHost(svc, new Uri("http://localhost:8080/api/")); //host.Open(); }
/// <summary> /// 封装对MongoDB 的操作处理。 /// </summary> public MongoDBHelper(bool createNewCollection) { var cfgs = CONNECTION_STRING.Split(':'); if (cfgs.Length != 2) { throw new MB.Util.APPException("请先配置Mongo数据库连接字符窜配置有误.例如:MongoDbConnection=IP:database", Util.APPMessageType.SysErrInfo); } _ConnectionString = string.Format("mongodb://{0}", cfgs[0]); _DataBaseName = cfgs[1]; _Server = MongoServer.Create(_ConnectionString); string collectionName = typeof(T).FullName; //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = _Server.GetDatabase(_DataBaseName) as MongoDatabase; if (createNewCollection) { mongoDatabase.DropCollection(collectionName); } if (mongoDatabase.CollectionExists(collectionName)) { mongoDatabase.CreateCollectionSettings <T>(collectionName); } _DataCollection = mongoDatabase.GetCollection <T>(collectionName); //链接数据库 _Server.Connect(); }
private void PrepareDatabase() { _database.DropCollection(CollectionName); _discCollection = _database.GetCollection <Disc>(CollectionName); var keys = IndexKeys.Ascending("Name", "Artist", "Year"); var options = IndexOptions.SetUnique(true); _discCollection.CreateIndex(keys, options); _discCollection.RemoveAll(); _disc1 = new Disc { Name = "Disc1", Artist = "Artist1", Gener = "Gener1", Year = "Year1" }; _disc2 = new Disc { Name = "Disc2", Artist = "Artist2", Gener = "Gener1", Year = "Year1" }; _disc3 = new Disc { Name = "Disc3", Artist = "Artist1", Gener = "Gener1", Year = "Year2" }; _disc4 = new Disc { Name = "Disc4", Artist = "Artist3", Gener = "Gener2", Year = "Year2" }; _discCollection.Insert(_disc1); _discCollection.Insert(_disc2); _discCollection.Insert(_disc3); _discCollection.Insert(_disc4); }
public void BeforeEachTest() { var client = new MongoClient("mongodb://localhost:27017"); var identityTesting = "identity-testing"; Database = client.GetServer().GetDatabase(identityTesting); Users = Database.GetCollection <IdentityUser>("users"); Roles = Database.GetCollection <IdentityRole>("roles"); DatabaseNewApi = client.GetDatabase(identityTesting); _UsersNewApi = DatabaseNewApi.GetCollection <IdentityUser>("users"); _RolesNewApi = DatabaseNewApi.GetCollection <IdentityRole>("roles"); Database.DropCollection("users"); Database.DropCollection("roles"); }
private void CopyCollections(params string[] exclusions) { foreach (var collectionName in _sourceMongoDatabase.GetCollectionNames()) { if (collectionName.StartsWith("system") || exclusions.Contains(exclusion => String.Equals(collectionName, exclusion))) { continue; } if (!_sourceMongoDatabase.CollectionExists(collectionName)) { Log.Warn().Message("Collection \"{0}\" was not found in the source database.", collectionName).Write(); return; } Log.Info().Message("Copying collection: {0}", collectionName).Write(); if (_mongoDatabase.CollectionExists(collectionName)) { _mongoDatabase.DropCollection(collectionName); } var source = _sourceMongoDatabase.GetCollection(collectionName); var target = _mongoDatabase.GetCollection(collectionName); target.InsertBatch(source.FindAll()); Log.Info().Message("Finished copying collection: {0}", collectionName).Write(); } }
public void BeforeEachTest() { var client = new MongoClient("mongodb://localhost:27017"); var identityTesting = "identity-testing"; Database = client.GetServer().GetDatabase(identityTesting); Users = Database.GetCollection<IdentityUser>("users"); Roles = Database.GetCollection<IdentityRole>("roles"); DatabaseNewApi = client.GetDatabase(identityTesting); _UsersNewApi = DatabaseNewApi.GetCollection<IdentityUser>("users"); _RolesNewApi = DatabaseNewApi.GetCollection<IdentityRole>("roles"); Database.DropCollection("users"); Database.DropCollection("roles"); }
protected override async Task <JobResult> RunInternalAsync(CancellationToken token) { if (!ConfigurationManager.AppSettings.GetBool("Migration:CanResetData").GetValueOrDefault()) { return(JobResult.FailedWithMessage("Migration:CanResetData was not set in the app.config.")); } Log.Info().Message("Flushing redis cache").Write(); _cacheClient.FlushAll(); Log.Info().Message("Resetting elastic search").Write(); ElasticSearchConfiguration.ConfigureMapping(_elasticClient, true); foreach (var collectionName in _mongoDatabase.GetCollectionNames().Where(name => !name.StartsWith("system"))) { Log.Info().Message("Dropping collection: {0}", collectionName).Write(); _mongoDatabase.DropCollection(collectionName); } Log.Info().Message("Creating indexes...").Write(); new ApplicationRepository(_mongoDatabase); new OrganizationRepository(_mongoDatabase); new ProjectRepository(_mongoDatabase); new TokenRepository(_mongoDatabase); new WebHookRepository(_mongoDatabase); new UserRepository(_mongoDatabase); Log.Info().Message("Finished creating indexes...").Write(); return(JobResult.Success); }
public void BeforeEachTest() { var client = new MongoClient(_TestingConnectionString); // todo move away from GetServer which could be deprecated at some point Database = client.GetServer().GetDatabase(IdentityTesting); Users = Database.GetCollection <IdentityUser>("users"); Roles = Database.GetCollection <IdentityRole>("roles"); DatabaseNewApi = client.GetDatabase(IdentityTesting); Database.DropCollection("users"); Database.DropCollection("roles"); ServiceProvider = CreateServiceProvider <IdentityUser, IdentityRole>(); }
// Drops all collections, including the special 'counters' collection for generating ids, // AND the binaries stored at Amazon S3 private void EraseData() { // Don't try this at home var collectionsToDrop = new string[] { Collection.RESOURCE, Collection.COUNTERS, Collection.SNAPSHOT }; foreach (var name in collectionsToDrop) { database.DropCollection(name); } /* * // When using Amazon S3, remove blobs from there as well * if (Config.Settings.UseS3) * { * using (var blobStorage = getBlobStorage()) * { * if (blobStorage != null) * { * blobStorage.Open(); * blobStorage.DeleteAll(); * blobStorage.Close(); * } * } * } */ }
public void Test_DynamicFields() { const string loggerName = "testDynamicFields"; var collection = _db.GetCollection(loggerName); // Clear out test collection collection.RemoveAll(); var logger = LogManager.GetLogger(loggerName); logger.LogException( LogLevel.Error, "Test Log Message", new Exception("Test Exception", new Exception("Inner Exception"))); Thread.Sleep(2000); collection.FindAll().Count().Should().Be(1); var logEntry = collection.FindAll().First(); Assert.IsTrue(logEntry.Contains("_id")); logEntry["level"].Should().Be(LogLevel.Error.ToString()); logEntry["message"].Should().Be("Test Log Message"); logEntry["exception"].Should().Be("Test Exception"); // Clean-up _db.DropCollection(loggerName); }
public void CreateSchema() { try { string databaseName = MongoUrl.Create(ConnectionString).DatabaseName; MongoClient client = new MongoClient(ConnectionString); MongoServer server = client.GetServer(); MongoDatabase database = server.GetDatabase(databaseName); database.DropCollection("Page"); database.DropCollection("PageContent"); database.DropCollection("User"); database.DropCollection("SiteConfiguration"); } catch (Exception e) { throw new DatabaseException(e, "Install failed: unable to connect to the database using {0} - {1}", ConnectionString, e.Message); } }
private void MenuItemBuildClientDocuments_Click(object sender, RoutedEventArgs e) { MongoDatabase lis = YellowstonePathology.Business.Mongo.MongoTestServer.Instance.LIS; lis.DropCollection("Client"); YellowstonePathology.Business.Mongo.ClientTransferBuilder clientTransferBuilder = new Business.Mongo.ClientTransferBuilder(); clientTransferBuilder.Build(); }
public void tearDown() { if (wammerDb.CollectionExists("attachments")) { wammerDb.DropCollection("attachments"); } server.Close(); }
public void DropCollection(String database, String collection) { MongoClient client = new MongoClient(connectionString); MongoServer server = client.GetServer(); server.Connect(); MongoDatabase test = server.GetDatabase(database); test.DropCollection(collection); }
public void Wipe() { try { string databaseName = MongoUrl.Create(ConnectionString).DatabaseName; MongoClient client = new MongoClient(ConnectionString); MongoServer server = client.GetServer(); MongoDatabase database = server.GetDatabase(databaseName); database.DropCollection(typeof(PageContent).Name); database.DropCollection(typeof(Page).Name); database.DropCollection(typeof(User).Name); database.DropCollection(typeof(SiteConfigurationEntity).Name); } catch (Exception ex) { throw new DatabaseException(ex, "An error occurred connecting to the MongoDB using the connection string {0}", ConnectionString); } }
/// <summary> /// 移除字段,备份为CollectionName_Legacy /// </summary> /// <param name="collectionName"></param> /// <param name="fieldName"></param> /// <param name="isBackUp">是否留存备份</param> public static void RemoveField(string collectionName, string fieldName, bool isBackUp = true) { MongoCollection targetCollection = InnerDefaultDatabase.GetCollection(collectionName); var docList = targetCollection.FindAllAs <BsonDocument>().ToList(); foreach (var item in docList) { item.Remove(fieldName); } var legacy = collectionName + "_Legacy_" + DateTime.Now.ToString("yyyyMMddHHmmss"); InnerDefaultDatabase.RenameCollection(collectionName, legacy); targetCollection = InnerDefaultDatabase.GetCollection(collectionName); targetCollection.InsertBatch(docList); if (!isBackUp) { InnerDefaultDatabase.DropCollection(legacy); } }
protected void DropCollections() { var roleProvider = new RoleProvider(); // roles var colName = Helper.GenerateCollectionName(_applicationName, RoleProvider.DEFAULT_ROLE_COLLECTION_SUFFIX); _db.DropCollection(colName); colName = Helper.GenerateCollectionName(_appName2, RoleProvider.DEFAULT_ROLE_COLLECTION_SUFFIX); _db.DropCollection(colName); // users colName = Helper.GenerateCollectionName(_applicationName, MembershipProvider.DEFAULT_USER_COLLECTION_SUFFIX); _db.DropCollection(colName); colName = Helper.GenerateCollectionName(_appName2, MembershipProvider.DEFAULT_USER_COLLECTION_SUFFIX); _db.DropCollection(colName); }
public void DropAndReCreateCollections() { if (mongoDatabase.CollectionExists(UserAuth_Col)) { mongoDatabase.DropCollection(UserAuth_Col); } if (mongoDatabase.CollectionExists(UserOAuthProvider_Col)) { mongoDatabase.DropCollection(UserOAuthProvider_Col); } if (mongoDatabase.CollectionExists(Counters_Col)) { mongoDatabase.DropCollection(Counters_Col); } CreateMissingCollections(); }
protected static void DropCollections(MongoDatabase db, params string[] collectionNames) { foreach (var collectionName in collectionNames) { if (db.CollectionExists(collectionName)) { db.DropCollection(collectionName); } } }
public BaseTest() { _bootstrapper = new BrowserTestBootstrapper(); _testDatabase = _bootstrapper.Database; _testDatabase.DropCollection("Authors"); _testDatabase.DropCollection("BlogPosts"); _browser = new Browser(_bootstrapper); //setting configuration AppConfiguration.Current.WebsiteUrl = ""; AppConfiguration.Current.WebsiteName = ""; AppConfiguration.Current.WebsiteDescription = ""; AppConfiguration.Current.WebsiteKeywords = ""; AppConfiguration.Current.DisqusShortName = ""; }
public void SavePortfolios(ObservableCollection <WorkspaceViewModel> portfolios) { _database.DropCollection("Portfolios"); _database.CreateCollection("Portfolios"); var collection = _database.GetCollection <PortfolioModel>("Portfolios"); foreach (PortfolioViewModel pvm in portfolios) { collection.Insert(pvm.GetPorfolioModel()); } }
/*public Tag BsonValueToTag(BsonValue item) * { * Tag tag = new Tag( * item["term"].AsString, * new Uri(item["scheme"].AsString), * item["label"].AsString); * * return tag; * } * * public IEnumerable<Tag> Tags() * { * return collection.Distinct(Field.CATEGORY).Select(BsonValueToTag); * } * * public IEnumerable<Tag> Tags(string resourcetype) * { * IMongoQuery query = MonQ.Query.EQ(Field.COLLECTION, resourcetype); * return collection.Distinct(Field.CATEGORY, query).Select(BsonValueToTag); * } * * public IEnumerable<Uri> Find(params Tag[] tags) * { * throw new NotImplementedException("Finding tags is not implemented on database level"); * } */ private void TryDropCollection(string name) { try { database.DropCollection(name); } catch { //don't worry. if it's not there. it's not there. } }
internal static MongoDbDataStore <FooModel> CreateDataStore() { client = new MongoClient(); server = client.GetServer(); server.Connect(); db = server.GetDatabase("qaudtest"); db.DropCollection("fooModel"); var dataStore = new MongoDbDataStore <FooModel>(db); return(dataStore); }
private void MenuItemBuildAccessionOrderDocuments_Click(object sender, RoutedEventArgs e) { MongoDatabase lis = YellowstonePathology.Business.Mongo.MongoTestServer.Instance.LIS; lis.DropCollection("AccessionOrder"); YellowstonePathology.Business.Mongo.AOTransferBuilder aoTransferBuilder = new Business.Mongo.AOTransferBuilder(); aoTransferBuilder.Build(); MessageBox.Show("All Done."); }
/// <summary> /// Drops all user defined collections from the database. Indexes and users are system collections and will not /// be affected. /// </summary> public void DropAllCollections() { foreach (var collectionName in _database.GetCollectionNames()) { if (collectionName.Contains("system.")) { //we are not allowed to remove or clear system collections continue; } _database.DropCollection(collectionName); } }
public MongoDocumentWriter(string connectionString, string databaseName, string collectionName) { var id = new ObjectId(); var server = new MongoClient(connectionString).GetServer(); _db = server.GetDatabase(databaseName); if (_db.CollectionExists(collectionName)) _db.DropCollection(collectionName); _db.CreateCollection(collectionName); _collection = _db.GetCollection(collectionName); }
public void TestDropCollection() { var collectionName = "testdropcollection"; Assert.IsFalse(database.CollectionExists(collectionName)); database[collectionName].Insert(new BsonDocument()); Assert.IsTrue(database.CollectionExists(collectionName)); database.DropCollection(collectionName); Assert.IsFalse(database.CollectionExists(collectionName)); }
public override void RankAchievements() { string databaseName = "Achievements"; if (ConfigurationManager.AppSettings["MongoDbName"] != null) { databaseName = ConfigurationManager.AppSettings["MongoDbName"]; } // TODO : Get connection string from app.config // TODO : Get database name from app.config MongoServer server = MongoServer.Create(ConfigurationManager.ConnectionStrings["AchievementDatabase"].ConnectionString); //server.Settings.SocketTimeout = new TimeSpan(TimeSpan.TicksPerMinute * 5); _database = server.GetDatabase(databaseName); if (_database.CollectionExists(AchievementUsageCollectionName)) { _database.DropCollection(AchievementUsageCollectionName); } MongoCollection<Character> characterCollection = _database.GetCollection<Character>(MongoCharacterRepository.CollectionName); characterCollection.MapReduce(_mapFunction, _reduceFunction, MapReduceOptions.SetOutput(AchievementUsageCollectionName)); MongoCollection<BsonDocument> ranking = _database.GetCollection(AchievementUsageCollectionName); IList<BsonDocument> rankings = ranking.FindAll().SetSortOrder(SortBy.Descending("value.count")).ToList(); int maxRank = 0; for (int i = 0; i < rankings.Count; i++) { int achievementId = Convert.ToInt32(rankings[i]["_id"].AsDouble); Achievement achievement = AchievementRepository.Find(achievementId); if (achievement != null) { achievement.Rank = i + 1; maxRank++; AchievementRepository.Save(achievement); } } var unrankedAchievements = AchievementRepository.FindAll().Where(a => a.Rank == 0); foreach (Achievement unrankedAchievement in unrankedAchievements) { unrankedAchievement.Rank = int.MaxValue; AchievementRepository.Save(unrankedAchievement); } }
/// <summary> /// Executes the command and returned the output documents /// </summary> /// <param name="db">The db to execute the command on</param> /// <returns></returns> public List<BsonDocument> Run(MongoDatabase db) { var ret = db.RunCommand(Build(), true); if (ret.Ok && ret.HasResponse) { callOk = true; if (ret.Response.Has("results")) { var docs = (ret.Response["results"] as object[]) .OfType<BsonDocument>() .ToList(); if (!string.IsNullOrEmpty(keyFieldName)) { var key = "value." + keyFieldName; foreach (var doc in docs) { doc[key] = doc["id"] = doc["_id"]; //id value is set to conform with the doc if read via select } return docs.Select(x => x["value"]).OfType<BsonDocument>().ToList(); } //if no key is specified, return the entire document. not just the value return docs; } else { var col = (string)ret.Response["result"]; var docs = db.GetCollection(col).Find().Select().OfType<BsonDocument>().ToList(); db.DropCollection(col); if (!string.IsNullOrEmpty(keyFieldName)) { var key = "value." + keyFieldName; foreach (var doc in docs) { doc[key] = doc["id"]; } return docs.Select(x=>x["value"]).OfType<BsonDocument>().ToList(); } //if no key is specified, return the entire document, not just the value return docs; } } callOk = false; //todo: log the error return null; }
private static void DropAndCreateCollections(MongoDatabase db, string[] collections) { string[] names = Enumerable.ToArray<string>(db.GetCollectionNames()); foreach (string name in names) { if (collections.Contains(name)) { db.DropCollection(name); } } foreach (string collection in collections) { db.CreateCollection(collection); } }