コード例 #1
0
        public void RegisterConventionPack_RegisterEqualConventionPacksTwoTimes_OneConventionPackRegistered()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterConventionPack(
                "duplicateTestConventionPack", new ConventionPack
            {
                new DuplicateTestConvention1(),
                new DuplicateTestConvention2()
            }, t => true);

            mongoDatabaseBuilder.RegisterConventionPack(
                "duplicateTestConventionPack", new ConventionPack
            {
                new DuplicateTestConvention2(),
                new DuplicateTestConvention1()
            }, t => true);

            // Act
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            IEnumerable <IConvention> conventions = ConventionRegistry
                                                    .Lookup(typeof(string)).Conventions;
            int duplicateTestConventionCount1 = conventions
                                                .Count(convention => convention.Name == nameof(DuplicateTestConvention1));
            int duplicateTestConventionCount2 = conventions
                                                .Count(convention => convention.Name == nameof(DuplicateTestConvention2));

            Assert.Equal(1, duplicateTestConventionCount1);
            Assert.Equal(1, duplicateTestConventionCount2);
        }
コード例 #2
0
        public void RegisterConventionPack_RegisterUnequalConventionPacksTwoTimes_ThrowsException()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterConventionPack(
                "unequalTestConventionPack", new ConventionPack
            {
                new DifferingTestConvention1(),
                new DifferingTestConvention2()
            }, t => true);

            mongoDatabaseBuilder.RegisterConventionPack(
                "unequalTestConventionPack", new ConventionPack
            {
                new DifferingTestConvention1(),
                new DifferingTestConvention2(),
                new DifferingTestConvention3()
            }, t => true);

            // Act
            Action differingRegistration = () => mongoDatabaseBuilder.Build();

            // Assert
            Assert.Throws <Exception>(differingRegistration);
        }
コード例 #3
0
        public void ConfigureCollection_SetDifferentSettingsToCollection_CollectionConfiguredSuccessfully()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            mongoDatabaseBuilder.ConfigureCollection(new FooCollectionConfiguration());
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            IMongoCollection <Foo> collection = result.GetCollection <Foo>();

            IEnumerable <BsonClassMap> classMaps = BsonClassMap.GetRegisteredClassMaps();

            Snapshot.Match(new
            {
                CollectionName = collection.CollectionNamespace.CollectionName,
                Settings       = collection.Settings,
                Indexes        = collection.Indexes.List().ToList(),
                ClassMaps      = classMaps.Select(map => new {
                    Name        = map.Discriminator,
                    IdMemberMap = new {
                        map.IdMemberMap?.ElementName,
                        map.IdMemberMap?.MemberName
                    },
                    AllMemberMaps = map.AllMemberMaps.Select(amm =>
                                                             new { amm.ElementName, amm.MemberName }),
                    IgnoreExtraElements = map.IgnoreExtraElements
                })
            });
        }
コード例 #4
0
        public void SetUpOnce()
        {
            var builder = new MongoDatabaseBuilder(new DatabaseSettings {
                DatabaseName = DatabaseName
            });
            var database = builder.Build();

            _collection = database.GetCollection <UserEntity>(MongoUserRepository.CollectionName);
            _repository = new MongoUserRepository(database);
        }
コード例 #5
0
        public void DisableTableScan_SetMongoServerTableScanToDisabled_MongoServerTableScanIsDisabled()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            mongoDatabaseBuilder.ConfigureDatabase(db => db.Client.DisableTableScan());
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            Assert.True(result.Client.IsTableScanDisabled());
        }
コード例 #6
0
        private static MongoDbContextData CreateContext(MongoResource mongoResource)
        {
            var mongoOptions = new MongoOptions
            {
                ConnectionString = mongoResource.ConnectionString,
                DatabaseName     = mongoResource.CreateDatabase().DatabaseNamespace.DatabaseName
            };
            var builder = new MongoDatabaseBuilder(mongoOptions);

            builder.RegisterImmutableConventionPack();
            return(builder.Build());
        }
コード例 #7
0
        public void RegisterSerializer_RegisterNull_ThrowsException()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterSerializer <NullTestType>(null);

            // Act
            Action registerSerializers = () => mongoDatabaseBuilder.Build();

            // Assert
            Assert.Throws <ArgumentNullException>(registerSerializers);
        }
コード例 #8
0
        public void AddInstrumentation_Command_ActivityCreated()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.AddInstrumentation();

            // Act
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            result.Client.Settings.ClusterConfigurator.Should().NotBeNull();
        }
