private DatabaseClient() { if (ConnectionInfo == null) { var colorWas = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("! default mongo connection is used !"); Console.ForegroundColor = colorWas; this.client = new MongoClient(); } else { //var settings = new MongoClientSettings(); //settings.Server = MongoServerAddress.Parse(ConnectionInfo.Server); //settings. var mongourlBuilder = new MongoUrlBuilder(); mongourlBuilder.Server = MongoServerAddress.Parse(ConnectionInfo.Server); mongourlBuilder.Username = ConnectionInfo.Username; mongourlBuilder.Password = ConnectionInfo.Password; this.client = new MongoClient(mongourlBuilder.ToMongoUrl()); } //TODO: implement connection //this.client = new MongoClient(); }
public MongoEventStore(ILoggerFactory loggerFactory, IEventStoreOptions options) { if (!(options is IMongoEventStoreOptions mongoOptions)) { throw new Exception("Options should be of type IMongoDatabaseOptions"); } Logger = loggerFactory.CreateLogger(GetType()); var mongoClientSettings = new MongoClientSettings { Server = MongoServerAddress.Parse(mongoOptions.ConnectionString) }; try { var client = new MongoClient(mongoClientSettings); var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrWhiteSpace(environment)) { environment = "testing"; } var mongoDatabase = client.GetDatabase($"{mongoOptions.DatabaseName}-{environment}"); Collection = mongoDatabase.GetCollection <TEvent>(options.CollectionName); } catch (Exception exception) { Logger.LogCritical( $"Error while connecting to {mongoClientSettings.Server.Host}. Exception: {exception.Message}", exception); throw; } }
public void TestParseWithHostAndPort() { var credentials = MongoServerAddress.Parse("host:123"); Assert.AreEqual("host", credentials.Host); Assert.AreEqual(123, credentials.Port); }
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); var connectionString = "ConnectTo=tcp://admin:changeit@localhost:1113; HeartBeatTimeout=500"; services.AddSingleton(x => EventStoreConnection.Create(connectionString: connectionString)); services.AddTransient <ITransientDomainEventPublisher, TransientDomainEventPubSub>(); services.AddTransient <ITransientDomainEventSubscriber, TransientDomainEventPubSub>(); services.AddTransient <IRepository <Cart, CartId>, EventSourcingRepository <Cart, CartId> >(); services.AddSingleton <IEventStore, EventStoreEventStore>(); var mongoSettings = new MongoClientSettings() { Server = MongoServerAddress.Parse("localhost:1234"), }; services.AddSingleton(x => new MongoClient(mongoSettings)); services.AddSingleton(x => x.GetService <MongoClient>().GetDatabase(ReadModelDBName)); services.AddTransient <IReadOnlyRepository <ReadCart>, MongoDBRepository <ReadCart> >(); services.AddTransient <IRepository <ReadCart>, MongoDBRepository <ReadCart> >(); services.AddTransient <IReadOnlyRepository <ReadCartItem>, MongoDBRepository <ReadCartItem> >(); services.AddTransient <IRepository <ReadCartItem>, MongoDBRepository <ReadCartItem> >(); services.AddTransient <IReadOnlyRepository <Product>, MongoDBRepository <Product> >(); services.AddTransient <IRepository <Product>, MongoDBRepository <Product> >(); services.AddTransient <IReadOnlyRepository <Customer>, MongoDBRepository <Customer> >(); services.AddTransient <IRepository <Customer>, MongoDBRepository <Customer> >(); services.AddTransient <IDomainEventHandler <CartId, CartCreatedEvent>, CartUpdater>(); services.AddTransient <IDomainEventHandler <CartId, ProductAddedEvent>, CartUpdater>(); services.AddTransient <IDomainEventHandler <CartId, ProductQuantityChangedEvent>, CartUpdater>(); services.AddTransient <ICartWriter, CartWriter>(); services.AddTransient <ICartReader, CartReader>(); }
//========================================================================= // // AJAX ACTIONS // //========================================================================= /// <summary> /// Fetches the instance log by connecting to its mongod server. /// This is fast and cheap, but won't work if the instance is down. /// </summary> public JsonResult GetServerLog(int id) { var server = ServerStatus.Get(id); var urlBuilder = new MongoUrlBuilder(); urlBuilder.ConnectTimeout = new TimeSpan(0, 0, 3); urlBuilder.Server = MongoServerAddress.Parse(server.Name); urlBuilder.ReadPreference = ReadPreference.SecondaryPreferred; var client = new MongoClient(urlBuilder.ToMongoUrl()); var conn = client.GetServer(); try { var command = new CommandDocument { { "getLog", "global" } }; var result = conn.GetDatabase("admin").RunCommand(command); return(Json(new { log = HtmlizeFromLogArray(result. Response["log"].AsBsonArray) }, JsonRequestBehavior.AllowGet)); } catch (MongoException e) { return(Json(new { error = e.Message }, JsonRequestBehavior.AllowGet)); } }
public IMongoDatabase BuildDatabaseClient(DatabaseSettings dbSettings) { Console.WriteLine($"Configured with these Settings: {Environment.NewLine}" + $"{JToken.FromObject(dbSettings).ToString()}"); var credential = MongoCredential.CreateCredential("admin", dbSettings.DatabaseUserName, dbSettings.DatabasePassword); var clientSettings = new MongoClientSettings() { Credential = credential, Server = MongoServerAddress.Parse(dbSettings.ConnectionString), AllowInsecureTls = true }; var client = new MongoClient(clientSettings); // DB Configuration var pack = new ConventionPack() { new EnumRepresentationConvention(BsonType.String) }; ConventionRegistry.Register("EnumStringConvention", pack, t => true); return(client.GetDatabase(dbSettings.DatabaseName)); }
public MongoDbService(MongoDBConfig dBConfig) { _dBConfig = dBConfig; _client = new MongoClient(new MongoClientSettings() { Server = MongoServerAddress.Parse(_dBConfig.Host), Credential = string.IsNullOrEmpty(_dBConfig.AuthMechanism) ? null : MongoCredential.CreateCredential( _dBConfig.AuthSource, _dBConfig.Username, _dBConfig.Password ) }); _dB = _client.GetDatabase(_dBConfig.Database); _data = _dB.GetCollection <CcData>(_dBConfig.CollectionData); _events = _dB.GetCollection <CcEvent>(_dBConfig.CollectionEvents); _groups = _dB.GetCollection <CcGroup>(_dBConfig.CollectionGroups); Data = new MongoCollection <CcData>(_data); Events = new MongoCollection <CcEvent>(_events); Groups = new MongoCollection <CcGroup>(_groups); }
private void ProcessFirstResponse(ConnectResponse response) { var isMasterResponse = response.IsMasterResult.Response; // first response has to match replica set name in settings (if any) var replicaSetName = isMasterResponse["setName"].AsString; if (_server.Settings.ReplicaSetName != null && replicaSetName != _server.Settings.ReplicaSetName) { var message = string.Format( "Server at address '{0}' is a member of replica set '{1}' and not '{2}'.", response.ServerInstance.Address, replicaSetName, _server.Settings.ReplicaSetName); throw new MongoConnectionException(message); } _server.ReplicaSetName = replicaSetName; // find all valid addresses var validAddresses = new HashSet <MongoServerAddress>(); if (isMasterResponse.Contains("hosts")) { foreach (string address in isMasterResponse["hosts"].AsBsonArray) { validAddresses.Add(MongoServerAddress.Parse(address)); } } if (isMasterResponse.Contains("passives")) { foreach (string address in isMasterResponse["passives"].AsBsonArray) { validAddresses.Add(MongoServerAddress.Parse(address)); } } if (isMasterResponse.Contains("arbiters")) { foreach (string address in isMasterResponse["arbiters"].AsBsonArray) { validAddresses.Add(MongoServerAddress.Parse(address)); } } // remove server instances created from the seed list that turn out to be invalid var invalidInstances = _server.Instances.Where(i => !validAddresses.Contains(i.Address)).ToArray(); // force evaluation foreach (var invalidInstance in invalidInstances) { _server.RemoveInstance(invalidInstance); } // add any server instances that were missing from the seed list foreach (var address in validAddresses) { if (!_server.Instances.Any(i => i.Address == address)) { var missingInstance = new MongoServerInstance(_server, address); _server.AddInstance(missingInstance); QueueConnect(missingInstance); } } }
public void TestParse(string host, int port, string value) { var address = MongoServerAddress.Parse(value); Assert.AreEqual(host, address.Host); Assert.AreEqual(port, address.Port); }
public void TestParse_InvalidValue(string value) { var expection = Record.Exception(() => MongoServerAddress.Parse(value)); Assert.IsType <FormatException>(expection); var expectedMessage = string.Format("'{0}' is not a valid server address.", value); Assert.Equal(expectedMessage, expection.Message); }
/// <summary> /// Raises the <see cref="E:System.Windows.Application.Startup"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); if (string.IsNullOrWhiteSpace(Settings.Default.MongoDbConnectionSettingFile)) { WriteLog("mongodb connection setting empty."); return; } var file = new FileInfo(Settings.Default.MongoDbConnectionSettingFile); if (!file.Exists) { WriteLog("mongodb connection file not exists."); return; } var model = file.JsonFileToObject <MongoDbConnectionModel>(); var builder = new MongoUrlBuilder { Server = MongoServerAddress.Parse(model.LoginAddress), DatabaseName = model.LoginDatabaseName, Username = model.LoginUserName, Password = model.LoginUserPassword }; this.mongoClient = new MongoClient(builder.ToMongoUrl()); this.mongoDatabase = this.mongoClient.GetDatabase("JryDictionary"); this.ThingSetAccessor = new ThingSetAccessor(this.mongoDatabase); this.SettingSetAccessor = new SettingSetAccessor(this.mongoDatabase); this.ThingSetAccessor.Initialize(); this.ModuleManager.Initialize(); if (File.Exists("Settings.json")) { using (var stream = File.OpenRead("Settings.json")) { this.JsonSettings = stream.ToArray().TryJsonToObject <Common.Settings>(); if (!string.IsNullOrWhiteSpace(this.JsonSettings?.Proxy)) { try { WebRequest.DefaultWebProxy = new WebProxy(this.JsonSettings?.Proxy); } catch (Exception) { if (Debugger.IsAttached) { Debugger.Break(); } } } } } }
public void TestFromUrlResolving(string connectionString, ConnectionStringScheme expectedScheme, string expectedEndPoint) { var url = new MongoUrl(connectionString); var result = MongoClientSettings.FromUrl(url); var expectedServers = new[] { MongoServerAddress.Parse(expectedEndPoint) }; result.Servers.Should().Equal(expectedServers); result.Scheme.Should().Be(expectedScheme); }
public PokemonService(PokemonDatabaseSettings settings, ILogger <PokemonService> logger) { this._logger = logger; var client = new MongoClient(new MongoClientSettings() { Server = MongoServerAddress.Parse(settings.Server), Credential = MongoCredential.CreateCredential(settings.DatabaseName, settings.UserName, settings.Password), }); var database = client.GetDatabase(settings.DatabaseName); this._pokemons = database.GetCollection <PokemonModel>(settings.CollectionName); }
public BookService(IBookstoreDatabaseSettings settings) { var client = new MongoClient(new MongoClientSettings { Server = MongoServerAddress.Parse(settings.ConnectionString), Credential = MongoCredential.CreateCredential( settings.Creds.Db, settings.Creds.User, settings.Creds.Password) }); var database = client.GetDatabase(settings.DatabaseName); _books = database.GetCollection <Book>(settings.BooksCollectionName); }
private static MongoDbCacheOptions CreateOptionsWithMongoClientSettings() { return(new MongoDbCacheOptions { MongoClientSettings = new MongoClientSettings { Server = MongoServerAddress.Parse("localhost") }, DatabaseName = "MongoCache", CollectionName = "appcache", ExpiredScanInterval = TimeSpan.FromMinutes(10) }); }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseConnection"/> class. /// </summary> /// <param name="configuration">A <see cref="IOptions{TOptions}"/> with database connection parameters.</param> public DatabaseConnection(IOptions <EmbeddingsConfiguration> configuration) { var config = configuration.Value; var settings = new MongoClientSettings { Servers = config.Servers.Select(_ => MongoServerAddress.Parse(_)), GuidRepresentation = GuidRepresentation.Standard, MaxConnectionPoolSize = config.MaxConnectionPoolSize, ClusterConfigurator = cb => cb.Subscribe(new DiagnosticsActivityEventSubscriber()) }; MongoClient = new MongoClient(settings.Freeze()); Database = MongoClient.GetDatabase(config.Database); }
public IMongoClient GetClient() { if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) { return(new MongoClient(Server)); } var credentials = MongoCredential.CreateCredential(Database, Username, Password); var settings = new MongoClientSettings() { Credential = credentials, Server = MongoServerAddress.Parse(Server.Replace("mongodb://", "")) }; return(new MongoClient(settings)); }
public MongoDbConnector(MongoDbConfiguration config) { Client = new MongoClient(new MongoClientSettings { Server = MongoServerAddress.Parse(config.Server), Credential = MongoCredential.CreateCredential(config.Credentials.Database, config.Credentials.User, config.Credentials.Password), UseSsl = false, VerifySslCertificate = false, SslSettings = new SslSettings { CheckCertificateRevocation = false } }); Database = Client.GetDatabase(config.Database); }
public async Task <bool> Initialize(JryVideoDataSourceProviderManagerMode mode) { var builder = new MongoUrlBuilder(); builder.Server = MongoServerAddress.Parse("127.0.0.1:50710"); builder.DatabaseName = "admin"; builder.Username = "******"; builder.Password = "******"; this.Client = new MongoClient(builder.ToMongoUrl()); this.Database = this.Client.GetDatabase("JryVideo_" + mode.ToString()); return(true); }
public HomeModule() { Get["/", true] = async(x, ct) => { var model = new Result(); try { using (var myBus = RabbitHutch.CreateBus("host=rabbitmq")) { if (myBus.IsConnected) { model.RabbitMqState = TestState.Successful; } } } catch (Exception ex) { Console.WriteLine(ex); model.RabbitMqState = TestState.Failed; } try { var mongoSettings = new MongoClientSettings { ConnectTimeout = TimeSpan.FromSeconds(5), Server = MongoServerAddress.Parse("mongo:27017") }; var client = new MongoClient(mongoSettings); var db = client.GetDatabase("MessagingServerDB"); var mongotest = await db.RunCommandAsync((Command <BsonDocument>) "{ping:1}"); model.MongoDbState = TestState.Successful; } catch (Exception ex) { Console.WriteLine(ex); model.MongoDbState = TestState.Failed; } return(View["Home", model]); }; }
public IMongoDatabase BuildDatabaseClient(DatabaseSettings dbSettings) { Console.WriteLine($"Configured with these Settings: {Environment.NewLine}" + $"{JToken.FromObject(dbSettings).ToString()}"); var credential = MongoCredential.CreateCredential("admin", dbSettings.DatabaseUserName, dbSettings.DatabasePassword); var clientSettings = new MongoClientSettings() { Credential = credential, Server = MongoServerAddress.Parse(dbSettings.ConnectionString), AllowInsecureTls = true }; var client = new MongoClient(clientSettings); return(client.GetDatabase(dbSettings.DatabaseName)); }
//========================================================================= // // AJAX ACTIONS // //========================================================================= /// <summary> /// Fetches the instance log by connecting to its mongod server. /// This is fast and cheap, but won't work if the instance is down. /// </summary> public JsonResult GetServerLog(int id) { var server = ServerStatus.Get(id); var mongo = MongoServer.Create(new MongoServerSettings { ConnectTimeout = new TimeSpan(0, 0, 3), Server = MongoServerAddress.Parse(server.Name), SlaveOk = true }); try { var result = mongo["admin"]["$cmd"].FindOne(Query.EQ("getLog", "global")); return(Json(new { log = HtmlizeFromLogArray(result.AsBsonDocument["log"].AsBsonArray) }, JsonRequestBehavior.AllowGet)); } catch (MongoException e) { return(Json(new { error = e.Message }, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// MongoDbContext /// </summary> /// <param name="option"></param> public MongoDbContext(IOptions <MongoDbOptions> option) { //芒果数据库客户端配置 var settings = new MongoClientSettings { Server = MongoServerAddress.Parse(option.Value.ConnectionString) }; //开启授权操作 if (option.Value.IsEnabledAuthorization) { settings.Credential = MongoCredential.CreateCredential(option.Value.DataBase, option.Value.UserName, option.Value.Password); } var client = new MongoClient(settings); _db = client.GetDatabase(option.Value.DataBase); }
private IMongoDatabase CreateDatabaseConnection(IOptions <MongoSettings> mongoSettings) { var configuration = mongoSettings.Value; // or use a connection string var settings = new MongoClientSettings() { Credentials = new[] { MongoCredential.CreateCredential( configuration.DatabaseName, configuration.Username, configuration.Password) }, Server = MongoServerAddress.Parse(configuration.ConnectionString) }; var client = new MongoClient(settings); return(client.GetDatabase(configuration.DatabaseName)); }
private static IServiceCollection AddMongoDb( this IServiceCollection services, DatabasesSettings mongoDbSettings) { services.AddSingleton <IMongoClient>(_ => { var mongoClientSettings = new MongoClientSettings { Servers = new[] { MongoServerAddress.Parse(mongoDbSettings.MongoDBConnectionString) } }; return(new MongoClient(mongoClientSettings)); }); services.AddSingleton(p => p.GetRequiredService <IMongoClient>().GetDatabase(mongoDbSettings.MongoDBName)); return(services); }
private List <MongoServerAddress> GetHostAddresses( QueryNodeResponse response ) { if (!response.IsMasterResult.Response.Contains("hosts")) { var message = string.Format("Server is not a member of a replica set: {0}", response.Address); throw new MongoConnectionException(message); } var nodes = new List <MongoServerAddress>(); foreach (BsonString host in response.IsMasterResult.Response["hosts"].AsBsonArray.Values) { var address = MongoServerAddress.Parse(host.Value); nodes.Add(address); } return(nodes); }
public void Resolve_with_resolveHosts_should_return_expected_result(string url, bool resolveHosts, string expectedServer, bool async) { var subject = new MongoUrl(url); MongoUrl result; if (async) { result = subject.Resolve(resolveHosts); } else { result = subject.ResolveAsync(resolveHosts).GetAwaiter().GetResult(); } var expectedServers = new[] { MongoServerAddress.Parse(expectedServer) }; result.Servers.Should().Equal(expectedServers); }
/// <summary> /// Constructor /// </summary> /// <param name="memoryCache"></param> /// <param name="loggerFactory"></param> /// <param name="options"></param> public MongoFactory(IMemoryCache memoryCache, ILoggerFactory loggerFactory, IRepositoryOptions options) : base(memoryCache, loggerFactory, options) { if (!(options is IMongoDatabaseOptions mongoOptions)) { throw new Exception("Options should be of type IMongoDatabaseOptions"); } _logger = loggerFactory.CreateLogger(GetType()); try { MongoClient client; try { var mongoClientSettings = new MongoClientSettings { Server = MongoServerAddress.Parse(mongoOptions.ConnectionString), MaxConnectionIdleTime = TimeSpan.FromMinutes(1) }; client = new MongoClient(mongoClientSettings); } catch { client = new MongoClient(mongoOptions.ConnectionString); } var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrWhiteSpace(environment)) { environment = "Development"; } _mongoDatabase = client.GetDatabase($"{mongoOptions.DatabaseName}-{environment}"); Repositories = new ConcurrentDictionary <Type, object>(); } catch (Exception exception) { _logger.LogCritical( $"Error while connecting to {mongoOptions.ConnectionString}.", exception); throw; } }
public DbService(MongoDBConfig dBConfig) { _dBConfig = dBConfig; _client = new MongoClient(new MongoClientSettings() { Server = MongoServerAddress.Parse(_dBConfig.Host), Credential = MongoCredential.CreateCredential( _dBConfig.AuthSource, _dBConfig.Username, _dBConfig.Password ) }); _dB = _client.GetDatabase(_dBConfig.Database); ColScheduler = _dB.GetCollection <ColScheduler>(_dBConfig.CollectionScheduler); ColTimers = _dB.GetCollection <ColTimers>(_dBConfig.CollectionTimers); ColRepoInfo = _dB.GetCollection <ColRepoInfo>(_dBConfig.CollectionRepoInfo); ColIndexInfo = _dB.GetCollection <ColIndexInfo>(_dBConfig.CollectionIndexInfo); CachedColIndexInfo = new CachedCollection <ColIndexInfo>(ColIndexInfo); }
public MongoFileManager(MongoConfiguration configuration) { _configuration = configuration; MongoClient client; if (!string.IsNullOrEmpty(configuration.Username) && !string.IsNullOrEmpty(configuration.Password)) { var credentials = MongoCredential.CreateCredential(configuration.Database, configuration.Username, configuration.Password); var settings = new MongoClientSettings() { Credential = credentials, Server = MongoServerAddress.Parse(configuration.Server.Replace("mongodb://", "")) }; client = new MongoClient(settings); } else { client = new MongoClient(configuration.Server); } var db = client.GetDatabase(configuration.Database); Bucket = new GridFSBucket(db); }