示例#1
0
        public static IMongoDatabase GetDatabase(MongodbConfig mongodbConfig)
        {
            ValidateParams(mongodbConfig);

            string databaseKey = mongodbConfig.ConnectionString + mongodbConfig.DBName;

            MongoClient    mongoClient = null;
            IMongoDatabase database    = null;

            if (MongoClients.ContainsKey(mongodbConfig.ConnectionString))
            {
                if (Databases.ContainsKey(databaseKey))
                {
                    database = Databases[databaseKey];
                }
                else
                {
                    mongoClient = MongoClients[mongodbConfig.ConnectionString];

                    database = mongoClient.GetDatabase(mongodbConfig.DBName);
                    Databases.Add(databaseKey, database);
                }
            }
            else
            {
                mongoClient = new MongoClient(mongodbConfig.ConnectionString);
                MongoClients.Add(mongodbConfig.ConnectionString, mongoClient);

                database = mongoClient.GetDatabase(mongodbConfig.DBName);
                Databases.Add(databaseKey, database);
            }

            return(database);
        }
示例#2
0
        public async Task NullExpressionOnReplaceTest()
        {
            MongodbConfig  mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase database      = MongodbProvider.GetDatabase(mongodbConfig);
            IMongodbSaveRepository <Test> saveRepository = new MongodbSaveRepository <Test>(database);

            await Assert.ThrowsAsync <ArgumentNullException>(() => saveRepository.ReplaceAsync(null, new Test()));
        }
示例#3
0
        public async Task NullEntitiesOnInsertManyTest()
        {
            MongodbConfig  mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase database      = MongodbProvider.GetDatabase(mongodbConfig);
            IMongodbSaveRepository <Test> saveRepository = new MongodbSaveRepository <Test>(database);

            await Assert.ThrowsAsync <ArgumentNullException>(() => saveRepository.InsertManyAsync(null));
        }
示例#4
0
        public async Task NullExpressionOnDeleteTest()
        {
            MongodbConfig            mongodbConfig    = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase           database         = MongodbProvider.GetDatabase(mongodbConfig);
            IDeleteRepository <Test> deleteRepository = new MongodbDeleteRepository <Test>(database);

            await Assert.ThrowsAsync <ArgumentNullException>(() => deleteRepository.DeleteAllByConditionsAsync(null));
        }
示例#5
0
        public async Task NothingToDeleteTest()
        {
            MongodbConfig            mongodbConfig    = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase           database         = MongodbProvider.GetDatabase(mongodbConfig);
            IDeleteRepository <Test> deleteRepository = new MongodbDeleteRepository <Test>(database);

            await deleteRepository.DeleteAllByConditionsAsync(x => x.ObjectId == "non-existent-object");
        }
示例#6
0
        private static IMongoDatabase GetMongoDatabase(IConfiguration configuration)
        {
            string mongodbConfigKey = "Mongodb";

            MongodbConfig  mongodbConfig = configuration.GetSection(mongodbConfigKey).Get <MongodbConfig>();
            IMongoDatabase database      = MongodbProvider.GetDatabase(mongodbConfig);

            return(database);
        }
示例#7
0
        public async Task NoResultsOnGetTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            IEnumerable <Test> tests = await getRepository.GetAllByConditionsAsync(x => x.ObjectId == "unexistent-object");

            Assert.Empty(tests);
        }
示例#8
0
        public async Task NothingToReplaceTest()
        {
            MongodbConfig  mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase database      = MongodbProvider.GetDatabase(mongodbConfig);
            IMongodbSaveRepository <Test> saveRepository = new MongodbSaveRepository <Test>(database);

            await Assert.ThrowsAsync <ReplaceException>(() => saveRepository.ReplaceAsync(x => x.ObjectId == "non-existent-object", new Test()
            {
                StringField = "nothing-to-replace-test"
            }));
        }
示例#9
0
        /// <summary>
        /// 使用Mongodb
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IServiceCollection AddMongodb(
            this IServiceCollection services,
            Action <MongodbConfig> options = null)
        {
            MongodbConfig option = new MongodbConfig();

            options?.Invoke(option);
            ObjectMapper.MapperTo <MongodbConfig>(option, ConfigFileHelper.Get <MongodbConfig>());//优先级装饰器
            services.AddSingleton(option);
            services.AddSingleton <MongodbManager>();
            return(services);
        }