コード例 #9
0
        public void ConfigureConnection_SetWrongConnectionSettings_ThrowsExceptionDuringBuild()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            mongoDatabaseBuilder.ConfigureConnection(
                settings => settings.HeartbeatInterval = TimeSpan.FromSeconds(-20));
            Action buildMongoDbContext = () => mongoDatabaseBuilder.Build();

            // Assert
            Assert.Throws <ArgumentOutOfRangeException>(buildMongoDbContext);
        }
コード例 #10
0
        public void RegisterConventionPack_NullConventionPackRegistered_ThrowsException()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterConventionPack("nullConventionPack", null, t => true);

            // Act
            Action registrationAction = () => mongoDatabaseBuilder.Build();

            // Assert
            Assert.Throws <ArgumentNullException>(registrationAction);
        }
コード例 #11
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(Policies.CorsPolicy, builder =>
                                  builder
                                  .WithOrigins(Urls.ReactDevServer)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  );
            });

            services.AddMemoryCache();

            services.Configure <DatabaseSettings>(Configuration.GetSection(nameof(DatabaseSettings)));
            services.AddSingleton(sp => sp.GetRequiredService <IOptions <DatabaseSettings> >().Value);
            services.AddSingleton(sp =>
            {
                var settings = sp.GetRequiredService <DatabaseSettings>();
                var builder  = new MongoDatabaseBuilder(settings);
                return(builder.Build());
            });
            services.AddSingleton <IDeckRepository, MongoDeckRepository>();
            services.AddSingleton <ICardRepository, MongoCardRepository>();
            services.AddSingleton <IUserRepository, MongoUserRepository>();

            services.AddSingleton <Random>();
            services.AddSingleton <CardMapper>();
            services.AddSingleton <DeckMapper>();
            services.AddSingleton <IDeckManager, DeckManager>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddMvc(o => o.EnableEndpointRouting = false);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "NSCards Api", Version = "v1"
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services
            .AddAuthentication(options => options.DefaultScheme = AuthenticationSchemes.Google)
            .AddScheme <GoogleAuthenticationSchemeOptions, GoogleAuthenticationHandler>(
                AuthenticationSchemes.Google, o => { });
        }
コード例 #12
0
        public void ConfigureConnection_NoConnectionSettingsSet_DefaultConnectionSettingsSet()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            Assert.Equal(ReadPreference.Primary, result.Client.Settings.ReadPreference);
            Assert.Equal(ReadConcern.Majority, result.Client.Settings.ReadConcern);
            Assert.Equal(WriteConcern.WMajority.With(journal: true),
                         result.Client.Settings.WriteConcern);
        }
コード例 #13
0
        public void RegisterSerializer_RegisterNoSpecificSerializer_DefaultSerializerRegistered()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            mongoDatabaseBuilder.Build();

            // Assert
            IBsonSerializer <NoSerializerRegistered> registeredSerializer =
                BsonSerializer.LookupSerializer <NoSerializerRegistered>();

            Assert.True(registeredSerializer is
                        BsonClassMapSerializer <NoSerializerRegistered>);
        }
コード例 #14
0
        public void RegisterSerializer_RegisterDifferentSerializerTwoTimesForSameType_ThrowsException()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);
            var originalSerializer   = new DuplicateRegisteredSerializer();
            var differentSerializer  = new DifferentRegisteredSerializer();

            mongoDatabaseBuilder.RegisterSerializer <DuplicateType>(originalSerializer);
            mongoDatabaseBuilder.RegisterSerializer <DuplicateType>(differentSerializer);

            // Act
            Action registerSerializers = () => mongoDatabaseBuilder.Build();

            // Assert
            Assert.Throws <BsonSerializationException>(registerSerializers);
        }
コード例 #15
0
        public void RegisterImmutableConventionPack_RegisteredSuccessfully()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterImmutableConventionPack();

            // Act
            mongoDatabaseBuilder.Build();

            // Assert
            IEnumerable <IConvention> conventions = ConventionRegistry.Lookup(typeof(string)).Conventions;

            Assert.NotNull(conventions.OfType <ImmutableConvention>().FirstOrDefault());
            Assert.NotNull(conventions.OfType <IgnoreExtraElementsConvention>().FirstOrDefault());
        }
コード例 #16
0
        public void RegisterConventionPack_ConventionPackNotRegistered_ConventionPacksNotRegistered()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            IEnumerable <IConvention> conventions = ConventionRegistry.Lookup(typeof(string)).Conventions;
            int enumRepConvention   = conventions.Count(convention => convention.Name == "EnumRepresentation");
            int camelCaseConvention = conventions.Count(convention => convention.Name == "CamelCaseElementName");

            Assert.Equal(0, enumRepConvention);
            Assert.Equal(0, camelCaseConvention);
        }
