public ShowsService(IMongoDbClientFactory clientFactory, IOptions <MongoDbOptions> mongoDbOptions, ILogger <ShowsService> logger) { _client = clientFactory.GetMongoDbClient(); _mongoDbOptions = mongoDbOptions.Value; _logger = logger; }
public PictureService(MongoDbOptions settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _pics = database.GetCollection <Picture>(settings.Collection); }
public static IServiceCollection AddScimStoreMongoDB( this IServiceCollection services, Action <MongoDbOptions> mongoDbSetup, List <SCIMSchema> initialSchemas = null, List <SCIMAttributeMapping> initialAttributeMapping = null) { if (mongoDbSetup != null) { services.Configure(mongoDbSetup); var options = new MongoDbOptions(); mongoDbSetup(options); services.AddSingleton <IMongoClient>(_ => new MongoClient(options.ConnectionString)); services.AddSingleton(provider => provider.GetService <IMongoClient>().GetDatabase(options.Database)); services.AddSingleton <SCIMDbContext>(); MongoDbClientExtensions.EnsureMongoDbSCIMDatabaseIsCreated(options, initialSchemas, initialAttributeMapping); } services.AddSingleton <ISCIMRepresentationCommandRepository, SCIMRepresentationCommandRepository>(); services.AddSingleton <ISCIMRepresentationQueryRepository, SCIMRepresentationQueryRepository>(); services.AddSingleton <ISCIMSchemaQueryRepository, SCIMSchemaQueryRepository>(); services.AddSingleton <ISCIMSchemaCommandRepository, SCIMSchemaCommandRepository>(); services.AddSingleton <ISCIMAttributeMappingQueryRepository, SCIMAttributeMappingQueryRepository>(); return(services); }
public MongoAssetRepository(IMongoDatabase database, IOptions <MongoDbOptions> options) : base(database) { Guard.NotNull(options, nameof(options)); this.options = options.Value; }
public PatchaWalletDbClient(IOptions <MongoDbOptions> optionsAccessor) { _options = optionsAccessor.Value; _client = new MongoClient(_options.Connection); StocksCollection = new DocumentCollection <Stock>(_client, _options.DatabaseId, STOCK_COLLECTION_ID); }
public void GetCollectionName_NoTableAttribute_ReturnsDefaultCollectionName() { // Arrange var loggerMock = new Mock <ILogger <GenericRepository <TestDalModelWithoutTableAttribute> > >(); var mongoCollection = new Mock <IMongoCollection <TestDalModelWithoutTableAttribute> >(); var mongoDatabase = new Mock <IMongoDatabase>(); mongoDatabase .Setup(md => md.GetCollection <TestDalModelWithoutTableAttribute>(It.IsAny <string>(), It.IsAny <MongoCollectionSettings>())) .Returns(mongoCollection.Object); var mongoClientMock = new Mock <IMongoClient>(); mongoClientMock .Setup(mc => mc.GetDatabase(It.IsAny <string>(), It.IsAny <MongoDatabaseSettings>())) .Returns(mongoDatabase.Object); var mongoRawOptions = new MongoDbOptions(); var mongoOptions = Microsoft.Extensions.Options.Options.Create(mongoRawOptions); // Act var genericRepository = new GenericRepository <TestDalModelWithoutTableAttribute>( loggerMock.Object, mongoClientMock.Object, mongoOptions); // Assert Assert.AreEqual(1, loggerMock.Invocations.Count); }
public MongoDbFixtureInitializer(IMongoDatabase database, IMongoDbSeeder seeder, MongoDbOptions options) { _seeder = seeder; _seed = options.Seed; }
/// <summary> /// Constructor /// </summary> /// <param name="applicationName">Name to identify the connection to MongoDb with</param> /// <param name="mongoDbOptions"></param> /// <param name="defaultCollectionName">Default collectionNamePostfix to write to unless overridden</param> public MongoDbAdapter(string applicationName, MongoDbOptions mongoDbOptions, string defaultCollectionName) { if (string.IsNullOrWhiteSpace(defaultCollectionName)) { throw new ArgumentException("defaultCollectionName"); } _logger.Debug("MongoDbAdapter: Creating connection to MongoDb on " + mongoDbOptions.HostName + ":" + mongoDbOptions.Port); //TODO Standardise AppId MongoClient mongoClient = MongoClientHelpers.GetMongoClient(mongoDbOptions, "MongoDbPopulator::" + applicationName, string.IsNullOrWhiteSpace(mongoDbOptions.UserName)); _logger.Debug("MongoDbAdapter: Getting reference to database " + mongoDbOptions.DatabaseName); _database = mongoClient.GetDatabase(mongoDbOptions.DatabaseName); _logger.Debug("MongoDbAdapter: Getting reference to collection " + defaultCollectionName); _defaultCollectionName = defaultCollectionName; _defaultCollection = _database.GetCollection <BsonDocument>(defaultCollectionName); _logger.Debug("MongoDbAdapter: Checking initial collection"); bool isLive = _database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait(1000); if (!isLive) { throw new ArgumentException($"Could not connect to the MongoDB server/database on startup at {mongoDbOptions.HostName}:{mongoDbOptions.Port}"); } _logger.Debug("MongoDbAdapter: Connection setup successfully"); }
private static int RecreateReport(GlobalOptions globalOptions, CohortPackagerCliOptions cliOptions) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Info($"Recreating report for job {cliOptions.ExtractionId}"); MongoDbOptions mongoDbOptions = globalOptions.MongoDatabases.ExtractionStoreOptions; MongoClient client = MongoClientHelpers.GetMongoClient(mongoDbOptions, SmiCliInit.HostProcessName); var jobStore = new MongoExtractJobStore(client, mongoDbOptions.DatabaseName); // NOTE(rkm 2020-10-22) Sets the extraction root to the current directory IJobReporter reporter = JobReporterFactory.GetReporter( "FileReporter", jobStore, new FileSystem(), Directory.GetCurrentDirectory(), cliOptions.ReportFormat.ToString(), cliOptions.OutputNewLine ?? globalOptions.CohortPackagerOptions.ReportNewLine, createJobIdFile: false ); try { reporter.CreateReport(cliOptions.ExtractionId); } catch (Exception e) { logger.Error(e); return(1); } return(0); }
public MongoUserStore(IMongoDatabase database, IOptions <MongoDbOptions> options) : base(database) { Guard.NotNull(options, nameof(options)); this.options = options.Value; }
public void OneTimeSetUp() { TestLogger.Setup(); GlobalOptions globalOptions = new GlobalOptionsFactory().Load(); _mongoOptions = globalOptions.MongoDatabases.DicomStoreOptions; }
public ClientFactory(IOptions <MongoDbOptions> mongoDbOptions, IOptions <TvMazeAPIOptions> tvMazeAPIOptions, ILogger <ClientFactory> logger) { _mongoDbOptions = mongoDbOptions.Value; _tvMazeApiOptions = tvMazeAPIOptions.Value; _logger = logger; }
public MongoDbInitializer(IMongoDatabase database, IMongoDbSeeder seeder, MongoDbOptions options) { _database = database; _seeder = seeder; _seed = options.Seed; BsonDefaults.GuidRepresentation = GuidRepresentation.CSharpLegacy; }
public MongoDbRepository(IOptionsMonitor <MongoDbOptions> mongoDbOptions) { _mongoDbOptions = mongoDbOptions.CurrentValue; var client = new MongoClient(_mongoDbOptions.ConnectionString); var db = client.GetDatabase(_mongoDbOptions.DataBaseName); _items = db.GetCollection <ToDoItem>(_mongoDbOptions.CollectionName); }
public MongoDbFixture(string collectionName, MongoDbOptions options) { _client = new MongoClient(options.ConnectionString); _databaseName = options.Database; _collectionName = collectionName; _database = _client.GetDatabase(_databaseName); //InitializeMongo(); _collection = _database.GetCollection <TEntity>(_collectionName); }
public QuestionsController(IConfiguration configuration) { var connectionString = configuration.GetConnectionString("default"); var databaseName = configuration.GetSection("databaseName").Value; var options = new MongoDbOptions(connectionString, databaseName, CollectionIds.Questions); var repository = new GenericRepository <Question>(options); _questionService = new QuestionService(repository); }
private async Task RunIt(MongoDbOptions options, IEntityStore store, string chunkId) { var sw = Stopwatch.StartNew(); var all = (await store.LoadItemsAsync <FakeEntity>(x => x.ChunkId == chunkId)).ToArray(); sw.Stop(); all.Length.Should().Be(BulkInsertCount); _logger.LogInformation("ReadBatched Duration: {TimeElapsed} - FindLimit:{FindLimit} FindBatchSize:{FindBatchSize}", sw.ElapsedMilliseconds, options.FindLimit, options.FindBatchSize); }
/// <summary> /// Default constructor /// </summary> /// <param name="options">Options for connecting to MongoDB</param> /// <param name="rabbitMqVirtualHost">RabbitMQ vhost where the messages are located. Used as part of the MongoDB collection names if provided</param> public MongoDeadLetterStore(MongoDbOptions options, string rabbitMqVirtualHost = null) { _logger = LogManager.GetLogger(GetType().Name); MongoClient client = MongoClientHelpers.GetMongoClient(options, "DeadLetterReprocessor"); _database = client.GetDatabase(options.DatabaseName); try { Ping(); } catch (ApplicationException e) { throw new ArgumentException( "Could not connect to the MongoDB server/database on startup at: " + options.HostName + ":" + options.Port, e); } var re = new Regex("^[A-Z_]+$", RegexOptions.IgnoreCase); if (string.IsNullOrWhiteSpace(rabbitMqVirtualHost) || !re.IsMatch(rabbitMqVirtualHost)) { _logger.Info("Not provided a valid string to label the collections (\"" + rabbitMqVirtualHost + "\"), using the default"); DeadLetterStoreCollectionName = DeadLetterStoreBaseCollectionName; DeadLetterGraveyardCollectionName = DeadLetterGraveyardBaseCollectionName; } else { _logger.Info("Provided vhost \"" + rabbitMqVirtualHost + "\" for naming the storage collections"); DeadLetterStoreCollectionName = DeadLetterStoreBaseCollectionName + "-" + rabbitMqVirtualHost; DeadLetterGraveyardCollectionName = DeadLetterGraveyardBaseCollectionName + "-" + rabbitMqVirtualHost; } _logger.Info("Connecting to dead letter store: " + options.DatabaseName + "." + DeadLetterStoreCollectionName); _deadLetterStore = _database.GetCollection <MongoDeadLetterDocument>(DeadLetterStoreCollectionName); long count = _deadLetterStore.CountDocuments(FilterDefinition <MongoDeadLetterDocument> .Empty); _logger.Info("Connected to " + (count > 0 ? "dead letter store containing " + count + " existing messages" : "empty dead letter store")); _logger.Info("Connecting to dead letter graveyard: " + options.DatabaseName + "." + DeadLetterGraveyardCollectionName); _deadLetterGraveyard = _database.GetCollection <MongoDeadLetterGraveyardDocument>(DeadLetterGraveyardCollectionName); count = _deadLetterGraveyard.CountDocuments(FilterDefinition <MongoDeadLetterGraveyardDocument> .Empty); _logger.Info("Connected to " + (count > 0 ? "dead letter graveyard containing " + count + " existing messages" : "empty dead letter graveyard")); }
/// <summary> /// The service for interacting with MongoDb. /// </summary> /// <param name="mongoDbOptions">The MongoDb options to use.</param> public MongoDbService(MongoDbOptions mongoDbOptions) { if (mongoDbOptions == null) { throw new ArgumentNullException(nameof(mongoDbOptions)); } MongoClient mongoClient = new MongoClient(mongoDbOptions.ConnectionString); _database = mongoClient.GetDatabase(mongoDbOptions.Database); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The service collection to add services to.</param> public void ConfigureServices(IServiceCollection services) { // Add controllers services.AddControllers(); // Configure the MongoDb options IConfiguration mongoDbConfiguration = Configuration.GetSection("MongoDb"); MongoDbOptions mongoDbOptions; try { mongoDbOptions = MongoDbOptions.FromConfiguration(mongoDbConfiguration); } catch (Exception exception) { throw new Exception($"Error configuring {nameof(MongoDbOptions)}. {exception.Message}"); } // Add services services.AddTransient <IMongoDbService, MongoDbService>(); services.AddSingleton(mongoDbOptions); // TODO: Move all mappings to a util class BsonClassMap.RegisterClassMap <AssemblyOrPart>(classMap => { // First enact the default mapping classMap.AutoMap(); // Set the BSON ID serializer so that the ID string is serialized as an object ID classMap.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId)); // Map fields that do not have a public setter and are not the ID so that BSON knows about them classMap.MapMember(assemblyOrPart => assemblyOrPart.Name); // Set this as the root class classMap.SetIsRootClass(true); }); // TODO: Move all mappings to a util class BsonClassMap.RegisterClassMap <Assembly>(classMap => { // First enact the default mapping classMap.AutoMap(); // Set the BSON creator to use classMap.MapCreator(assembly => new Assembly(assembly.Id, assembly.Name)); }); // TODO: Move all mappings to a util class BsonClassMap.RegisterClassMap <Part>(classMap => { // First enact the default mapping classMap.AutoMap(); // Set the BSON creator to use classMap.MapCreator(part => new Part(part.Id, part.Name)); }); }
static void Main(string[] args) { WebHost.CreateDefaultBuilder() .ConfigureAppConfiguration((context, config) => { config.Sources.Clear(); var env = context.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); }) .ConfigureServices(services => { services.AddTransient(prov => { var conf = prov.GetRequiredService <IConfiguration>(); var options = new MongoDbOptions { ConnectionString = conf["MongoDb:ConnectionString"], DatabaseName = conf["MongoDb:DatabaseName"] }; return(new WeatherContext(options)); }); services.AddHealthChecks(); }) .Configure((context, app) => { if (context.HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(e => { e.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); e.MapGet("/current", async c => { var weatherContext = c.RequestServices.GetRequiredService <WeatherContext>(); var currentWeather = await weatherContext.Weather.Find(new BsonDocument()).FirstOrDefaultAsync(); await c.Response.WriteAsJsonAsync(currentWeather); }); }); }) .Build() .Run(); }
private MongoDbOptions SetMongoPassword(MongoDbOptions opt) { //get the environment variables current value string envVar = Environment.GetEnvironmentVariable("MONGO_SERVICE_PASSWORD"); //if there's an env var for it and there are mongodb options being used if (!string.IsNullOrWhiteSpace(envVar) && opt != null) { opt.Password = envVar; } return(opt); }
public void Load_db_should() { MongoDbOptions mongoDbOptions = new MongoDbOptions() { Connection = "mongodb://localhost:27017", DatabaseId = "dpsp_unittests" }; var mockMongoDbOptions = new Mock <IOptions <MongoDbOptions> >(); mockMongoDbOptions.Setup(ap => ap.Value).Returns(mongoDbOptions); var repository = new PatchaWalletDbClient(mockMongoDbOptions.Object); }
public MongoRepository( ILogger <MongoRepository> logger, IOptions <MongoDbOptions> options, IMongoClient mongoClient ) { _logger = logger; _options = options.Value; _logger.LogCritical($"mongo connection string: {options.Value.ConnectionString}"); var database = mongoClient.GetDatabase(_database); _skillCollection = database.GetCollection <SkillEntity>(_collection); }
public MongoDbRepository(MongoDbOptions options) { var mongoUrl = new MongoUrl(options.ConnectionString); var settings = MongoClientSettings.FromUrl(mongoUrl); settings.SslSettings = new SslSettings { EnabledSslProtocols = SslProtocols.Tls12 }; var client = new MongoClient(settings); var database = client.GetDatabase(options.DatabaseName); _collection = database.GetCollection <T>(options.CollectionId); }
public static void MongoDbCheck(MongoDbOptions databaseOptions, string dbName) { var client = new MongoClient(databaseOptions.MongoUrl); var database = client.GetDatabase(dbName); var isMongoLive = database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait(1000); while (!isMongoLive) { Global.Logger.Error("MongoDB: Connection to {0} FAILED! Waiting for connection", dbName); Thread.Sleep(1000); isMongoLive = database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait(1000); } Global.Logger.Information("MongoDB: Connection to {0} SUCCESSFUL!", dbName); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IConfiguration>(Configuration); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); var connectionString = Configuration.GetConnectionString("HighlightsConnString"); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(connectionString)); var mongoDbOptions = new MongoDbOptions(); Configuration.Bind("MongoDb", mongoDbOptions); services.AddSingleton(mongoDbOptions); services.AddScoped <MongoDbContext>(); services.AddDefaultIdentity <IdentityUser>(options => { options.Password.RequiredLength = 6; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = false; }) .AddEntityFrameworkStores <ApplicationDbContext>(); services.AddScoped <IVideoService, VideoService>(); services.AddTransient <IRepository <FileData>, GenericRepository <FileData> >(); services.AddTransient <IMongoRepository <FileData>, MongoDbRepository <FileData> >(); services.Configure <RazorViewEngineOptions>(o => { // {2} is area, {1} is controller,{0} is the action o.ViewLocationFormats.Add($"/Views/Partial/{{0}}{RazorViewEngine.ViewExtension}"); o.ViewLocationFormats.Add($"/Views/Video/{{0}}{RazorViewEngine.ViewExtension}"); }); services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public static IConveyBuilder AddMongo(this IConveyBuilder builder, MongoDbOptions mongoOptions, Type seederType = null, bool registerConventions = true) { if (!builder.TryRegister(RegistryName)) { return(builder); } if (mongoOptions.SetRandomDatabaseSuffix) { var suffix = $"{Guid.NewGuid():N}"; Console.WriteLine($"Setting a random MongoDB database suffix: '{suffix}'."); mongoOptions.Database = $"{mongoOptions.Database}_{suffix}"; } builder.Services.AddSingleton(mongoOptions); builder.Services.AddSingleton <IMongoClient>(sp => { var options = sp.GetRequiredService <MongoDbOptions>(); return(new MongoClient(options.ConnectionString)); }); builder.Services.AddTransient(sp => { var options = sp.GetRequiredService <MongoDbOptions>(); var client = sp.GetRequiredService <IMongoClient>(); return(client.GetDatabase(options.Database)); }); builder.Services.AddTransient <IMongoDbInitializer, MongoDbInitializer>(); builder.Services.AddTransient <IMongoSessionFactory, MongoSessionFactory>(); if (seederType is null) { builder.Services.AddTransient <IMongoDbSeeder, MongoDbSeeder>(); } else { builder.Services.AddTransient(typeof(IMongoDbSeeder), seederType); } builder.AddInitializer <IMongoDbInitializer>(); if (registerConventions && !_conventionsRegistered) { RegisterConventions(); } return(builder); }
public GenericRepositoryTests() { var loggerMock = new Mock <ILogger <GenericRepository <TestDalModel> > >(); _mongoCollectionMock = new Mock <IMongoCollection <TestDalModel> >(); _mongoDatabaseMock = new Mock <IMongoDatabase>(); _mongoClientMock = new Mock <IMongoClient>(); Setup(); var mongoRawOptions = new MongoDbOptions(); var mongoOptions = Microsoft.Extensions.Options.Options.Create(mongoRawOptions); _genericRepository = new GenericRepository <TestDalModel>( loggerMock.Object, _mongoClientMock.Object, mongoOptions); }
public static void AddLogMongodb(this IServiceCollection services, Action <MongoDbOptions> action = null) { MongoDbOptions options = new MongoDbOptions(); action?.Invoke(options); services.AddSingleton(options); services.AddSingleton <IMongodbTransPortService, LogMongodbTransPortService>(); TransPortServiceDependencyInjection.AddFunc((serviceProvider, name) => { if (name.Equals(MongodbConstant.MONGODBNAME, StringComparison.OrdinalIgnoreCase)) { return(serviceProvider.GetService <IMongodbTransPortService>()); } return(null); }); }