static void Main(string[] args) { DateTime startTime = DateTime.Now; string now = startTime.ToString("yyyy.MM.dd HH.mm"); Console.WriteLine("Started at " + now); MongoDB.Driver.IMongoClient client = new MongoClient(); // connect to localhost MongoDB.Driver.IMongoDatabase test = client.GetDatabase("prop2"); IMongoCollection <BsonDocument> collection = test.GetCollection <BsonDocument>("prop"); IMongoCollection <BsonDocument> collection1 = test.GetCollection <BsonDocument>("prop1"); Task tsk = insert(collection1, collection); //tsk.ConfigureAwait(true); tsk.Wait(); Task t = createIndex(collection); t.Wait(); // await collection.Indexes.CreateOneAsync(Builders<BsonDocument>.IndexKeys.Ascending(doc => doc["quad"])); // Task calculateNear = near(collection); // calculateNear.Wait(); DateTime endTime = DateTime.Now; TimeSpan elapsedTime = endTime - startTime; Console.WriteLine("elapsedTime = " + elapsedTime); Console.WriteLine("Press Enter to Continue..."); Console.ReadKey(false); }
public DataModelsController() { MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); _db = client.GetDatabase(ConfigurationManager.AppSettings["dbname"]); _models = _db.GetCollection <DataModel>("data_models"); _entityController = new EntityModelsController(); }
public IndexModule() { //The get and post methods for the main page. Get["/"] = parameters => { var collection1 = database.GetCollection <BsonDocument>("users"); var filter = Builders <BsonDocument> .Filter.Ne("emailaccounts", ""); var result = collection1.Find(filter).ToList(); var result2 = collection1.Distinct <BsonArray>("emailaccounts", filter); List <BsonDocument> l = new List <BsonDocument>(); var p = "<html>"; foreach (var x in result) { //Console.WriteLine(x); p = p + "<p>" + x.ToString() + "</p>"; l.Add(x); } p = p + "</html>"; Console.WriteLine(p + "!!!!"); return(p); }; Post["/"] = parameters => { var body = Request.Body.ToString(); Console.WriteLine(body); return(HttpStatusCode.OK); }; //Get["/hello/{name}"] = parameters => { return "Hello " + parameters.name; }; }
/// <summary> Creates a <see cref="BDoc"/> out of <paramref name="data"/>, and inserts a new record in the given <paramref name="database"/> and <paramref name="collection"/>. </summary> /// <param name="database"> Database to add data to </param> /// <param name="collection"> Collection to add data to </param> /// <param name="data"> Data to turn into a BDoc and insert </param> public void InsertData(string database, string collection, JsonObject data) { BDoc doc = ToBson(data); MDB db = dbClient.GetDatabase(database); db.GetCollection <BDoc>(collection).InsertOne(doc); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var collection = _database.GetCollection <dynamic>(logLevel.ToString().ToLower()); string message = formatter(state, exception); collection.InsertOneAsync(new { time = DateTime.Now, name = _name, message, exception }); }
public DbAppTenantResolver( ILoggerFactory loggerFactory ) : base(loggerFactory) { //this.tenants = options.Value.Tenants; var client = new MongoDB.Driver.MongoClient("mongodb://localhost"); // mongodb://admin:abc123!@localhost/database MongoDB.Driver.IMongoDatabase _database = client.GetDatabase("mydb"); var collection = _database.GetCollection <AppTenant>("tenants"); this.tenants = collection.Find(Builders <AppTenant> .Filter.Empty).ToList(); }
public CachingMongoDbAppTenantResolver( IMemoryCache cache, ILoggerFactory loggerFactory, IOptions <MultitenancyOptions> options) : base(cache, loggerFactory) { //this.tenants = options.Value.Tenants; var client = new MongoDB.Driver.MongoClient("mongodb://localhost"); // mongodb://admin:abc123!@localhost MongoDB.Driver.IMongoDatabase _database = client.GetDatabase("kiralikbul"); var collection = _database.GetCollection <AppTenant>("tenants"); this.tenants = collection.Find(Builders <AppTenant> .Filter.Empty).ToList(); }
static async Task MainAsync() { var client = new MongoClient("mongodb://192.168.8.5"); IMongoDatabase db = client.GetDatabase("schoool3"); var collection = db.GetCollection <Student>("students2"); var newStudents = CreateNewStudents(); await collection.InsertManyAsync(newStudents); var filter = "{ FirstName: 'Gregor'}"; await collection.Find(filter) .ForEachAsync(document => Console.WriteLine(document)); await collection.Find(student => student.Age < 25 && student.FirstName != "Peter") .ForEachAsync(student => Console.WriteLine(student.FirstName + " " + student.LastName)); }
/// <summary> Creates a <see cref="BDoc"/> out of every <see cref="JsonObject"/> in <paramref name="data"/>, and inserts each as a new record in the given <paramref name="database"/> and <paramref name="collection"/>. </summary> /// <param name="database"> Database to add data to </param> /// <param name="collection"> Collection to add data to </param> /// <param name="data"> Data to insert insert </param> public void InsertData(string database, string collection, JsonArray vals) { List <BDoc> docs = new List <BDoc>(vals.Count); foreach (var data in vals) { if (data is JsonObject) { docs.Add(ToBson(data as JsonObject)); // InsertData(database, collection, data as JsonObject); } } if (docs.Count > 0) { MDB db = dbClient.GetDatabase(database); db.GetCollection <BDoc>(collection).InsertMany(docs); } }
public void handle(RegistrationInfoFactory infoFactory, IrcDotNet.IrcClient client, FehBot bot, MongoDB.Driver.IMongoDatabase db, IrcDotNet.IrcUser from, IrcDotNet.IrcChannel to, string message) { var nickName = infoFactory.NickName; var messageCollection = db.GetCollection <BsonDocument> ("Message"); if (isTellMessage(message, nickName)) { Tuple <string, string> request = parseRequest(HandlerUtils.removeMention(message, nickName)); if (!request.Item1.Equals(nickName)) { messageCollection.InsertOne(new BsonDocument { { "network", infoFactory.Server }, { "channel", to.Name.ToLower() }, { "recipient", request.Item1 }, { "sender", from.NickName }, { "message", request.Item2 } }); client.LocalUser.SendMessage(to, from.NickName + ": kk"); var messageObject = new JObject(); messageObject.Add("channel", to.Name.ToLower()); messageObject.Add("recipient", request.Item1); messageObject.Add("sender", from.NickName); messageObject.Add("message", request.Item2); callWebHook(db, messageObject); } } else { var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("recipient", from.NickName) & builder.Eq("channel", to.Name.ToLower()) & builder.Eq("network", infoFactory.Server); messageCollection.Find(filter).ForEachAsync((document) => { var objectId = document.GetValue("_id").AsObjectId; var createdDate = objectId.CreationTime; DateDiff diff = new DateDiff(createdDate, DateTime.Now.ToUniversalTime()); client.LocalUser.SendMessage(to, String.Format("({0} ago) {1} => {2}, {3}", diff.GetDescription(6), document.GetValue("sender").AsString, document.GetValue("recipient").AsString, document.GetValue("message").AsString)); messageCollection.DeleteOne(document); }); } }
public async Task <IActionResult> GetServiceList() { ContractModel model = new ContractModel(); string strmodel = Newtonsoft.Json.JsonConvert.SerializeObject(model); var cols = monogodb.GetCollection <ServiceModel>("ContractInfo"); ServiceModel[] defaultModels = new ServiceModel[] { new ServiceModel() { ServiceCode = 100, ServiceName = "스케쥴링", Describe = "스케쥴링 알고리즘" }, new ServiceModel() { ServiceCode = 101, ServiceName = "Peak-cut", Describe = "피크컷 알고리즘" }, new ServiceModel() { ServiceCode = 102, ServiceName = "주파수 조정(Frequency Regulation)", Describe = "주파수 조정 알고리즘" }, new ServiceModel() { ServiceCode = 100, ServiceName = "DR", Describe = "수요반응" } }; await cols.InsertManyAsync(defaultModels); IAsyncCursor <ServiceModel> cursor = await cols.FindAsync <ServiceModel>(null); JArray jArray = new JArray(); //List<ServiceModel> result_models = new List<ServiceModel>(); await cursor.ForEachAsync(db => jArray.Add(db)); return(Ok(jArray)); }
public void run() { int dbToggle = 1; //prop2 if (dbToggle == 0) { MongoDB.Driver.IMongoClient client = new MongoClient(); // connect to localhost MongoDB.Driver.IMongoDatabase prop2 = client.GetDatabase("prop2"); IMongoCollection <BsonDocument> prop2Collection = prop2.GetCollection <BsonDocument>("prop2"); MongoDB.Driver.IMongoDatabase p = client.GetDatabase("p"); IMongoCollection <BsonDocument> pCollection = p.GetCollection <BsonDocument>("p"); Task tsk = insertDFW_geoJSON(prop2Collection, pCollection); tsk.Wait(); //Task t = createIndex(pCollection); //t.Wait(); } //test db if (dbToggle == 1) { MongoDB.Driver.IMongoClient client = new MongoClient(); // connect to localhost MongoDB.Driver.IMongoDatabase prop2 = client.GetDatabase("test"); IMongoCollection <BsonDocument> prop2Collection = prop2.GetCollection <BsonDocument>("prop1"); MongoDB.Driver.IMongoDatabase p = client.GetDatabase("p"); IMongoCollection <BsonDocument> pCollection = p.GetCollection <BsonDocument>("p"); Task tsk = insertDFW_geoJSON(prop2Collection, pCollection); tsk.Wait(); Task t = createIndex(pCollection); t.Wait(); } }
public void getAllData(string collectionName, string title1, string title2, string title3) { var Collections = database.GetCollection <Elas>(collectionName); List <Elas> list = null; int num = 0; if (title1 == "All categories") { list = Collections.Find(x => x.Subcategory == "").ToList(); foreach (var f in list) { points p = new points(); p.Category = f.Category; p.Elasticity = f.Elasticity; p.Quintile = f.Quintile; pl.Add(p); } } else if (title2 == "") { list = Collections.Find(x => x.Category == title1).ToList(); foreach (var f in list) { if ((f.Subcategory != "") && (f.Subsubcategory == "")) { num++; points p = new points(); p.Category = f.Subcategory; p.Elasticity = f.Elasticity; p.Quintile = f.Quintile; pl.Add(p); } } if (num == 0) { //if there is no subcategory. foreach (var f in list) { num++; points p = new points(); p.Category = f.Category; p.Elasticity = f.Elasticity; p.Quintile = f.Quintile; pl.Add(p); } } } else if (title3 == "") { list = Collections.Find(x => x.Category == title1 && x.Subcategory == title2).ToList(); foreach (var f in list) { if ((f.Subsubcategory != "") && (f.Subsubsubcategory == "")) { num++; points p = new points(); p.Category = f.Subsubcategory; p.Elasticity = f.Elasticity; p.Quintile = f.Quintile; pl.Add(p); } } if (num == 0) //if there is no subsubcategory. { foreach (var f in list) { num++; points p = new points(); p.Category = f.Subcategory; p.Elasticity = f.Elasticity; p.Quintile = f.Quintile; pl.Add(p); } } } else { list = Collections.Find(x => x.Category == title1 && x.Subcategory == title2 && x.Subsubcategory == title3).ToList(); foreach (var f in list) { points p = new points(); p.Category = f.Subsubcategory; p.Elasticity = f.Elasticity; p.Quintile = f.Quintile; pl.Add(p); } } }
/// <summary> Reseeds a database using the given descriptor. </summary> /// <param name="reseedInfo"> JsonObject containing description of how to reseed the database. </param> public void Reseed(JsonObject reseedInfo, string topDir = null) { if (reseedInfo.Has <JsonArray>("drop")) { Drop(reseedInfo.Get <JsonArray>("drop")); } if (reseedInfo.Has <JsonObject>("index")) { Index(reseedInfo.Get <JsonObject>("index")); } if (reseedInfo.Has <JsonObject>("insert")) { Insert(reseedInfo.Get <JsonObject>("insert"), topDir); } void Drop(JsonArray databases) { foreach (var dbname in databases) { if (dbname.isString) { dbClient.DropDatabase(dbname.stringVal); } } } void Index(JsonObject descriptor) { string database = descriptor.Pull("database", dbName); string collection = descriptor.Pull("collection", "Garbage"); if (database == "$default") { database = dbName; } JsonObject fields = descriptor.Pull <JsonObject>("fields"); MDB db = dbClient.GetDatabase(database); List <CreateIndexModel <BDoc> > indexes = new List <CreateIndexModel <BDoc> >(); IndexKeysDefinition <BDoc> index = null; foreach (var pair in fields) { string fieldName = pair.Key; int order = pair.Value; if (order > 0) { index = index?.Ascending(fieldName) ?? Builders <BDoc> .IndexKeys.Ascending(fieldName); } else { index = index?.Descending(fieldName) ?? Builders <BDoc> .IndexKeys.Descending(fieldName); } } var model = new CreateIndexModel <BDoc>(index); db.GetCollection <BDoc>(collection).Indexes.CreateOne(model); } void Insert(JsonObject descriptor, string dir) { string database = descriptor.Pull("database", dbName); string collection = descriptor.Pull("collection", "Garbage"); string[] files = descriptor.Pull <string[]>("files"); if (files == null) { files = new string[] { collection }; } dir = ForwardSlashPath(dir); if (!dir.EndsWith("/")) { dir += "/"; } foreach (var file in files) { string json = null; string fpath = dir + file; if (file.EndsWith("/**")) { string directory = fpath.Replace("/**", ""); Glob(database, collection, directory); } else { try { json = json ?? File.ReadAllText(fpath); } catch (Exception) { } try { json = json ?? File.ReadAllText(fpath + ".json"); } catch (Exception) { } try { json = json ?? File.ReadAllText(fpath + ".wtf"); } catch (Exception) { } if (json == null) { Log.Warning($"Seeder could not find file {{{ForwardSlashPath(file)}}} under {{{dir}}}"); continue; } JsonValue data = Json.Parse(json); if (data == null || !(data is JsonObject) && !(data is JsonArray)) { Log.Warning($"Seeder cannot use {{{ForwardSlashPath(file)}}} under {{{dir}}}, it is not an object or array."); continue; } if (data is JsonObject) { data["filename"] = UpToLast(FromLast(ForwardSlashPath(fpath), "/"), "."); InsertData(database, collection, data as JsonObject); } else if (data is JsonArray) { InsertData(database, collection, data as JsonArray); } } } } void Glob(string database, string collection, string directory) { List <string> files = AllFilesInDirectory(directory); foreach (string file in files) { string json = null; try { json = json ?? File.ReadAllText(file); } catch (Exception e) { Log.Warning($"Seeder could not find {{{file}}}.", e); } try { JsonValue data = Json.Parse(json); if (data == null || !(data is JsonObject) && !(data is JsonArray)) { Log.Warning($"Seeder cannot use {{{ForwardSlashPath(file)}}}, it is not an object or array."); continue; } if (data is JsonObject) { data["filename"] = UpToLast(FromLast(ForwardSlashPath(file), "/"), "."); InsertData(database, collection, data as JsonObject); } else if (data is JsonArray) { InsertData(database, collection, data as JsonArray); } } catch (Exception e) { Log.Warning($"Seeder could not parse {{{ForwardSlashPath(file)}}}.", e); } } } }
public void handle(RegistrationInfoFactory infoFactory, IrcDotNet.IrcClient client, FehBot bot, MongoDB.Driver.IMongoDatabase db, IrcDotNet.IrcUser from, IrcDotNet.IrcChannel to, string message) { if (isFactoidMentionRequest(message)) { Tuple <string, string> request = ParseFactionMention(message); var term = request.Item1.Trim(); var target = request.Item2.Trim(); var factoid = db.GetCollection <BsonDocument>("factoid"); var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("term", term) & builder.Eq("channel", to.Name.ToLower()) & builder.Eq("network", infoFactory.Server); var document = factoid.Find(filter).FirstOrDefault(); if (document == null) { string template = "{0}, Huh?"; client.LocalUser.SendMessage(to, String.Format(template, from.NickName)); } else { string template = "{0}, {1}."; client.LocalUser.SendMessage(to, String.Format(template, target, document.GetValue("meaning").AsString)); } } else if (isFactoidGetRequest(message)) { var term = parseFactoidGet(message); var factoid = db.GetCollection <BsonDocument>("factoid"); var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("term", term) & builder.Eq("channel", to.Name.ToLower()) & builder.Eq("network", infoFactory.Server); var document = factoid.Find(filter).FirstOrDefault(); if (document == null) { string template = "{0}, Huh?"; client.LocalUser.SendMessage(to, String.Format(template, from.NickName)); } else { string template = "{0}, {1}"; client.LocalUser.SendMessage(to, String.Format(template, from.NickName, document.GetValue("meaning").AsString)); } } else if (isFactoidStoreRequest(message, infoFactory.NickName)) { message = HandlerUtils.removeMention(message, infoFactory.NickName); var request = parseFactoidStoreRequest(message); var term = request.Item1; var definition = request.Item2; var factoid = db.GetCollection <BsonDocument>("factoid"); var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("term", term) & builder.Eq("channel", to.Name.ToLower()) & builder.Eq("network", infoFactory.Server); var document = factoid.Find(filter).FirstOrDefault(); if (document == null) { factoid.InsertOne(new BsonDocument { { "term", term }, { "channel", to.Name.ToLower() }, { "network", infoFactory.Server }, { "meaning", definition } }); } else { var update = Builders <BsonDocument> .Update.Set("meaning", definition); factoid.UpdateOne(filter, update); } string template = "{0}, Got it!"; client.LocalUser.SendMessage(to, String.Format(template, from.NickName)); } else if (isFactoidRemoveRequest(message, infoFactory.NickName)) { message = HandlerUtils.removeMention(message, infoFactory.NickName); string term = parseFactoidRemoveRequest(message); var factoid = db.GetCollection <BsonDocument>("factoid"); var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("term", term) & builder.Eq("channel", to.Name.ToLower()) & builder.Eq("network", infoFactory.Server); var document = factoid.Find(filter).FirstOrDefault(); if (document == null) { string template = "{0}, Huh?"; client.LocalUser.SendMessage(to, String.Format(template, from.NickName)); } else { factoid.DeleteOne(filter); string template = "{0}, It never happened."; client.LocalUser.SendMessage(to, String.Format(template, from.NickName)); } } }
public EntityModelsController() { MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient(); _db = client.GetDatabase(ConfigurationManager.AppSettings["dbname"]); _models = _db.GetCollection <EntityDefinition>("entity_definitions"); }
public IMongoCollection <T> Document <T>() where T : DbModel { var doc = db.GetCollection <T>(typeof(T).Name); return(doc); }