コード例 #17
0
        public void ConfigureConnection_SetSpecificConnectionSettings_MongoConnectionSettingsSetSuccessfully()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            // Act
            mongoDatabaseBuilder
            .ConfigureConnection(settings => settings.ApplicationName = "Test")
            .ConfigureConnection(settings => settings.ConnectionMode  = ConnectionMode.Direct)
            .ConfigureConnection(settings => settings.WriteConcern    = WriteConcern.W3);
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            Assert.Equal("Test", result.Client.Settings.ApplicationName);
            Assert.Equal(ConnectionMode.Direct, result.Client.Settings.ConnectionMode);
            Assert.Equal(WriteConcern.W3, result.Client.Settings.WriteConcern);
        }
コード例 #18
0
        public void RegisterSerializer_RegisterSpecificSerializer_RegisteredSuccessfully()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);
            var arrangedSerializer   = new SimpleStringRegisteredSerializer();

            mongoDatabaseBuilder.RegisterSerializer <SimpleString>(arrangedSerializer);

            // Act
            mongoDatabaseBuilder.Build();

            // Assert
            IBsonSerializer <SimpleString> registeredSerializer =
                BsonSerializer.LookupSerializer <SimpleString>();

            Assert.True(registeredSerializer is SimpleStringRegisteredSerializer);
        }
コード例 #19
0
        public void RegisterConventionPack_RegisterOneSpecificConventionPackWithoutName_ThrowsException()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterConventionPack(
                null, new ConventionPack
            {
                new EnumRepresentationConvention(BsonType.String),
                new CamelCaseElementNameConvention()
            }, t => true);

            // Act
            Action registrationAction = () => mongoDatabaseBuilder.Build();

            // Assert
            Assert.Throws <ArgumentNullException>(registrationAction);
        }
コード例 #20
0
        public void RegisterSerializer_RegisterSameSerializerTwoTimesForSameType_SerializerRegisteredOnce()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);
            var firstSerializer      = new DuplicateRegisteredSerializer();
            var secondSerializer     = new DuplicateRegisteredSerializer();

            mongoDatabaseBuilder.RegisterSerializer <DuplicateType>(firstSerializer);
            mongoDatabaseBuilder.RegisterSerializer <DuplicateType>(secondSerializer);

            // Act
            mongoDatabaseBuilder.Build();

            // Assert
            IBsonSerializer <DuplicateType> registeredSerializer =
                BsonSerializer.LookupSerializer <DuplicateType>();

            Assert.True(registeredSerializer is DuplicateRegisteredSerializer);
        }
コード例 #21
0
        public void RegisterConventionPack_RegisterOneSpecificConventionPack_RegisteredSuccessfully()
        {
            // Arrange
            var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions);

            mongoDatabaseBuilder.RegisterConventionPack(
                "camelCase", new ConventionPack
            {
                new EnumRepresentationConvention(BsonType.String),
                new CamelCaseElementNameConvention()
            }, t => true);

            // Act
            MongoDbContextData result = mongoDatabaseBuilder.Build();

            // Assert
            IEnumerable <IConvention> conventions = ConventionRegistry.Lookup(typeof(string)).Conventions;

            Assert.NotNull(conventions.OfType <EnumRepresentationConvention>().FirstOrDefault(c => c.Representation == BsonType.String));
            Assert.NotNull(conventions.OfType <CamelCaseElementNameConvention>().FirstOrDefault());
        }
コード例 #22
0
ファイル: Startup.cs プロジェクト: vaspahomov/web-project
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(Policies.CorsPolicy, builder =>
                                  builder
                                  .WithOrigins(Urls.Front, Urls.DevServer)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  );
            });

            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Backend", Version = "v1"
                });
            });

            services.AddSingleton <IPictureModificator, ImageSharpPictureModificator>();

            services.Configure <DatabaseSettings>(Configuration.GetSection(nameof(DatabaseSettings)));
            services.AddSingleton(sp => sp.GetRequiredService <IOptions <DatabaseSettings> >().Value);
            services.AddSingleton(sp =>
            {
                var settings = sp.GetRequiredService <DatabaseSettings>();
                var builder  = new MongoDatabaseBuilder(settings);
                return(builder.Build());
            });

            services.AddSingleton <IPictureRepository, MongoPictureRepository>();
            services.AddSingleton <IUserRepository, MongoUserRepository>();
            services.AddScoped <IUserService, UserService>();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }