protected void LoadTimelineConcat() { // Response.Write("start "); MongoClient mclient = new MongoClient(GlobalVariables.mongolabConection); var db = mclient.GetDatabase(GlobalVariables.mongoDatabase); var collection = db.GetCollection<DocumentInfo>("DocumentsCollection"); var filter = Builders<DocumentInfo>.Filter.Eq("name", "Ilciuc"); //await collection.Find(new BsonDocument()).ForEachAsync(d => jsString += d+","); jsString = ""; collection.Find(new BsonDocument()).ForEachAsync(d => jsString += "{\"id\":\"" + ReplaceToHTML(d.id) + "\",\"title\" : \"" + ReplaceToHTML(d.title) + "\",\"startdate\" : \"" + d.startdate + "\",\"enddate\" : \"" + endDate(d.enddate) + "\",\"importance\" : \"" + 50 + "\",\"description\" : \"" + ReplaceToHTML(d.description) + "\",\"link\" : \"" + ReplaceToHTML(d.link) + "\",\"image\" : \"" + ReplaceToHTML(d.image) + "\"},").Wait(); //await collection.Find(filter).ForEachAsync(d => jsString += "{\"id\":\"" + d.id + "\",\"title\" : \"" + d.title + "\",\"startdate\" : \"" + d.startdate + "\",\"enddate\" : \"" + d.enddate + "\",\"importance\" : \"" + d.importance + "\",\"description\" : \"" + d.description + "\",\"link\" : \"" + d.link + "\",\"image\" : \"" + d.image + "\"},"); jsonData = "[{" + "\"id\": \"main_data\"," + "\"title\": \"TimeTrail\"," + "\"initial_zoom\": \"40\"," + //"\"focus_date\": \"1998-03-11 12:00:00\","+ "\"image_lane_height\": 50," + "\"events\":[" + jsString.TrimEnd(',') + "]" + "}]"; //Response.Write(" end"); }
public void Post(UserModel model) { var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017"); var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks"); BsonArray arr = new BsonArray(); dynamic jobj = JsonConvert.DeserializeObject<dynamic>(model.Movies.ToString()); foreach (var item in jobj) { foreach(var subitem in item) { arr.Add(subitem.Title.ToString()); } } var document = new BsonDocument { { "Facebook_ID", model.Facebook_ID }, { "Ime", model.Ime }, { "Prezime", model.Prezime }, { "Email", model.Email }, { "DatumRodjenja", model.DatumRodjenja }, { "Hometown", model.Hometown}, { "ProfilePictureLink", model.ProfilePictureLink }, { "Movies", arr }, }; var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo"); collection.InsertOneAsync(document); }
private static async Task MainAsync(string[] args) { var client = new MongoClient(); var db = client.GetDatabase("photos"); var albums = db.GetCollection<BsonDocument>("albums"); var result = await albums .Aggregate() .Unwind("images") .Group(@"{ _id: ""$images"" }") .ToListAsync(); var nonOrphansIds = result .Select((p) => (int)p["_id"]) .ToList(); var images = db.GetCollection<BsonDocument>("images"); var allImages = await images .Find(new BsonDocument()) .ToListAsync(); List<int> orphanIds = new List<int>(); foreach (var image in allImages) { int id = (int)image["_id"]; if (!nonOrphansIds.Contains(id)) { await images.DeleteOneAsync(string.Format(CultureInfo.InvariantCulture, "{{_id: {0}}}", id)); } } }
private void button10_Click(object sender, EventArgs e) { var client = new MongoClient("mongodb://localhost"); var database = client.GetDatabase("docs"); var fs = new GridFSBucket(database); //var aaa = fs.Find() var test = fs.DownloadAsBytesByName("Muzika"); MemoryStream memStream = new MemoryStream(test); //OpenFileDialog open = new OpenFileDialog(); //open.Filter = "Audio File (*.mp3;*.wav)|*.mp3;*.wav;"; //if (open.ShowDialog() != DialogResult.OK) return; DisposeWave(); // if (open.FileName.EndsWith(".mp3")) // { NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(memStream)); stream = new NAudio.Wave.BlockAlignReductionStream(pcm); // } // else if (open.FileName.EndsWith(".wav")) //{ // NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(open.FileName)); // stream = new NAudio.Wave.BlockAlignReductionStream(pcm); //} //else throw new InvalidOperationException("Not a correct audio file type."); output = new NAudio.Wave.DirectSoundOut(); output.Init(stream); output.Play(); }
public MongoDbDriver(string connectionString, string collectionName) { var builder = new SqlConnectionStringBuilder(connectionString); _client = new MongoClient(builder.DataSource); _database = _client.GetDatabase(builder.InitialCatalog); _collectionName = collectionName; }
public Logger(string logger) { var client = new MongoClient(Properties.Settings.Default.Mongo_log); _db = client.GetDatabase("patientcarelog"); _logCollection = _db.GetCollection<BsonDocument>("Logs"); _logger = logger; }
public async void TestMongoDB() { const string connectionString = "mongodb://localhost"; MongoClient client = new MongoClient(connectionString); IMongoDatabase database = client.GetDatabase("test"); IMongoCollection<Unit> collection = database.GetCollection<Unit>("Unit"); World world = World.Instance; // 加载配置 world.AddComponent<ConfigComponent>(); world.AddComponent<EventComponent<EventAttribute>>(); world.AddComponent<TimerComponent>(); world.AddComponent<UnitComponent>(); world.AddComponent<FactoryComponent<Unit>>(); world.AddComponent<BehaviorTreeComponent>(); world.AddComponent<NetworkComponent>(); world.Load(); Unit player1 = world.GetComponent<FactoryComponent<Unit>>().Create(UnitType.GatePlayer, 1); player1["hp"] = 10; await collection.InsertOneAsync(player1); Unit player3 = player1.Clone(); Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player3)); //Thread.Sleep(20 * 1000); //world.Load(); // //Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2)); }
static async Task MainAsync(string[] args) { var urlString = "mongodb://localhost:27017"; var client = new MongoClient(urlString); var db = client.GetDatabase("students"); var collection = db.GetCollection<BsonDocument>("grades"); var filter = new BsonDocument("type","homework"); // var count = 0; var sort = Builders<BsonDocument>.Sort.Ascending("student_id").Ascending("score"); var result = await collection.Find(filter).Sort(sort).ToListAsync(); var previous_id=-1 ; var student_id=-1; int count = 0; foreach (var doc in result) { student_id = (int)doc["student_id"]; //Console.WriteLine(student_id); if (student_id != previous_id) { count++; previous_id = student_id; Console.WriteLine("removing :{0} ", doc); // await collection.DeleteOneAsync(doc); await collection.DeleteManyAsync(doc); } // process document } Console.WriteLine(count); //Console.WriteLine(coll.FindAsync<"">); }
/// <summary /> public PatientRepository() { var client = new MongoClient(ConfigurationManager.ConnectionStrings["Mongo_patientcare_datamock"].ConnectionString); _log = new Logger("WebAPI : PatientRepository"); _db = client.GetDatabase("patientcare_datamock"); _patients = _db.GetCollection<BsonDocument>("Patients"); }
public async Task<ActionResult> AddWord() { var client = new MongoClient(_connection); var db = client.GetDatabase(_database); var words = db.GetCollection<BsonDocument>("Word"); var word1 = new Word { Text = "Ape", Type = Enums.WordType.Noun.ToString() }; var bsonObject = word1.ToBsonDocument(); try { await words.InsertOneAsync(bsonObject); } catch (Exception ex) { return Json(ex.Message, JsonRequestBehavior.AllowGet); } return Json("success", JsonRequestBehavior.AllowGet); }
public IMongoDatabase GetDatabase() { var client = new MongoClient(this.ConnectionString); var db = client.GetDatabase(this.DatabaseName); return db; }
public TodoItemRepository(string mongoConnection, string databaseName) { collectionName = "todoitems"; var client = new MongoClient(mongoConnection); this.database = client.GetDatabase(databaseName); this.collection = database.GetCollection<TodoItem>(collectionName); }
private static IMongoCollection<FormMongoEntity> GetCollection() { var client = new MongoClient(); var db = client.GetDatabase("joinzjazure"); var collection = db.GetCollection<FormMongoEntity>("Forms"); return collection; }
/// <summary> /// /// </summary> /// <param name="args">[repository] [source collection name] [target collection name]</param> /// <returns></returns> public async Task RunAsync(string[] args) { var repository = args[0]; var sourceCollectionName = args[1]; var targetCollectionName = args[2]; var client = new MongoClient(_connectionStringProvider.GetConnectionString(repository)); IMongoDatabase _database = client.GetDatabase(repository); IMongoCollection<BsonDocument> targetCollection = _database.GetCollection<BsonDocument>(targetCollectionName); IMongoCollection<BsonDocument> sourceCollection = _database.GetCollection<BsonDocument>(sourceCollectionName); await sourceCollection.Find(new BsonDocument()).ForEachAsync(async (thread) => { foreach (var user in thread.GetElement(targetCollectionName).Value.AsBsonArray) { var filter = Builders<BsonDocument>.Filter.Eq("id", user.ToBsonDocument().GetElement("id").Value); var count = await targetCollection.Find(filter).CountAsync(); if (count == 0) { await targetCollection.InsertOneAsync(user.ToBsonDocument()); } } }); }
/// <summary> /// Gets the mongo connection. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> internal static MongoDatabase GetMongoConnection(String connectionString) { UserClassMap.Register(); var mongoUrl = MongoUrl.Create(connectionString); var server = new MongoClient(connectionString).GetServer(); return server.GetDatabase(mongoUrl.DatabaseName); }
// ---- Ubacivanje podataka u bazi ---- private void BtnSubmitData_Click(object sender, EventArgs e) { // ---- Provera ispravnosti podataka ---- if (String.IsNullOrWhiteSpace(TbPunoIme.Text)) { MessageBox.Show("Unesi Puno ime trenera!"); return; } else if (String.IsNullOrWhiteSpace(TbMestoRodjenja.Text)) { MessageBox.Show("Unesi mesto rodjenja trenera!"); return; } else if (String.IsNullOrWhiteSpace(TbTrenutniKlub.Text)) { MessageBox.Show("Unesi trenutni klub(reprezentaciju) koju trenira trener!"); return; } Trener forSave = new Trener(); forSave.PunoIme = StringCleaner.checkString(TbPunoIme.Text); forSave.MestoRodjenja = StringCleaner.checkString(TbMestoRodjenja.Text); forSave.TrenutniKlub = StringCleaner.checkString(TbTrenutniKlub.Text); forSave.TrenerskaKarijera = StringCleaner.checkString(RtbTrenerskaKarijera.Text); forSave.Uspesi = StringCleaner.checkString(RtbUspesi.Text); forSave.DatumRodjenja = StringCleaner.checkString(dateTimePicker1.Value.ToShortDateString()); var _client = new MongoClient(); var _database = _client.GetDatabase("test"); var collection = _database.GetCollection<BsonDocument>("treneri"); var filter = new BsonDocument() { {"PunoIme",TbPunoIme.Text} }; var filterForUniqueCheck = Builders<BsonDocument>.Filter.Eq("PunoIme", this.TbPunoIme.Text); var document = forSave.ToBsonDocument(); //test if exists var test = collection.Find(filterForUniqueCheck).Count(); if(test == 0) { collection.InsertOne(document); if (slikaTrenera != null) { AuxLib.AddImageToGridFS(slikaTrenera, forSave.PunoIme, format); } MessageBox.Show("Uspesno dodat novi trener!"); } else { //TO DO : URADITI UPDATE SLIKE (AuxLib treba da ima remove image i remove mp3 i da se izbaci slika i ubaci nova); collection.ReplaceOne(filter, document); MessageBox.Show("Uspesno azuriran trener!"); } }
public LogEntryRepository(MongoClient mongoClient, IConfiguration configuration, string databaseName = "Kelpie") { _mongoClient = mongoClient; _configuration = configuration; _database = _mongoClient.GetDatabase(databaseName); _collection = _database.GetCollection<LogEntry>("LogEntry"); }
static void Main(string[] args) { var client = new MongoClient(); var db = client.GetDatabase("CustomerDb"); var CustColl = db.GetCollection<Customer>("Customer"); // query customer var customerID = new ObjectId("xxx"); var customers = CustColl .Find(c => c.Id == customerID) .SortBy(c => c.fullName) .Limit(3) .ToListAsync() .Result; foreach (var customer in customers) { Console.WriteLine(customer.fullName); } //Update Customer var cust = customers.First(); cust.fullName = cust.fullName.ToUpper(); }
public async Task<UserModel> Get(string Facebook_ID) { var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017"); var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks"); string facebookID = '"' + Facebook_ID + '"'; UserModel user = new UserModel(); int i = 0; var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo"); var filter = Builders<BsonDocument>.Filter.Eq("Facebook_ID", facebookID); var result = await collection.Find(filter).ToListAsync(); foreach (BsonDocument item in result) { user.Facebook_ID = item.GetElement("Facebook_ID").Value.ToString(); user.Ime = item.GetElement("Ime").Value.ToString(); user.Prezime = item.GetElement("Prezime").Value.ToString(); user.Email = item.GetElement("Email").Value.ToString(); user.DatumRodjenja = item.GetElement("DatumRodjenja").Value.ToString(); user.Hometown = item.GetElement("Hometown").Value.ToString(); user.ProfilePictureLink = item.GetElement("ProfilePictureLink").Value.ToString(); // foreach (var movie in item.GetElement("Movies").Value.AsBsonArray) // { // user.Movies[i] = movie.ToString(); // i++; // } i = 0; user._id = item.GetElement("_id").Value.ToString(); } var json = new JavaScriptSerializer().Serialize(user); return user; }
private async Task MainAsync() { var connStr = "mongodb://localhost:27017"; var client = new MongoClient(connStr); var db = client.GetDatabase("store"); var col = db.GetCollection<Product>("products"); await db.DropCollectionAsync("products"); Random random = new Random(); List<string> descriptions = new List<string>() { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj" }; List<string> categories = new List<string>() { "sports", "food", "clothing", "electronics" }; List<string> brands = new List<string>() { "GE", "nike", "adidas", "toyota", "mitsubishi" }; var docs = Enumerable.Range(0, 100) .Select(i => new Product { Id = i, SKU = String.Format("{0:D8}", i), Price = random.NextDouble() * (100 - 1) + 1, Description = descriptions[random.Next(descriptions.Count)], Category = categories[random.Next(categories.Count)], Brand = brands[random.Next(brands.Count)], Reviews = new List<Review>(), }); await col.InsertManyAsync(docs); await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.SKU), new CreateIndexOptions() { Unique = true }); await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Descending(x => x.Price)); await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.Description)); await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.Category).Ascending(x => x.Brand)); await col.Indexes.CreateOneAsync("{'reviews.author':1}"); }
public MongoDbBase(string connectionString, string database) { this.connectionString = connectionString; this.database = database; Client = new MongoClient(connectionString); Database = Client.GetDatabase(database); }
public static int Main(string[] args) { var client = new MongoClient(""); var db = client.GetDatabase("guess-what"); var templateCollection = db.GetCollection<BsonDocument>("templates"); // Use this to delete single items or spam: // templateCollection.DeleteOne(new BsonDocument(new BsonElement("_id", BsonValue.Create("Zp-ifMYR_0W6D0GwKsuoSw")))); // templateCollection.DeleteOne(new BsonDocument(new BsonElement("_id", BsonValue.Create("Ss0ISYQbSEyUsYVnMjbDAw")))); /* var regex = new Regex("^<a href=\"http://.*#\\d*\">.*</a>,$"); foreach (var template in templateCollection.Find(new BsonDocument()).ToList()) { var description = template.GetElement("Description").Value.ToString().Trim(); if (regex.Matches(description).Count > 0) { templateCollection.DeleteOne(new BsonDocument (template.GetElement("_id"))); } else { Console.WriteLine("OK :" + description); } } */ Console.WriteLine("END."); Console.ReadLine(); return 0; }
public GameInfoActor(String gameId) { _gameId = gameId; _dict = new Dictionary<String, String>(); var url = new MongoUrl("mongodb://localhost:27020/BaseballRetro"); var client = new MongoClient(url); var db = client.GetDatabase(url.DatabaseName); Receive<GameInfoMessage>(msg => { _dict.Add(msg.Key, msg.Value); if (msg.Key.Equals("visteam", StringComparison.OrdinalIgnoreCase)) { _visitor = msg.Value; } if (msg.Key.Equals("hometeam", StringComparison.OrdinalIgnoreCase)) { _home = msg.Value; } }); Receive<GameInfoSaveMessage>(msg => { var coll = db.GetCollection<GameInfo>("gameInfo"); coll.InsertOneAsync(new GameInfo(_gameId, _home, _visitor, _dict)).Wait(); }); }
public ClothesDbContext(string connectionString) { var mongoClient = new MongoClient(connectionString); _mongoDatabase = mongoClient.GetDatabase("ClothesWashing"); RegisterClassMaps(); }
private IMongoDatabase Connect() { var client = new MongoClient(connectionString); var database = client.GetDatabase(databaseName); return database; }
static void Main(string[] args) { //var mongoDB_MongoLab = "mongodb://*****:*****@ds061158.mongolab.com:61158/teste"; var mongoDB_Local = "mongodb://localhost"; var mongoDB = mongoDB_Local; var client = new MongoClient(mongoDB); var db = client.GetDatabase("teste"); var clienteCollection = db.GetCollection<Cliente>("cliente"); var novoCliente = new Cliente() { Nome = "Carlos" }; clienteCollection.InsertOne(novoCliente); var id = novoCliente.Id; var filter = Builders<Cliente>.Filter.Eq("Nome", "Carlos"); var cli1 = clienteCollection.Find<Cliente>(filter).FirstOrDefault(); if (cli1 != null) { var update = Builders<Cliente>.Update.Set("Nome", "Carlos dos Santos"); clienteCollection.UpdateOne(filter, update); } var dados = clienteCollection.Find<Cliente>(new BsonDocument()).ToListAsync().Result; foreach (var c in dados) { Console.WriteLine("{0} - {1}",c.Id,c.Nome); } }
public void Initialize() { var connect = "mongodb://localhost"; _client = new MongoClient(connect); _db = _client.GetDatabase("local"); _collection = _db.GetCollection<Person>("Person"); }
public virtual List<Guitar> Select() { var client = new MongoClient("mongodb://localhost/"); var database = client.GetDatabase("GuitarApiDB"); var collection = database.GetCollection<Guitar>("Products"); return collection.Find(_ => true).ToListAsync().Result; }
public void AddTool() { var client = new MongoDB.Driver.MongoClient("mongodb://localhost:27017"); var datebase = client.GetDatabase("Slownik"); var collection = datebase.GetCollection <Tool>("Narzędzia"); var filter = new BsonDocument(); filter.Set("EN", "Hamer"); Tool t1 = new Tool(); t1.CodeTool = "001"; ToolTranslate f = new ToolTranslate(); ICollection <ToolTranslate> tt = new List <ToolTranslate> { new ToolTranslate() { EN = "Hamer", PL = "Młotek" } }; t1.Tanslate = tt; collection.InsertOne(t1); Tool t2 = new Tool(); t2.CodeTool = "002"; ToolTranslate f1 = new ToolTranslate(); ICollection <ToolTranslate> tt2 = new List <ToolTranslate> { new ToolTranslate() { PL = "śrubokrętr", EN = "screwdriver", SE = "skruvmejsel" } }; t2.Tanslate = tt2; collection.InsertOne(t2); Tool t3 = new Tool(); t3.CodeTool = "003"; ToolTranslate f2 = new ToolTranslate(); ICollection <ToolTranslate> tt3 = new List <ToolTranslate> { new ToolTranslate() { PL = "Wiertarka" } }; t3.Tanslate = tt3; collection.InsertOne(t3); Tool t4 = new Tool(); t4.CodeTool = "004"; ToolTranslate f3 = new ToolTranslate(); ICollection <ToolTranslate> tt4 = new List <ToolTranslate> { new ToolTranslate() { ES = "vicio" } }; t4.Tanslate = tt4; collection.InsertOne(t4); var te = from t in collection.AsQueryable <Tool>() where t.Tanslate.Any(c => c.PL == "Młotek") select t; foreach (Tool t in te) { string name = t.CodeTool; int g = 0; } }
public bool DeletePoint(Point point) { try { #region Validations List <Point> points = new PointRepository().GetAllPoints().ToList(); if (!points.Exists(p => p.Id == point.Id)) { return(false); } #endregion Validations #region Cache Storage if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "CACHE") { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Point[])ctx.Cache[CacheKey]).ToList(); if (currentData.Exists(p => p.Id == point.Id)) { currentData.RemoveAt(currentData.FindIndex(p => p.Id == point.Id)); } ctx.Cache[CacheKey] = currentData.ToArray(); return(true); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(false); } } } #endregion #region DB Storage MySQl else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MYSQL") { try { var dbCon = DBConnection.Instance(); if (dbCon.IsConnect()) { string query = "DELETE FROM `ROUTES` WHERE IdSource=" + point.Id + " OR IdDestination = " + point.Id; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteNonQuery(); query = "DELETE FROM `POINTS` WHERE Id=" + point.Id; cmd = new MySqlCommand(query, dbCon.Connection); reader = cmd.ExecuteNonQuery(); dbCon.Close(); if (reader == 1) { return(true); } else { return(false); } } } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } #endregion DB Storage MySQl #region DB Storage Mongo else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MONGO") { var dbCon = DBConnectionMongo.Instance(); MongoDB.Driver.MongoClient client = dbCon.GetClient(); client.StartSession(); var collectionR = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Route>("ROUTES"); var Deleteall = collectionR.DeleteMany(Builders <Route> .Filter.Or( Builders <Route> .Filter.Eq("IdSource", point.Id), Builders <Route> .Filter.Eq("IdDestination", point.Id))); var collection = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Point>("POINTS"); var Deleteone = collection.DeleteOneAsync(Builders <Point> .Filter.Eq("Id", point.Id)); return(true); } #endregion DB Storage Mongo } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); } return(false); }
public Route[] GetAllRoutes() { List <Route> allRoutes = new List <Route>(); try { #region Cache Storage if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "CACHE") { var ctx = HttpContext.Current; if (ctx != null) { return((Route[])ctx.Cache[CacheKey]); } return(new Route[] { new Route { IdSource = 0, IdDestination = 0, RouteCost = 0, RouteTime = 0 } }); } #endregion #region DB Storage MySQl else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MYSQL") { var dbCon = DBConnection.Instance(); if (dbCon.IsConnect()) { //suppose col0 and col1 are defined as VARCHAR in the DB string query = "SELECT IdSource,IdDestination,RouteCost,RouteTime Name FROM ROUTES"; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteReader(); while (reader.Read()) { Route route = new Route(); route.IdSource = reader.GetInt32(0); route.IdDestination = reader.GetInt32(1); route.RouteCost = reader.GetInt32(2); route.RouteTime = reader.GetInt32(3); allRoutes.Add(route); } dbCon.Close(); } } #endregion DB Storage MySQl #region DB Storage Mongo else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MONGO") { var dbCon = DBConnectionMongo.Instance(); MongoDB.Driver.MongoClient client = dbCon.GetClient(); client.StartSession(); var collection = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Route>("ROUTES"); allRoutes = collection.Find(_ => true).ToList(); } #endregion DB Storage Mongo } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); } return(allRoutes.ToArray()); }
public bool SavePoint(Point point) { try { #region Validations List <Point> points = new PointRepository().GetAllPoints().ToList(); if (points.Exists(p => p.Name == point.Name)) { return(false); } #endregion Validations #region Cache Storage if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "CACHE") { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Point[])ctx.Cache[CacheKey]).ToList(); if (point.Id == -1) { var maxItemID = currentData.Max(x => x.Id); point.Id = maxItemID + 1; } currentData.Add(point); ctx.Cache[CacheKey] = currentData.ToArray(); return(true); } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } } #endregion #region DB Storage MySQl else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MYSQL") { try { var dbCon = DBConnection.Instance(); if (dbCon.IsConnect()) { //suppose col0 and col1 are defined as VARCHAR in the DB string query = "INSERT INTO `POINTS`(`Name`) VALUES ('" + point.Name + "')"; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteNonQuery(); dbCon.Close(); return(true); } } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } #endregion DB Storage MySQl #region DB Storage Mongo else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MONGO") { var dbCon = DBConnectionMongo.Instance(); MongoDB.Driver.MongoClient client = dbCon.GetClient(); client.StartSession(); point.Id = Convert.ToInt32(Sequence.GetNextSequenceValue("pointid", client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]))); var collection = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Point>("POINTS"); collection.InsertOne(point); return(true); } #endregion DB Storage Mongo } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); } return(false); }
public bool DeleteRoute(Route route) { try { #region Validations List <Route> routes = new RouteRepository().GetAllRoutes().ToList(); if (!routes.Exists(r => r.IdSource == route.IdSource && r.IdDestination == route.IdDestination)) { return(false); } #endregion Validations #region Cache Storage if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "CACHE") { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Route[])ctx.Cache[CacheKey]).ToList(); if (currentData.Exists(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)) { currentData.RemoveAt(currentData.FindIndex(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)); } ctx.Cache[CacheKey] = currentData.ToArray(); return(true); } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } } #endregion #region DB Storage MySQl else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MYSQL") { try { var dbCon = DBConnection.Instance(); if (dbCon.IsConnect()) { //suppose col0 and col1 are defined as VARCHAR in the DB string query = "DELETE FROM `ROUTES` WHERE IdSource = " + route.IdSource + " AND IdDestiny = " + route.IdDestination; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteNonQuery(); dbCon.Close(); return(true); } } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } #endregion DB Storage MySQl #region DB Storage Mongo else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MONGO") { var dbCon = DBConnectionMongo.Instance(); MongoDB.Driver.MongoClient client = dbCon.GetClient(); client.StartSession(); var collection = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Route>("ROUTES"); var Deleteone = collection.DeleteOneAsync(Builders <Route> .Filter.And( Builders <Route> .Filter.Eq("IdSource", route.IdSource), Builders <Route> .Filter.Eq("IdDestination", route.IdDestination))); return(true); } #endregion DB Storage Mongo } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); } return(false); }
public bool UpdateRoute(Route route) { try { #region Validations List <Route> routes = new RouteRepository().GetAllRoutes().ToList(); if (!routes.Exists(r => r.IdSource == route.IdSource && r.IdDestination == route.IdDestination)) { return(false); } #endregion Validations #region Cache Storage if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "CACHE") { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Route[])ctx.Cache[CacheKey]).ToList(); if (currentData.Exists(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)) { if (currentData[currentData.FindIndex(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)].RouteCost != route.RouteCost && route.RouteCost > 0) { currentData[currentData.FindIndex(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)].RouteCost = route.RouteCost; } if (currentData[currentData.FindIndex(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)].RouteTime != route.RouteTime && route.RouteTime > 0) { currentData[currentData.FindIndex(p => p.IdSource == route.IdSource && p.IdDestination == route.IdDestination)].RouteTime = route.RouteTime; } } ctx.Cache[CacheKey] = currentData.ToArray(); return(true); } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } } #endregion #region DB Storage MySQl else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MYSQL") { try { var dbCon = DBConnection.Instance(); if (dbCon.IsConnect()) { if (!string.IsNullOrEmpty(route.RouteCost.ToString())) { if (route.RouteCost > 0) { string query = "UPDATE `ROUTES` SET `RouteCost`=" + route.RouteCost + "ss WHERE IdSource=" + route.IdSource + " AND IdDestiny = " + route.IdDestination; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteNonQuery(); } } if (!string.IsNullOrEmpty(route.RouteTime.ToString())) { if (route.RouteTime > 0) { string query = "UPDATE `ROUTES` SET `RouteTime`=" + route.RouteTime + " WHERE IdSource=" + route.IdSource + " AND IdDestiny = " + route.IdDestination; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteNonQuery(); } } dbCon.Close(); return(true); } } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } #endregion DB Storage MySQl #region DB Storage Mongo else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MONGO") { var dbCon = DBConnectionMongo.Instance(); MongoDB.Driver.MongoClient client = dbCon.GetClient(); client.StartSession(); var collection = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Route>("ROUTES"); if (!string.IsNullOrEmpty(route.RouteCost.ToString())) { if (route.RouteCost > 0) { var updoneresult = collection.UpdateOneAsync(Builders <Route> .Filter.And( Builders <Route> .Filter.Eq("IdSource", route.IdSource), Builders <Route> .Filter.Eq("IdDestination", route.IdDestination)), Builders <Route> .Update.Set("RouteCost", route.RouteCost)); } } if (!string.IsNullOrEmpty(route.RouteTime.ToString())) { if (route.RouteTime > 0) { var updoneresult = collection.UpdateOneAsync(Builders <Route> .Filter.And( Builders <Route> .Filter.Eq("IdSource", route.IdSource), Builders <Route> .Filter.Eq("IdDestination", route.IdDestination)), Builders <Route> .Update.Set("RouteTime", route.RouteTime)); } } return(true); } #endregion DB Storage Mongo } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); } return(false); }
public ActionResult <IEnumerable <Aluno> > Get() { var listaAlunos = _mongoDbClient.GetDatabase("admin").GetCollection <Aluno>("aluno").Find(Builders <Aluno> .Filter.Where(it => it.Idade > 0)).ToList(); return(listaAlunos); }
public bool SaveRoute(Route route) { try { #region Validations List <Point> points = new PointRepository().GetAllPoints().ToList(); if (!points.Exists(p => p.Id == route.IdSource)) { return(false); } else if (!points.Exists(p => p.Id == route.IdDestination)) { return(false); } List <Route> routes = new RouteRepository().GetAllRoutes().ToList(); if (routes.Exists(r => r.IdSource == route.IdSource && r.IdDestination == route.IdDestination)) { return(false); } #endregion Validations #region Cache Storage if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "CACHE") { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Route[])ctx.Cache[CacheKey]).ToList(); currentData.Add(route); ctx.Cache[CacheKey] = currentData.ToArray(); return(true); } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } } #endregion #region DB Storage MySQl else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MYSQL") { try { var dbCon = DBConnection.Instance(); if (dbCon.IsConnect()) { //suppose col0 and col1 are defined as VARCHAR in the DB string query = "INSERT INTO `ROUTES`(`IdSource`, `IdDestination`, `RouteCost`, `RouteTime`) VALUES (" + route.IdSource + "," + route.IdDestination + "," + route.RouteCost + "," + route.RouteTime + ")"; var cmd = new MySqlCommand(query, dbCon.Connection); var reader = cmd.ExecuteNonQuery(); dbCon.Close(); return(true); } } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); return(false); } } #endregion DB Storage MySQl #region DB Storage Mongo else if (ConfigurationManager.AppSettings["dbType"].ToUpper() == "DB_MONGO") { var dbCon = DBConnectionMongo.Instance(); MongoDB.Driver.MongoClient client = dbCon.GetClient(); client.StartSession(); var collection = client.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"]).GetCollection <Route>("ROUTES"); collection.InsertOne(route); return(true); } #endregion DB Storage Mongo } catch (Exception ex) { new DeliveryWService.Services.LogService(true).Error(DeliveryWService.Services.LogServiceAux.GetCurrentMethod() + " - " + ex.Message); } return(false); }
public void GenerateAccentureReport() { using (FileStream stream = new FileStream(@"C:\Temp\AccentureReport.xlsx", FileMode.Create)) { using (var package = new ExcelPackage(stream)) { var wb = package.Workbook; var ws = wb.Worksheets.Add("Test Execution"); //TestCaseExecutionId TestCaseName Phase Status Priority Cycle ExecutionPlannedDate ExecutionActualDate LoggedOn LoggedBy MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); var db = client.GetDatabase("tosca"); var reportableObjects = db.GetCollection <ReportableObject>("reportable_objects"); #region Test Execution var executionLogs = reportableObjects.FindSync <ReportableObject>(Builders <ReportableObject> .Filter.Eq <string>("Type", "Execution Test Case Log")).ToList(); ws.Cells[1, 1].Value = "TestCaseExecutionId"; ws.Cells[1, 2].Value = "TestCaseName"; ws.Cells[1, 3].Value = "Phase"; ws.Cells[1, 4].Value = "Status"; ws.Cells[1, 5].Value = "Priority"; ws.Cells[1, 6].Value = "Cycle"; ws.Cells[1, 7].Value = "ExecutionPlannedDate"; ws.Cells[1, 8].Value = "ExecutionActualDate"; ws.Cells[1, 9].Value = "LoggedOn"; ws.Cells[1, 10].Value = "LoggedBy"; ws.Cells[1, 11].Value = "ExecutedTestCase"; for (int i = 0; i < executionLogs.Count; i++) { ReportableObject log = executionLogs[i]; ws.Cells[i + 2, 1].Value = log.ID; ws.Cells[i + 2, 2].Value = log["DisplayedName"]; ws.Cells[i + 2, 3].Value = "Product Test"; ws.Cells[i + 2, 4].Value = log["Result"]; ws.Cells[i + 2, 5].Value = "Medium"; ws.Cells[i + 2, 6].Value = "1"; ws.Cells[i + 2, 7].Value = log["EndTime"]; ws.Cells[i + 2, 7].Style.Numberformat.Format = "dd-mmm-yyyy"; ws.Cells[i + 2, 8].Value = log["EndTime"]; ws.Cells[i + 2, 8].Style.Numberformat.Format = "dd-mmm-yyyy"; ws.Cells[i + 2, 9].Value = log["StartTime"]; ws.Cells[i + 2, 9].Style.Numberformat.Format = "dd-mmm-yyyy"; ws.Cells[i + 2, 10].Value = log["UserName"]; ws.Cells[i + 2, 11].Value = log["ExecutedTestCase"]; } #endregion #region Test Cases var testCases = reportableObjects.Find(x => x.Type == "Test Case").ToList(); ws = wb.Worksheets.Add("Test Cases"); ws.Cells[1, 1].Value = "TestCaseId"; ws.Cells[1, 2].Value = "TestCaseName"; ws.Cells[1, 3].Value = "TestCaseDescription"; ws.Cells[1, 4].Value = "Phase"; ws.Cells[1, 5].Value = "Priority"; ws.Cells[1, 6].Value = "Status"; ws.Cells[1, 7].Value = "IsAutomated"; ws.Cells[1, 8].Value = "CarryForwardFlag"; ws.Cells[1, 9].Value = "Cycle"; ws.Cells[1, 10].Value = "TestExecutionPlannedDate"; ws.Cells[1, 11].Value = "LoggedBy"; ws.Cells[1, 12].Value = "LoggedOn"; ws.Cells[1, 13].Value = "Requirement"; for (int i = 0; i < testCases.Count; i++) { ReportableObject log = testCases[i]; var reqFilter = Builders <ReportableObject> .Filter.ElemMatch(x => x.Links, x => x.LinkDescription.Description == "Linked Test Cases" && x.LinkedObjects.Contains(log.ID)); var reqs = reportableObjects.Find(reqFilter).ToList(); ws.Cells[i + 2, 1].Value = log.ID; ws.Cells[i + 2, 2].Value = log["DisplayedName"]; ws.Cells[i + 2, 3].Value = log["Description"]; ws.Cells[i + 2, 4].Value = "Product Test"; ws.Cells[i + 2, 5].Value = "Medium"; ws.Cells[i + 2, 6].Value = "Created"; ws.Cells[i + 2, 7].Value = "No"; ws.Cells[i + 2, 8].Value = "No"; ws.Cells[i + 2, 9].Value = "1"; ws.Cells[i + 2, 10].Value = ""; ws.Cells[i + 2, 11].Value = "Admin"; ws.Cells[i + 2, 12].Value = ""; if (reqs.Count > 0) { ws.Cells[i + 2, 13].Value = reqs.Select(x => x.ID).Aggregate((x, y) => $"{x},{y}"); } } var reqWS = wb.Worksheets.Add("Requirements"); var allReqs = reportableObjects.Find(x => x.Type == "Requirement").ToList(); for (int i = 0; i < allReqs.Count; i++) { var req = allReqs[i]; for (int j = 0; j < req.Properties.Count; j++) { if (i == 0) { if (j == 0) { reqWS.Cells[1, 1].Value = "ID"; } reqWS.Cells[1, j + 2].Value = req.Properties[j].Name; } if (j == 0) { reqWS.Cells[i + 2, 1].Value = req.ID; } reqWS.Cells[i + 2, j + 2].Value = req.Properties[j].Value; } } #endregion package.Save(); } } }
public async Task <IActionResult> Generate(ObjectId memoryId) { var client = new MongoDB.Driver.MongoClient("mongodb://*****:*****@localhost/?safe=true"); var db = client.GetDatabase("memoryvault"); var coll = db.GetCollection <MemoryItemModel>("memories"); var founds = coll.Find(p => p.Id == memoryId).FirstOrDefault(); if (founds == null) { return(NotFound("File not found.")); } GridFSBucketOptions opts = new GridFSBucketOptions(); opts.BucketName = "memoryfiles"; var bucket = new GridFSBucket(db, opts); bool isChanged = false; List <ThumbnailItemModel> lstThumbs = new List <ThumbnailItemModel>(); foreach (ThumbnailSizes size in Enum.GetValues(typeof(ThumbnailSizes))) { using (var stream = bucket.OpenDownloadStream(founds.ItemId)) { var dimension = GetDimension(size); using (Image <Rgba32> bg = new Image <Rgba32>(dimension, dimension)) { try { using (Image <Rgba32> image = Image.Load(stream)) //open the file and detect the file type and decode it { int iWidth; int iHeight; int margin = 3; float ratio = (float)image.Width / (float)image.Height; if (ratio > 1) { iWidth = dimension - 2 * margin; iHeight = (int)(iWidth / ratio); } else { iHeight = dimension - 2 * margin; iWidth = (int)(iHeight * ratio); } // image is now in a file format agnostic structure in memory as a series of Rgba32 pixels image.Mutate(ctx => ctx.Resize(iWidth, iHeight)); // resize the image in place and return it for chaining bg.Mutate(ctx => ctx.Fill(Rgba32.Black)); int pX = (int)((dimension - iWidth) / 2); int pY = (int)((dimension - iHeight) / 2); bg.Mutate(ctx => ctx.DrawImage(image, PixelBlenderMode.Normal, 1, new SixLabors.Primitives.Point(pX, pY))); //var thPath = $"c:/temp/thumbs/th.{memoryId}.{DateTime.Now.ToString("MMDD_HHmmsss")}.{(ThumbnailSizes)size}.png"; //using (var fs = new System.IO.FileStream(thPath, FileMode.CreateNew)) //{ // bg.SaveAsPng(fs); // based on the file extension pick an encoder then encode and write the data to disk // await fs.FlushAsync(); // fs.Close(); //} using (var ms = new MemoryStream()) { bg.SaveAsPng(ms); lstThumbs.Add(new ThumbnailItemModel { CreateTime = DateTime.Now, Size = size, Data = ms.ToArray() }); isChanged = true; } } } catch (Exception exc) { Debug.WriteLine(exc.Message); } } } } if (isChanged) { await coll.UpdateOneAsync( p => p.Id == memoryId , Builders <MemoryItemModel> .Update.AddToSetEach(s => s.Thumbnails, lstThumbs) ); } return(Ok()); }
public MongoDbStoreStrategy(string databasename, MongoDatabaseSettings settings) { MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); database = client.GetDatabase(databasename, settings); }
public MDB() { client = new MongoClient("mongodb://10.0.0.100/MBM"); db = client.GetDatabase("MBM"); }
public async Task <IActionResult> Upload() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest()); } try { if (!Request.Form.Files.Any()) { return(BadRequest("There is no file.")); } var client = new MongoDB.Driver.MongoClient("mongodb://*****:*****@localhost/?safe=true"); var db = client.GetDatabase("memoryvault"); var coll = db.GetCollection <MemoryItemModel>("memories"); foreach (var fileReq in Request.Form.Files) { GridFSBucketOptions opts = new GridFSBucketOptions(); opts.BucketName = "memoryfiles"; var bucket = new GridFSBucket(db, opts); ObjectId res; using (var stream = fileReq.OpenReadStream()) { res = await bucket.UploadFromStreamAsync(fileReq.FileName, stream); } var ext = System.IO.Path.GetExtension(fileReq.FileName); var memory = new MemoryItemModel { CreateTime = DateTime.Now, ItemId = res, FileName = fileReq.FileName, FileExtension = ext }; await coll.InsertOneAsync(memory); QueueRepository.Enqueue(new CreateThumbnailCommand { MemoryId = memory.Id.ToString() }); } } catch (MongoWriteException exc) { if (((MongoBulkWriteException)exc.InnerException).WriteErrors.Any(p => p.Category == ServerErrorCategory.DuplicateKey)) { return(Ok()); } return(Ok(exc.Message)); } catch (Exception exc) { return(Ok(exc.Message)); } return(Ok()); }
public EntityModelsController() { MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); _db = client.GetDatabase(ConfigurationManager.AppSettings["dbname"]); _models = _db.GetCollection <EntityDefinition>("entity_definitions"); }
public static string CreateContact(ContactPersonOrganization newContact) { MongoClient client = new MongoClient(); IMongoDatabase database = client.GetDatabase("GCCHRConnectDB"); IMongoCollection<ContactPersonOrganization> collection = database.GetCollection<ContactPersonOrganization>(ContactPersonOrganization.TableOrCollectionName); collection.InsertOne(newContact); IMongoDatabase database1 = client.GetDatabase("TestDB"); IMongoCollection<BsonDocument> collection1 = database1.GetCollection<BsonDocument>(ContactPersonOrganization.TableOrCollectionName); BsonDocument TestDoc = new BsonDocument("SampleKey", 12); collection1.InsertOne(TestDoc); return newContact.Id; }
protected void SetUp() { var f = new FileStream("config.json", FileMode.Open); var sr = new StreamReader(f); try { var settings = JsonConvert .DeserializeObject<MongoSettings>(sr.ReadToEnd()); var client = new MongoClient(new MongoUrl(settings.Url)); _database = client.GetDatabase(settings.DatabaseName); } catch (FileNotFoundException) { throw new Exception("Talk to John about why this one fails"); } finally { f.Dispose(); sr.Dispose(); } _collectionName = Guid.NewGuid().ToString(); _collection = _database.GetCollection<Container>(_collectionName); var mapper = new StringMapper<BasePaymentModel>(x => x.PaymentType) .Register<AchInputModel>("ach") .Register<CreditCardInputModel>("cc") .Register<PayPalInputModel>("paypal"); BsonSerializer.RegisterDiscriminatorConvention( typeof(BasePaymentModel), new DiscriminatorConvention<string, BasePaymentModel>(mapper)); }