Exemplo n.º 1
0
        public static MongoOptions Validate(
            this MongoOptions mongoOptions)
        {
            if (mongoOptions == null)
            {
                throw new Exception(
                          $"The MongoDB options for could not be found " +
                          $"within the configuration section or the options are null.");
            }

            if (string.IsNullOrEmpty(mongoOptions.ConnectionString))
            {
                throw new Exception(
                          $"The connection string of the MongoDB configuration " +
                          $"could not be found within the configuration section. " +
                          $"Please verify that this section contains the " +
                          $"{nameof(MongoOptions.ConnectionString)} field.");
            }

            if (string.IsNullOrEmpty(mongoOptions.DatabaseName))
            {
                throw new Exception(
                          $"The database name of the MongoDB configuration " +
                          $"could not be found within the section " +
                          $"Please verify that this section contains the " +
                          $"{nameof(MongoOptions.DatabaseName)} field.");
            }

            return(mongoOptions);
        }
Exemplo n.º 2
0
        private static MongoOptions GetMongoDbOptions(IConfiguration configuration)
        {
            string sectionName = Wellknown.ConfigSections.Identity;

            MongoOptions options = configuration
                                   .GetSection($"{sectionName}:Database")
                                   .Get <MongoOptions>();

            if (options == null)
            {
                throw new IdentityConfigurationException(
                          $@"Could not load configuration for Database, make sure that the
                      section: '{sectionName}:Database' is defined");
            }

            if (options.ConnectionString == null)
            {
                throw new IdentityConfigurationException(
                          $@"Database ConnectionString can not be null, make sure
                      key: '{sectionName}:Database:ConnectionString' is defined");
            }

            if (options.DatabaseName == null)
            {
                throw new IdentityConfigurationException(
                          $@"DatabaseName can not be null, make sure
                      key: '{sectionName}:Database:DatabaseName' is defined");
            }

            return(options);
        }
Exemplo n.º 3
0
        public PhotoManagerContext(MongoOptions mongoOptions)
        {
            var connection = new MongoUrlBuilder(mongoOptions.ConnectionString);
            var client     = new MongoClient(mongoOptions.ConnectionString);

            _database = client.GetDatabase(connection.DatabaseName);
        }
        public MongoDbContext(MongoOptions mongoOptions, bool enableAutoInitialize)
        {
            MongoOptions = mongoOptions.Validate();

            if (enableAutoInitialize)
            {
                Initialize();
            }
        }
Exemplo n.º 5
0
 public MongoDatabaseBuilder(MongoOptions mongoOptions)
 {
     _mongoOptions = mongoOptions;
     _registrationConventionActions = new List <Action>();
     _registrationSerializerActions = new List <Action>();
     _mongoClientSettingsActions    = new List <Action <MongoClientSettings> >();
     _databaseConfigurationActions  = new List <Action <IMongoDatabase> >();
     _collectionActions             = new List <Action <IMongoDatabase, IMongoCollections> >();
 }
 public MongoDbContextDataTests(MongoResource mongoResource)
 {
     _mongoDatabase = mongoResource.CreateDatabase();
     _mongoOptions  = new MongoOptions
     {
         ConnectionString = mongoResource.ConnectionString,
         DatabaseName     = _mongoDatabase.DatabaseNamespace.DatabaseName
     };
 }
Exemplo n.º 7
0
 public MongoDatabaseBuilder(MongoOptions mongoOptions)
 {
     _mongoOptions = mongoOptions;
     _registrationConventionActions = new List <Action>();
     _registrationSerializerActions = new List <Action>();
     _mongoClientSettingsActions    = new List <Action <MongoClientSettings> >();
     _databaseConfigurationActions  = new List <Action <IMongoDatabase> >();
     _builderActions = new List <Action <IMongoDatabase, Dictionary <Type, object> > >();
 }
Exemplo n.º 8
0
        /// <summary>
        /// Use the KickStart extension to configure MongoDB.
        /// </summary>
        /// <param name="configurationBuilder">The configuration builder.</param>
        /// <returns>
        /// A fluent <see langword="interface"/> to configure KickStart.
        /// </returns>
        public static IConfigurationBuilder UseMongoDB(this IConfigurationBuilder configurationBuilder)
        {
            var options = new MongoOptions();
            var starter = new MongoStarter(options);
            var builder = new MongoBuilder(options);

            configurationBuilder.ExcludeName("MongoDB");
            configurationBuilder.Use(starter);

            return(configurationBuilder);
        }
Exemplo n.º 9
0
 public UnitOfWorkEventHandlerDecorator(IEventHandler <T> handler, IMongoSessionFactory sessionFactory,
                                        IExceptionToMessageMapperResolver exceptionToMessageMapperResolver, IMessageBroker messageBroker,
                                        MongoOptions options, ILogger <UnitOfWorkEventHandlerDecorator <T> > logger)
 {
     _handler        = handler;
     _sessionFactory = sessionFactory;
     _exceptionToMessageMapperResolver = exceptionToMessageMapperResolver;
     _messageBroker = messageBroker;
     _options       = options;
     _logger        = logger;
 }
Exemplo n.º 10
0
        public static MongoOptions <TMongoDBContext> GetMongoOptions <TMongoDBContext>(
            this IConfiguration configuration, string mongoDbPath) where TMongoDBContext : IMongoDbContext
        {
            MongoOptions <TMongoDBContext> mongoOptions = configuration
                                                          .GetSection(mongoDbPath)
                                                          .Get <MongoOptions <TMongoDBContext> >();

            mongoOptions.Validate();

            return(mongoOptions);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Use the KickStart extension to configure MongoDB.
        /// </summary>
        /// <param name="configurationBuilder">The configuration builder.</param>
        /// <returns>
        /// A fluent <see langword="interface"/> to configure KickStart.
        /// </returns>
        public static IConfigurationBuilder UseMongoDB(this IConfigurationBuilder configurationBuilder)
        {
            var options = new MongoOptions();
            var starter = new MongoStarter(options);
            var builder = new MongoBuilder(options);

            configurationBuilder.ExcludeName("MongoDB");
            configurationBuilder.Use(starter);

            return configurationBuilder;
        }
        public void Constructor_MongoOptions_CanAccessWhenNotInitialize()
        {
            // Arrange
            var testMongoDbContext = new TestMongoDbContext(_mongoOptions, false);

            // Act
            MongoOptions mongoOptions = testMongoDbContext.MongoOptions;

            // Assert
            Assert.NotNull(mongoOptions);
        }
        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());
        }
Exemplo n.º 14
0
        /// <summary>
        /// Use the KickStart extension to configure MongoDB.
        /// </summary>
        /// <param name="configurationBuilder">The configuration builder.</param>
        /// <returns>
        /// A fluent <see langword="interface"/> to configure KickStart.
        /// </returns>
        public static IConfigurationBuilder UseMongoDB(this IConfigurationBuilder configurationBuilder)
        {
            var options = new MongoOptions();
            var starter = new MongoStarter(options);
            var builder = new MongoBuilder(options);

            configurationBuilder.ExcludeAssemblyFor <MongoStarter>();
            configurationBuilder.ExcludeAssemblyFor <global::MongoDB.Driver.IMongoDatabase>();
            configurationBuilder.Use(starter);

            return(configurationBuilder);
        }
Exemplo n.º 15
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity <AuctorUser, AuctorRole>(opts => { opts.Password.RequireNonAlphanumeric = false; })
            .AddJRepoStores()
            .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);

            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            var mongoOptions = new MongoOptions("mongodb://*****:*****@localhost:27017", "AuctorAuth");

            services.AddJRepoMongoDb(mongoOptions);

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddJRepoStores()

                          /*.AddInMemoryIdentityResources(Config.GetIdentityResources())
                           * .AddInMemoryApiResources(Config.GetApis())
                           * .AddInMemoryClients(Config.GetClients())*/
                          .AddAspNetIdentity <AuctorUser>();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }

            services.AddAuthentication()

            /*.AddGoogle(options =>
             * {
             *  // register your IdentityServer with Google at https://console.developers.google.com
             *  // enable the Google+ API
             *  // set the redirect URI to http://localhost:5000/signin-google
             *  options.ClientId = "copy client ID from Google here";
             *  options.ClientSecret = "copy client secret from Google here";
             * })*/;
        }