示例#10
0
        public async Task NullSortOnGetTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            Sort <Test, bool> sort = null;

            await Assert.ThrowsAsync <ArgumentNullException>(async() => await getRepository.GetAllByConditionsAsync(
                                                                 x => true,
                                                                 sort));
        }
示例#11
0
        public async Task NullExpressionOnGetTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            Sort <Test, string> sort = new Sort <Test, string>(
                x => x.StringField,
                SortType.Desc);

            await Assert.ThrowsAsync <ArgumentNullException>(async() => await getRepository.GetAllByConditionsAsync(null));
        }
示例#12
0
        public async Task InvalidPaginationTakeNumberTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            Sort <Test, string> sort = new Sort <Test, string>(
                x => x.StringField,
                SortType.Desc);

            await Assert.ThrowsAsync <ArgumentException>(async() => await getRepository.GetAllByConditionsAsync(
                                                             x => true,
                                                             sort,
                                                             new Pagination(0, -2)));
        }
示例#13
0
        public async Task StringAscSortAndPaginationTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            Sort <Test, string> sort = new Sort <Test, string>(
                x => x.StringField,
                SortType.Asc);

            IEnumerable <Test> sortedTests = await getRepository.GetAllByConditionsAsync(
                x => true,
                sort,
                new Pagination(0, 2));

            Assert.True(sortedTests != null && sortedTests.Count() == 2);
        }
示例#14
0
        private static void ValidateParams(MongodbConfig mongodbConfig)
        {
            if (mongodbConfig == null)
            {
                throw new ArgumentNullException("The config provided can't be null");
            }

            if (string.IsNullOrEmpty(mongodbConfig.ConnectionString))
            {
                throw new ArgumentNullException("The config provided can't be null");
            }

            if (string.IsNullOrEmpty(mongodbConfig.DBName))
            {
                throw new ArgumentNullException("The config provided can't be null");
            }
        }
        public async Task InsertManyVsInsertOne()
        {
            MongodbConfig          mongodbConfig  = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase         database       = MongodbProvider.GetDatabase(mongodbConfig);
            ISaveRepository <Test> saveRepository = new MongodbSaveRepository <Test>(database);
            Stopwatch stopwatch = new Stopwatch();

            IList <Test> tests = TestHelper.CreateRandomTests(100);

            // First insert in order establish the connection
            await saveRepository.InsertAsync(tests.ElementAt(0));

            // One-by-one insert
            stopwatch.Restart();
            foreach (Test test in tests)
            {
                await saveRepository.InsertAsync(test);
            }
            stopwatch.Stop();
            TimeSpan oneByOneTime = stopwatch.Elapsed;

            // Multi-thread insert
            stopwatch.Restart();
            IList <Task> tasks = new List <Task>();

            foreach (Test test in tests)
            {
                tasks.Add(saveRepository.InsertAsync(test));
            }
            await Task.WhenAll(tasks);

            stopwatch.Stop();
            TimeSpan multiThreadTime = stopwatch.Elapsed;

            // Insert many (bulk)
            stopwatch.Restart();
            await saveRepository.InsertManyAsync(tests);

            stopwatch.Stop();
            TimeSpan bulkTime = stopwatch.Elapsed;

            Assert.True(
                TimeSpan.Compare(oneByOneTime, multiThreadTime) == 1 &&
                TimeSpan.Compare(multiThreadTime, bulkTime) == 1);
        }
示例#16
0
        public async Task StringDescSortAndPaginationCancelledTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            Sort <Test, string> sort = new Sort <Test, string>(
                x => x.StringField,
                SortType.Desc);

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(0.1));

            await Assert.ThrowsAsync <OperationCanceledException>(async() => await getRepository.GetAllByConditionsAsync(
                                                                      x => true,
                                                                      sort,
                                                                      new Pagination(0, 2),
                                                                      cancellationTokenSource.Token));
        }
示例#17
0
        public static MongodbConfig GetMongodbConfig()
        {
            MongodbConfig mongodbConfig = new MongodbConfig();

            string mongoConnString = Environment.GetEnvironmentVariable("mongo_db_conn_string_test");
            string regex           = @"^.*/(?<dbname>.*)\?";

            Match match = Regex.Match(mongoConnString, regex);

            if (match.Success)
            {
                string dbname = match.Groups["dbname"].ToString();

                mongodbConfig.ConnectionString = mongoConnString;
                mongodbConfig.DBName           = dbname;
            }

            return(mongodbConfig);
        }
示例#18
0
        public async Task NumberAscSortAndPaginationTest()
        {
            MongodbConfig         mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase        database      = MongodbProvider.GetDatabase(mongodbConfig);
            IGetRepository <Test> getRepository = new MongodbGetRepository <Test>(database);

            Sort <Test, double> sort = new Sort <Test, double>(
                x => x.NumberField,
                SortType.Asc);

            IEnumerable <Test> tests = await getRepository.GetAllByConditionsAsync(
                x => true,
                sort,
                new Pagination(0, 2));

            Assert.True(tests != null && tests.Count() == 2);

            IEnumerable <Test> sortedTests = tests.OrderBy(x => x.NumberField);

            Assert.True(tests.SequenceEqual(sortedTests));
        }
示例#19
0
        public async Task MultipleEntityIntegralTest()
        {
            MongodbConfig  mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase database      = MongodbProvider.GetDatabase(mongodbConfig);
            IMongodbSaveRepository <Test> saveRepository   = new MongodbSaveRepository <Test>(database);
            IGetRepository <Test>         getRepository    = new MongodbGetRepository <Test>(database);
            IDeleteRepository <Test>      deleteRepository = new MongodbDeleteRepository <Test>(database);

            Test newTest1 = new Test()
            {
                BoolField      = true,
                NumberField    = 1,
                ObjectId       = Guid.NewGuid().ToString(),
                StringField    = "multiple-object-1",
                TimestampField = DateTime.UtcNow
            };

            Test newTest2 = new Test()
            {
                BoolField      = true,
                NumberField    = 2,
                ObjectId       = Guid.NewGuid().ToString(),
                StringField    = "multiple-object-2",
                TimestampField = DateTime.UtcNow.AddMinutes(1)
            };

            IList <Test> newTests = new List <Test>()
            {
                newTest1, newTest2
            };

            await saveRepository.InsertManyAsync(newTests);

            IEnumerable <Test> savedTests = await getRepository.GetAllByConditionsAsync(x =>
                                                                                        x.ObjectId == newTest1.ObjectId ||
                                                                                        x.ObjectId == newTest2.ObjectId);

            Assert.True(savedTests.Count() == 2);

            Test savedTest1 = savedTests.Single(x =>
                                                x.ObjectId == newTest1.ObjectId &&
                                                x.NumberField == newTest1.NumberField &&
                                                x.StringField == newTest1.StringField &&
                                                DateTimeHelper.AreEquals(x.TimestampField, newTest1.TimestampField) &&
                                                x.BoolField == newTest1.BoolField);

            Test savedTest2 = savedTests.Single(x =>
                                                x.ObjectId == newTest2.ObjectId &&
                                                x.NumberField == newTest2.NumberField &&
                                                x.StringField == newTest2.StringField &&
                                                DateTimeHelper.AreEquals(x.TimestampField, newTest2.TimestampField) &&
                                                x.BoolField == newTest2.BoolField);

            string modifiedStringField = "modified-multiple-objects";
            UpdateDefinition <Test> updateDefinition = Builders <Test> .Update.Set(x => x.StringField, modifiedStringField);

            await saveRepository.UpdateManyAsync(
                x =>
                x.ObjectId == newTest1.ObjectId ||
                x.ObjectId == newTest2.ObjectId,
                updateDefinition);

            IEnumerable <Test> modifiedTests = await getRepository.GetAllByConditionsAsync(x =>
                                                                                           x.StringField == modifiedStringField &&
                                                                                           (x.ObjectId == savedTest1.ObjectId || x.ObjectId == savedTest2.ObjectId));

            Assert.True(modifiedTests.Count() == 2);

            Test modifiedTest1 = modifiedTests.Single(x =>
                                                      x.ObjectId == newTest1.ObjectId &&
                                                      x.NumberField == newTest1.NumberField &&
                                                      x.StringField == modifiedStringField &&
                                                      DateTimeHelper.AreEquals(x.TimestampField, newTest1.TimestampField) &&
                                                      x.BoolField == newTest1.BoolField);

            Test modifiedTest2 = modifiedTests.Single(x =>
                                                      x.ObjectId == newTest2.ObjectId &&
                                                      x.NumberField == newTest2.NumberField &&
                                                      x.StringField == modifiedStringField &&
                                                      DateTimeHelper.AreEquals(x.TimestampField, newTest2.TimestampField) &&
                                                      x.BoolField == newTest2.BoolField);

            await deleteRepository.DeleteAllByConditionsAsync(x =>
                                                              x.StringField == modifiedStringField);

            IEnumerable <Test> deletedTests = await getRepository.GetAllByConditionsAsync(x => x.StringField == modifiedStringField);

            Assert.True(deletedTests == null || deletedTests.Count() == 0);
        }
