示例#1
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="settings"></param>
        public MongoDatabase(IDatabaseSettings settings)
        {
            string connectionString = ConnectionStringHelper.GenerateConnectionString(settings);
            var    client           = new MongoClient(connectionString);

            this.Database = client.GetDatabase(settings.DefaultAuthDatabase);
        }
 public MongoContext()
 {
     _client   = new MongoClient("mongodb://*****:*****@ds127293.mlab.com:27293/shop");
     _server   = _client.GetServer();
     _database = _client.GetDatabase("shop");
     database  = _server.GetDatabase("shop");
 }
示例#3
0
        public MongoDatabase(IOptions <DataConfig> otpions)
        {
            var dataConfig = otpions.Value;
            var client     = new MongoClient(dataConfig.ConnectionString);

            _database = client.GetDatabase(dataConfig.DatabaseName);
        }
        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();
 }
示例#6
0
        public MongoConnDatabase(MongoConnectionConfiguration config)
        {
            var url         = new MongoUrlBuilder(config.ConnectionString).ToMongoUrl();
            var mongoClient = new MongoClient(url);

            Database = mongoClient.GetDatabase(config.DatabaseName);
        }
        // GET: Home
        public HomeController()
        {
            //var client = new MongoClient(ConfigurationManager.AppSettings["connectionString"]);
            var client = new MongoClient("mongodb://localhost:27017");

            database = client.GetDatabase("expenditure");
            //var Collections = db.GetCollection<food>("expenditure");
        }
示例#8
0
        /// <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 FileDescriptorAsset(NeoAssets.Mongo.NeoVirtFS myFile,
                                   MongoDB.Driver.IMongoDatabase db,
                                   MongoDB.Driver.IMongoCollection <NeoBakedVolumes.Mongo.BakedAssets> bac,
                                   MongoDB.Driver.IMongoCollection <NeoBakedVolumes.Mongo.BakedVolumes> bVol) : base(myFile)
        {
            // Just load this stuff - we become active if we get an open call

            asset = null;

            this.db   = db;
            this.bac  = bac;
            this.bVol = bVol;
            this.file = myFile;
        }
        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();
        }
        private MongoDB.Driver.IMongoDatabase GetMongoDatabase()
        {
            if (database == null)
            {
                var client = CreateMongoClient();
                if (!DatabaseExists(client, databaseName) && !autoCreateDb)
                {
                    throw new KeyNotFoundException("此MongoDB名称不存在:" + databaseName);
                }

                database = CreateMongoClient().GetDatabase(databaseName);
            }

            return(database);
        }
        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();
        }
示例#13
0
        /// <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);
            }
        }
示例#14
0
        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));
        }
        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();
            }
        }
示例#16
0
 public EntityModelsController()
 {
     MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient();
     _db     = client.GetDatabase(ConfigurationManager.AppSettings["dbname"]);
     _models = _db.GetCollection <EntityDefinition>("entity_definitions");
 }
示例#17
0
        /// <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 MongoDbStoreStrategy(string databasename, MongoDatabaseSettings settings)
 {
     MongoDB.Driver.MongoClient client = new MongoDB.Driver.MongoClient();
     database = client.GetDatabase(databasename, settings);
 }
示例#19
0
        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));
                }
            }
        }
示例#20
0
        public MongoContext()
        {
            var client = new MongoClient("mongodb://localhost");

            Db = client.GetDatabase("test");
        }
示例#21
0
 protected EntityCrudRepository(IMongoDatabase database) : base(database)
 {
 }
示例#22
0
        public void handle(RegistrationInfoFactory infoFactory, IrcDotNet.IrcClient client, FehBot bot, MongoDB.Driver.IMongoDatabase db, IrcDotNet.IrcUser from, IrcDotNet.IrcChannel to, string message)
        {
            if (to == null && isCode(message))
            {
                string code     = parseCodeRequest(message);
                string nick     = from.NickName;
                var    document = getForCode(nick.Trim(), code.Trim(), db);
                if (document != null)
                {
                    addListener(document, db);
                    var link = new JObject();

                    link.Add("nick", document.Nick);
                    link.Add("remoteUserName", document.RemoteUserName);

                    callWebHook(db, link);
                }
            }
        }
示例#23
0
 public CategoryRepository(IMongoDatabase database)
 {
     _database = database;
 }
示例#24
0
 public MongoInitializer(IMongoDatabase database, IOptions <MongoOptions> options, IDatabaseSeeder seeder)
 {
     _database = database;
     _seed     = options.Value.Seed;
     _seeder   = seeder;
 }
 public TvPlayerRepository()
     : base()
 {
     var client = new MongoClient(ConnectionString);
     database = client.GetDatabase(DataBaseName);
 }
示例#26
0
        public RepositoryMongo(IConfiguration configuration)
        {
            var client = new MongoDB.Driver.MongoClient(configuration.GetConnectionString("defaultConnection"));

            this.dataBase = client.GetDatabase(configuration.GetConnectionString("dataBaseName"));
        }
 public ActivityRepository(IMongoDatabase database)
 {
     _database = database;
 }
示例#28
0
 public MongodbLogger(string name, MongoDB.Driver.IMongoDatabase database)
 {
     _name     = name;
     _database = database;
 }
示例#29
0
 public void Dispose()
 {
     db     = null;
     client = null;
 }
示例#30
0
 public MDB()
 {
     client = new MongoClient("mongodb://10.0.0.20/MBM");
     db     = client.GetDatabase("MBM");
 }
示例#31
0
        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);
                });
            }
        }