Exemplo n.º 16
0
        private void ReloadOptions(MongoOptions options)
        {
            Options = options;

            var url      = new MongoUrl(Options.EventConnection);
            var client   = new MongoClient(url);
            var database = client.GetDatabase(options.EventDbName);

            _collection = database.GetCollection <SubscribeEvent>(options.SubscribeEventName, new MongoCollectionSettings()
            {
                AssignIdOnInsert = false
            });
        }
Exemplo n.º 17
0
    public VariableValueStoreTests(MongoResource mongoResource)
    {
        _mongoDatabase = mongoResource.CreateDatabase();
        _mongoDatabase.Client.DisableTableScan();

        var mongoOptions = new MongoOptions
        {
            ConnectionString = mongoResource.ConnectionString,
            DatabaseName     = _mongoDatabase.DatabaseNamespace.DatabaseName
        };

        _docuStoreDbContext = new ConfixAuthorDbContext(mongoOptions);
    }
Exemplo n.º 18
0
        protected BaseRepository(ILogger <TModel> logger,
                                 ICacheService cacheService,
                                 IOptions <MongoOptions> options,
                                 IValidator <TModel> validator = null
                                 )
        {
            _validator   = validator ?? new InlineValidator <TModel>();
            CacheService = cacheService;
            Logger       = logger;
            _options     = options.Value;

            InitClient();
        }