示例#20
0
        public async Task SingleEntityIntegralTest()
        {
            MongodbConfig  mongodbConfig = MongoDbHelper.GetMongodbConfig();
            IMongoDatabase database      = MongodbProvider.GetDatabase(mongodbConfig);
            IMongodbSaveRepository <Test> saveRepository   = new MongodbSaveRepository <Test>(database);
            IGetRepository <Test>         getRepository    = new MongodbGetRepository <Test>(database);
            IDeleteRepository <Test>      deleteRepository = new MongodbDeleteRepository <Test>(database);

            Test newTest = new Test()
            {
                BoolField      = true,
                NumberField    = 1,
                ObjectId       = Guid.NewGuid().ToString(),
                StringField    = "new-single-object",
                TimestampField = DateTime.UtcNow
            };

            await saveRepository.InsertAsync(newTest);

            Test savedTest = await getRepository.GetFirstByConditionsAsync(x =>
                                                                           x.ObjectId == newTest.ObjectId &&
                                                                           x.BoolField == newTest.BoolField &&
                                                                           x.NumberField == newTest.NumberField &&
                                                                           x.StringField == newTest.StringField &&
                                                                           x.TimestampField == newTest.TimestampField);

            savedTest.BoolField      = false;
            savedTest.NumberField    = 2;
            savedTest.StringField    = "modified-single-object";
            savedTest.TimestampField = DateTime.UtcNow.AddDays(1);

            await saveRepository.ReplaceAsync(
                x =>
                x.ObjectId == newTest.ObjectId &&
                x.BoolField == newTest.BoolField &&
                x.NumberField == newTest.NumberField &&
                x.StringField == newTest.StringField &&
                x.TimestampField == newTest.TimestampField,
                savedTest);

            Test modifiedTest = (await getRepository.GetAllByConditionsAsync(x =>
                                                                             x.ObjectId == savedTest.ObjectId &&
                                                                             x.BoolField == savedTest.BoolField &&
                                                                             x.NumberField == savedTest.NumberField &&
                                                                             x.StringField == savedTest.StringField &&
                                                                             x.TimestampField == savedTest.TimestampField)).Single();

            await deleteRepository.DeleteAllByConditionsAsync(x =>
                                                              x.ObjectId == savedTest.ObjectId &&
                                                              x.BoolField == savedTest.BoolField &&
                                                              x.NumberField == savedTest.NumberField &&
                                                              x.StringField == savedTest.StringField &&
                                                              x.TimestampField == savedTest.TimestampField);

            Test deletedTest = await getRepository.GetFirstByConditionsAsync(x =>
                                                                             x.ObjectId == savedTest.ObjectId &&
                                                                             x.BoolField == savedTest.BoolField &&
                                                                             x.NumberField == savedTest.NumberField &&
                                                                             x.StringField == savedTest.StringField &&
                                                                             x.TimestampField == savedTest.TimestampField);

            Assert.Null(deletedTest);
        }