Exemplo n.º 19
0
        public static IServiceCollection AddBlogDatabase(
            this IServiceCollection services, IConfiguration configuration)
        {
            MongoOptions blogDbOptions = configuration
                                         .GetMongoOptions(WellKnown.Path.SimpleBlogDB);

            services.AddSingleton(blogDbOptions);
            services.AddSingleton <ISimpleBlogDbContext, SimpleBlogDbContext>();
            services.AddSingleton <IBlogRepository, BlogRepository>();
            services.AddSingleton <IUserRepository, UserRepository>();
            services.AddSingleton <ITagRepository, TagRepository>();

            return(services);
        }
Exemplo n.º 20
0
        public static IServiceCollection AddMongoDbExtensions(this IServiceCollection services, Action <MongoOptions> setupDatabaseAction)
        {
            var dbOptions = new MongoOptions();

            setupDatabaseAction(dbOptions);

            var storedEventCollection  = MongoUtil.FromConnectionString <StoredEvent>(dbOptions.ConnectionString, dbOptions.StoredEventCollection);
            var refreshTokenCollection = MongoUtil.FromConnectionString <RefreshToken>(dbOptions.ConnectionString, dbOptions.RefreshTokenCollection);

            services.AddSingleton(x => storedEventCollection);
            services.AddSingleton(x => refreshTokenCollection);

            return(services);
        }
Exemplo n.º 21
0
        private void ConfigureMongoDb(ContainerBuilder builder)
        {
            var optionsSection = Configuration.GetSection("mongo");
            var options        = new MongoOptions();

            optionsSection.Bind(options);
            builder.RegisterInstance(options).SingleInstance();

            var mongoClient = new MongoClient(options.ConnectionString);

            builder.RegisterInstance(mongoClient.GetDatabase(options.Database));
            builder.RegisterType <MongoEntryRepository>()
            .As <IEntryRepository>()
            .InstancePerLifetimeScope();
        }
Exemplo n.º 22
0
        public MongoDbContext(MongoOptions mongoOptions, bool enableAutoInitialize)
        {
            if (mongoOptions == null)
            {
                throw new ArgumentNullException(nameof(mongoOptions));
            }

            mongoOptions.Validate();

            MongoOptions = mongoOptions;

            // This initialization should be removed and switched to Lazy initialization.
            if (enableAutoInitialize)
            {
                Initialize(mongoOptions);
            }
        }
Exemplo n.º 23
0
        protected void Initialize(MongoOptions mongoOptions)
        {
            if (_mongoDbContextData == null)
            {
                lock (_lockObject)
                {
                    if (_mongoDbContextData == null)
                    {
                        var mongoDatabaseBuilder = new MongoDatabaseBuilder(MongoOptions);

                        OnConfiguring(mongoDatabaseBuilder);

                        _mongoDbContextData = mongoDatabaseBuilder.Build();
                    }
                }
            }
        }
Exemplo n.º 24
0
        private void ReloadOptions(MongoOptions options)
        {
            Options = options;

            var url      = new MongoUrl(Options.SnapshootConnection);
            var client   = new MongoClient(url);
            var database = client.GetDatabase(options.SnapshootDbName);

            MongoDatabase = database;

            foreach (var item in _cache.Values)
            {
                if (item is IConfigureChange source)
                {
                    source.Reload();
                }
            }
        }
    public static IServiceCollection AddMongoStore(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        MongoOptions options = configuration.GetSection("Confix:Storage:Database")
                               .Get <MongoOptions>();

        services.AddSingleton <IConfixAuthorDbContext>(new ConfixAuthorDbContext(options));
        services.AddSingleton <IApplicationStore, ApplicationStore>();
        services.AddSingleton <IChangeLogStore, ChangeLogStore>();
        services.AddSingleton <IEnvironmentStore, EnvironmentStore>();
        services.AddSingleton <IComponentStore, ComponentStore>();
        services.AddSingleton <IVariableStore, VariableStore>();
        services.AddSingleton <IVariableValueStore, VariableValueStore>();
        services.AddSingleton <IPublishingStore, PublishingStore>();

        return(services);
    }
Exemplo n.º 26
0
        public static IServiceCollection AddDataAccess(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            MongoOptions dbOptions = GetMongoDbOptions(configuration);

            services.AddSingleton(dbOptions);
            services.AddSingleton <IIdentityDbContext>(new IdentityDbContext(dbOptions));
            services.AddSingleton <IClientRepository, ClientRepository>();
            services.AddSingleton <IPersistedGrantRepository, PersistedGrantRepository>();
            services.AddSingleton <IApiScopeRepository, ApiScopeRepository>();
            services.AddSingleton <IApiResourceRepository, ApiResourceRepository>();
            services.AddSingleton <IIdentityResourceRepository, IdentityResourceRepository>();
            services.AddSingleton <IUserRepository, UserRepository>();

            services.AddSingleton <DataSeeder>();

            return(services);
        }
        public static void InitializeDatabase(TestContext context)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("test-settings.json")
                                .AddJsonFile("test-settings.user.json", optional: true)
                                .Build();

            _mongoOptions = configuration.GetSection(MongoOptions.Mongo).Get <MongoOptions>();

            _mongoCollectionPrefix = $"test-run-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-fff}-";
            context.WriteLine($"Configured Mongo to write to collection with prefix {_mongoCollectionPrefix}");

            _collectionNameMapper = new TestSuffixedCollectionNameMapperWrapper(
                new TypeCollectionNameMapper(),
                _mongoCollectionPrefix
                );

            CreateDatabaseContext().GetDatabase(); // create database
        }
Exemplo n.º 28
0
        public static IServiceCollection AddInfrastructure(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddMediatR(Assembly.GetExecutingAssembly());
            serviceCollection.AddTransient <IEventProcessor, EventProcessor>();

            serviceCollection.AddTransient <IMongoClientProvider, MongoClientProvider>();
            serviceCollection.AddTransient <IMongoDatabaseProvider, MongoDatabaseProvider>();
            serviceCollection.AddTransient <IMongoCollectionProvider, MongoCollectionProvider>();

            serviceCollection.AddSingleton <IExampleRepository, MongoExampleRepository>();

            ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

            IConfiguration configuration = serviceProvider.GetService <IConfiguration>();

            MongoOptions mongoOptions = configuration.GetSection("Mongo").Get <MongoOptions>();

            serviceCollection.AddSingleton(mongoOptions);

            return(serviceCollection);
        }
Exemplo n.º 29
0
        private void ReloadOptions(MongoOptions options)
        {
            Options = options;

            var url = new MongoUrl(Options.EventConnection);

            var client   = new MongoClient(url);
            var database = client.GetDatabase(options.EventDbName);


            _collection = database.GetCollection <IEvent>(options.EventName, new MongoCollectionSettings()
            {
                AssignIdOnInsert = false
            });

            var indk      = Builders <IEvent> .IndexKeys;
            var aggrIndex = indk.Combine(
                indk.Ascending(nameof(IEvent.AggregateRootId)),
                indk.Ascending(nameof(IEvent.AggregateRootTypeName)),
                indk.Ascending(nameof(IEvent.Version))
                );


            var timestampIndex = indk.Ascending(nameof(IEvent.UTCTimestamp));


            //Unique = true 这里如果加唯一索引,可能在批量写入事件时出现错误
            var aggrIndexModel = new CreateIndexModel <IEvent>(aggrIndex, new CreateIndexOptions()
            {
                Name = "aggr_index"
            });
            var timestampIndexModel = new CreateIndexModel <IEvent>(timestampIndex, new CreateIndexOptions()
            {
                Name = "timestamp_index"
            });

            _collection.Indexes.CreateOne(timestampIndexModel);
            _collection.Indexes.CreateOne(aggrIndexModel);
        }
Exemplo n.º 30
0
        public static void AddMongo(this IServiceCollection services)
        {
            var configuration = services.BuildServiceProvider().GetRequiredService <IConfiguration>();

            var mongoOptions = new MongoOptions();

            configuration.GetSection(MongoOptions.SectionName).Bind(mongoOptions);

            var mongoClient = new MongoClient(mongoOptions.ConnectionString);

            services.AddSingleton(mongoOptions);
            services.AddSingleton(mongoClient);

            services.AddTransient <IMongoDatabase>(s =>
            {
                var _mongoClient  = s.GetRequiredService <MongoClient>();
                var _mongoOptions = s.GetRequiredService <MongoOptions>();
                return(_mongoClient.GetDatabase(_mongoOptions.DataBase));
            });

            services.AddTransient <IMongoDbInitializer, MongoDbInitializer>();
            services.AddTransient <IMongoDbSeeder, MongoDbSeeder>();
        }
        public static IServiceCollection AddMongoDbStore(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            MongoOptions options = configuration.GetSection("MagicMedia:Database")
                                   .Get <MongoOptions>();

            services.AddSingleton(new MediaStoreContext(options));
            services.AddSingleton <IThumbnailBlobStore>((c) =>
            {
                MediaStoreContext mongoCtx = c.GetService <MediaStoreContext>();
                return(new GridFsThumbnailStore(mongoCtx.CreateGridFsBucket()));
            });

            services.AddSingleton <IMediaStore, MongoMediaStore>();
            services.AddSingleton <IFaceStore, FaceStore>();
            services.AddSingleton <ICameraStore, CameraStore>();
            services.AddSingleton <IPersonStore, PersonStore>();
            services.AddSingleton <IGroupStore, GroupStore>();
            services.AddSingleton <IAlbumStore, AlbumStore>();

            return(services);
        }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoStarter"/> class.
 /// </summary>
 /// <param name="options">The options to use.</param>
 public MongoStarter(MongoOptions options)
 {
     _options = options;
 }
Exemplo n.º 33
0
 public MongoBuilder(MongoOptions options)
 {
     _options = options;
 }