/// <summary> /// Initializes a new instance of the <see cref="JobStore"/> class. /// </summary> public JobStore() { log = LogManager.GetLogger(GetType()); string connectionString; if( ConfigurationManager.ConnectionStrings["quartznet-mongodb"] != null ) connectionString = ConfigurationManager.ConnectionStrings["quartznet-mongodb"].ConnectionString; else connectionString = DefaultConnectionString; // // If there is no connection string to use then throw an // exception to abort construction. // if (string.IsNullOrWhiteSpace(connectionString)) throw new ApplicationException("Connection string is missing for the MongoDB job store."); lock (lockObject) { var urlBuilder = new MongoUrlBuilder(connectionString); var client = new MongoClient(urlBuilder.ToMongoUrl()); this.database = client.GetServer().GetDatabase(urlBuilder.DatabaseName); } }
private void InitiateDatabase() { var connectionString = ConfigurationManager.ConnectionStrings["Mongo.ConnectionString"].ConnectionString; var mongoUrlBuilder = new MongoUrlBuilder(connectionString); mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl()); Database = mongoClient.GetDatabase(mongoUrlBuilder.DatabaseName); }
public void MongoUriConstructor() { var uriBuilder = new MongoUrlBuilder("mongodb://*****:*****@localhost/myDatabase"); IMongoDatabaseFactory mongoDbFactory = new SimpleMongoDatabaseFactory(uriBuilder.ToMongoUrl()); Assert.That(ReflectionUtils.GetInstanceFieldValue(mongoDbFactory, "_credentials"), Is.EqualTo(new MongoCredentials("myUsername", "myPassword"))); Assert.That(ReflectionUtils.GetInstanceFieldValue(mongoDbFactory, "_databaseName").ToString(), Is.EqualTo("myDatabase")); }
static MongoDatabase CreatDataBase(string bdName, string userName, string userPw) { var mongoUrlBuilder = new MongoUrlBuilder("mongodb://localhost"); MongoServer server = MongoServer.Create(mongoUrlBuilder.ToMongoUrl()); MongoCredentials credentials = new MongoCredentials(userName, userPw); MongoDatabase database = server.GetDatabase(bdName, credentials); return database; }
public MongoEventStore(string connectionString, ITypeCatalog typeCatalog) { _eventHashRef = new Dictionary<string, string>(); typeCatalog.GetDerivedTypes(typeof(DomainEvent)).ToList(). ForEach(x => BsonClassMap.RegisterClassMap(new DomainEventMapper(x, _eventHashRef))); var connection = new MongoUrlBuilder(connectionString); _collection = MongoServer.Create(connection.ToMongoUrl()).GetDatabase(connection.DatabaseName).GetCollection<DomainEvent>("events"); }
private static MongoDatabase GetDatabase() { var testDbConnStrBuilder = new MongoUrlBuilder("mongodb://localhost/Guid-vs-ObjectId?safe=true"); var connectionString = testDbConnStrBuilder.ToMongoUrl(); var client = new MongoClient(connectionString); var mongoDatabase = client.GetServer().GetDatabase(connectionString.DatabaseName); mongoDatabase.SetProfilingLevel(ProfilingLevel.All); return mongoDatabase; }
public void Init() { var connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString; var connectionStringBuilder = new MongoUrlBuilder(connectionString); var mongoClient = new MongoClient(connectionStringBuilder.ToMongoUrl()); _server = mongoClient.GetServer(); var dbName = connectionStringBuilder.DatabaseName; _db = _server.GetDatabase(dbName); }
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 void TestClone() { // set everything to non default values to test that all settings are cloned var connectionString = "mongodb://*****:*****@somehost/?" + "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" + "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" + "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;secondaryAcceptableLatency=128;socketTimeout=129;" + "ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" + "fireAndForget=false;fsync=true;journal=true;w=2;wtimeout=131"; var builder = new MongoUrlBuilder(connectionString); var url = builder.ToMongoUrl(); var settings = MongoClientSettings.FromUrl(url); var clone = settings.Clone(); Assert.AreEqual(settings, clone); }
public void Setup() { _runner = MongoDbRunner.Start(); var mongoUrlBuilder = new MongoUrlBuilder(_runner.ConnectionString); mongoUrlBuilder.DatabaseName = "AutomatedTest"; //setup mongo database var client = new MongoClient(mongoUrlBuilder.ToMongoUrl()); Database = client.GetDatabase(mongoUrlBuilder.DatabaseName); Collection = Database.GetCollection<RootEntity>("Root"); ContainsNotProvidedTagsEntityId = ObjectId.GenerateNewId(); SubEntityId = ObjectId.GenerateNewId(); //add mock data var entities = new List<RootEntity>() { new RootEntity() { Id = ObjectId.GenerateNewId(), Tags = new List<string>() {"tag1"}, SubCollection = new List<SubEntity>() { new SubEntity() { Id = SubEntityId } } }, new RootEntity() { Id = ContainsNotProvidedTagsEntityId, Tags = new List<string>() {"tag1", "tag2"}, SubCollection = new List<SubEntity>() { new SubEntity() { Id = SubEntityId } } } }; Collection.InsertManyAsync(entities).Wait(); }
public static void Main(string[] args) { var definition = Configuration.Configure<CmdLine>(); CmdLine cmdLine = null; try { cmdLine = definition.CreateAndBind(args); } catch (InvalidOperationException) { ShowHelp(definition); Environment.Exit(0); } if (cmdLine.ShowHelp || !cmdLine.IsValid()) { ShowHelp(definition); Environment.Exit(0); } var mongoUrlBuilder = new MongoUrlBuilder { DatabaseName = cmdLine.Database, ConnectTimeout = TimeSpan.FromSeconds(30), Server = new MongoServerAddress(cmdLine.DatabaseHost, cmdLine.DatabasePort), }; var scriptRunner = new MongoScriptRunner(cmdLine.MongoClient, mongoUrlBuilder.ToMongoUrl()); if (cmdLine.DryRun) { System.Console.Out.WriteLine("*** Dry run - nothing is executed."); } var consoleInteraction = (cmdLine.DryRun) ? (IUserInteraction)new DryRunConsoleInteraction() : new InteractiveConsoleInteraction(); Synchronize(scriptRunner, consoleInteraction, cmdLine, mongoUrlBuilder); }
public Task<bool> Initialize(JryVideoDataSourceProviderManagerMode mode) { if (!Enum.IsDefined(typeof(JryVideoDataSourceProviderManagerMode), mode)) throw new ArgumentOutOfRangeException(nameof(mode)); this.Mode = 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 Task.FromResult(true); }
public void TestClone() { // set everything to non default values to test that all settings are cloned var connectionString = "mongodb://*****:*****@somehost/?" + "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" + "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" + "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;secondaryAcceptableLatency=128;socketTimeout=129;" + "ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" + "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other"; var builder = new MongoUrlBuilder(connectionString); var url = builder.ToMongoUrl(); var settings = MongoClientSettings.FromUrl(url); // a few settings can only be made in code settings.Credentials = new[] { MongoCredential.CreateMongoCRCredential("database", "username", "password").WithMechanismProperty("SERVICE_NAME", "other") }; settings.SslSettings = new SslSettings { CheckCertificateRevocation = false }; var clone = settings.Clone(); Assert.AreEqual(settings, clone); }
public MongoContext() { var pack = new ConventionPack() { new CamelCaseElementNameConvention(), new EnumRepresentationConvention(BsonType.String) }; ConventionRegistry.Register("CamelCaseConvensions", pack, t => true); var mongoUrlBuilder = new MongoUrlBuilder(ConfigurationManager.ConnectionStrings["AuthContext"].ConnectionString); var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl()); var server = mongoClient.GetServer(); Database = server.GetDatabase(mongoUrlBuilder.DatabaseName); userCollection = Database.GetCollection<User>("users"); roleCollection = Database.GetCollection<Role>("roles"); clientCollection = Database.GetCollection<Client>("clients"); refreshTokenCollection = Database.GetCollection<RefreshToken>("refreshTokens"); }
public ApiResponse SetConnection(ConnectionModel model) { var builder = new MongoUrlBuilder(); var server = new MongoServerAddress(model.Server, model.Port ?? 27017); builder.Server = server; var url = builder.ToMongoUrl(); try { var conn = MongoServer.Create(url); conn.Connect(); conn.Disconnect(); } catch { return new ApiResponse(false, string.Format("Connection to {0} failed.", url)); } HttpContext.Current.Response.Cookies.Add(new HttpCookie("Mongo.Manager.Connection", url.ToString())); return new ApiResponse(); }
private IContainer BootstrapContainer() { var container = new Container(); container.Configure(cfg => { cfg.Scan(scanner => { scanner.WithDefaultConventions(); scanner.AssemblyContainingType<IScript>(); }); var mongoUrlBuilder = new MongoUrlBuilder(Properties.Settings.Default.TestDatabaseConnectionString); cfg.For<MongoUrlBuilder>() .Singleton() .Use(new MongoUrlBuilder(Properties.Settings.Default.TestDatabaseConnectionString)); cfg.For<MongoDatabase>() .Transient() .Use(ctx => { var client = new MongoClient(mongoUrlBuilder.ToString()); client.GetServer().Connect(); return client.GetServer().GetDatabase(mongoUrlBuilder.DatabaseName); }); cfg.For<MongoDbScriptEnumerator>() .Transient() .Use<MongoDbScriptEnumerator>() .Ctor<string>().Is(Properties.Settings.Default.LogCollectionName); cfg.For<MongoScriptRunner>() .Transient() .Use(() => new MongoScriptRunner(Properties.Settings.Default.MongoClientPath, mongoUrlBuilder.ToMongoUrl())); }); return container; }
protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator) { base.ConfigureBus(configurator); var builder = new MongoUrlBuilder { DatabaseName = EventDatabaseName, Server = new MongoServerAddress("localhost"), Username = "******", Password = "******", ConnectTimeout = TimeSpan.FromSeconds(30), ConnectionMode = ConnectionMode.Automatic, GuidRepresentation = GuidRepresentation.Standard }; var url = builder.ToMongoUrl(); Client = new MongoClient("mongodb://127.0.0.1"); Database = Client.GetDatabase(EventDatabaseName); _convention = new MassTransitMongoDbConventions(); }
public void MongoDbTestFixtureSetup() { var builder = new MongoUrlBuilder { DatabaseName = EventDatabaseName, Server = new MongoServerAddress("localhost", 9001), Username = "******", Password = "******", ConnectTimeout = TimeSpan.FromSeconds(30), ConnectionMode = ConnectionMode.Automatic, GuidRepresentation = GuidRepresentation.Standard }; MongoUrl url = builder.ToMongoUrl(); Client = new MongoClient(url); Server = Client.GetServer(); Database = Server.GetDatabase(EventDatabaseName); _convention = new MassTransitMongoDbConventions(); }
public void TestFromUrl() { // set everything to non default values to test that all settings are converted var connectionString = "mongodb://*****:*****@somehost/?authSource=db;appname=app;" + "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;heartbeatInterval=1m;heartbeatTimeout=2m;" + "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" + "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;localThreshold=128;socketTimeout=129;" + "serverSelectionTimeout=20s;ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" + "w=1;fsync=true;journal=true;w=2;wtimeout=131"; var builder = new MongoUrlBuilder(connectionString); var url = builder.ToMongoUrl(); var settings = MongoServerSettings.FromUrl(url); Assert.Equal(url.ApplicationName, settings.ApplicationName); Assert.Equal(url.ConnectionMode, settings.ConnectionMode); Assert.Equal(url.ConnectTimeout, settings.ConnectTimeout); Assert.Equal(1, settings.Credentials.Count()); Assert.Equal(url.Username, settings.Credentials.Single().Username); Assert.Equal(url.AuthenticationMechanism, settings.Credentials.Single().Mechanism); Assert.Equal(url.AuthenticationSource, settings.Credentials.Single().Source); Assert.Equal(new PasswordEvidence(url.Password), settings.Credentials.Single().Evidence); Assert.Equal(url.GuidRepresentation, settings.GuidRepresentation); Assert.Equal(url.HeartbeatInterval, settings.HeartbeatInterval); Assert.Equal(url.HeartbeatTimeout, settings.HeartbeatTimeout); Assert.Equal(url.IPv6, settings.IPv6); Assert.Equal(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime); Assert.Equal(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime); Assert.Equal(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize); Assert.Equal(url.MinConnectionPoolSize, settings.MinConnectionPoolSize); Assert.Equal(url.ReadPreference, settings.ReadPreference); Assert.Equal(url.ReplicaSetName, settings.ReplicaSetName); Assert.Equal(url.LocalThreshold, settings.LocalThreshold); Assert.True(url.Servers.SequenceEqual(settings.Servers)); Assert.Equal(url.ServerSelectionTimeout, settings.ServerSelectionTimeout); Assert.Equal(url.SocketTimeout, settings.SocketTimeout); Assert.Equal(null, settings.SslSettings); Assert.Equal(url.UseSsl, settings.UseSsl); Assert.Equal(url.VerifySslCertificate, settings.VerifySslCertificate); Assert.Equal(url.ComputedWaitQueueSize, settings.WaitQueueSize); Assert.Equal(url.WaitQueueTimeout, settings.WaitQueueTimeout); Assert.Equal(url.GetWriteConcern(false), settings.WriteConcern); }
public void TestFromUrl() { // set everything to non default values to test that all settings are converted var connectionString = "mongodb://*****:*****@somehost/?" + "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" + "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" + "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;secondaryAcceptableLatency=128;socketTimeout=129;" + "ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" + "fireAndForget=false;fsync=true;journal=true;w=2;wtimeout=131"; var builder = new MongoUrlBuilder(connectionString); var url = builder.ToMongoUrl(); var settings = MongoClientSettings.FromUrl(url); Assert.AreEqual(url.ConnectionMode, settings.ConnectionMode); Assert.AreEqual(url.ConnectTimeout, settings.ConnectTimeout); Assert.AreEqual("{}", settings.CredentialsStore.ToString()); Assert.AreEqual(url.DefaultCredentials, settings.DefaultCredentials); Assert.AreEqual(url.GuidRepresentation, settings.GuidRepresentation); Assert.AreEqual(url.IPv6, settings.IPv6); Assert.AreEqual(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime); Assert.AreEqual(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime); Assert.AreEqual(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize); Assert.AreEqual(url.MinConnectionPoolSize, settings.MinConnectionPoolSize); Assert.AreEqual(url.ReadPreference, settings.ReadPreference); Assert.AreEqual(url.ReplicaSetName, settings.ReplicaSetName); Assert.AreEqual(url.SecondaryAcceptableLatency, settings.SecondaryAcceptableLatency); Assert.IsTrue(url.Servers.SequenceEqual(settings.Servers)); Assert.AreEqual(url.SocketTimeout, settings.SocketTimeout); Assert.AreEqual(url.UseSsl, settings.UseSsl); Assert.AreEqual(url.VerifySslCertificate, settings.VerifySslCertificate); Assert.AreEqual(url.ComputedWaitQueueSize, settings.WaitQueueSize); Assert.AreEqual(url.WaitQueueTimeout, settings.WaitQueueTimeout); Assert.AreEqual(url.GetWriteConcern(false), settings.WriteConcern); }
public void DoTest() { // ------------------------------ // 步骤一. 取得一个 MongoClient 对象. // ------------------------------ // mongoDB 复制集 安装在 mongo01 / mongo02 / mongo03 这3台虚拟机上. MongoUrlBuilder url = new MongoUrlBuilder(); url.ConnectionMode = MongoDB.Driver.ConnectionMode.ReplicaSet; url.DatabaseName = "test"; url.ReplicaSetName = "rs0"; url.Servers = new List<MongoServerAddress>() { MongoServerAddress.Parse("mongo01"), MongoServerAddress.Parse("mongo02"), MongoServerAddress.Parse("mongo03") }; MongoClient client = new MongoClient(url.ToMongoUrl()); // ------------------------------ // 步骤二. 取得一个 MongoServer 对象. // ------------------------------ // Get a Reference to a Server Object MongoServer server = client.GetServer(); // ------------------------------ // 步骤三. 取得一个 MongoDatabase 对象. // ------------------------------ // Get a Reference to a Database Object MongoDatabase database = server.GetDatabase("test"); // "test" is the name of the database // ------------------------------ // 步骤四. 取得一个 MongoCollection 对象. // ------------------------------ // Get a Reference to a Collection Object // "TestMain" is the name of the collection MongoCollection<TestBasic> collection = database.GetCollection<TestBasic>("TestBasic"); // ------------------------------ // 步骤五. 完成 插入、查询、更新、删除 之类的相关操作. // ------------------------------ TestBasic mainData = new TestBasic() { Name = "C# 访问 MongoDB 的例子代码", }; // 完成插入处理. collection.Insert(mainData); // 获取插入后的 id. var id = mainData.Id; Console.WriteLine("数据 {0} 已插入到 MongoDB", mainData); Console.WriteLine("请到命令行方式下执行 db.TestBasic.find() 核对数据!"); Console.WriteLine("按回车键继续测试处理..."); Console.ReadLine(); // 尝试查询. var query = Query<TestBasic>.EQ(e => e.Id, id); var entity = collection.FindOne(query); Console.WriteLine("数据查询结果为: {0}", entity); entity.Name = "TEST_UPDATE"; collection.Save(entity); Console.WriteLine("尝试对数据进行更新并保存,更新后结果: {0}", entity); Console.WriteLine("请到命令行方式下执行 db.TestBasic.find() 核对数据!"); Console.WriteLine("按回车键继续测试处理..."); Console.ReadLine(); var update = Update<TestBasic>.Set(e => e.Name, "TEST_UPDATE"); collection.Update(query, update); collection.Remove(query); Console.WriteLine("完成测试数据删除的处理..."); Console.WriteLine("请到命令行方式下执行 db.TestBasic.find() 核对数据!"); Console.WriteLine("按回车键结束测试..."); Console.ReadLine(); }
private IEnumerable<MongoUrl> EnumerateBuiltAndParsedUrls( MongoUrlBuilder built, string formatString, string[] values1, string[] values2) { yield return built.ToMongoUrl(); foreach (var parsed in EnumerateParsedUrls(formatString, values1, values2)) { yield return parsed; } }
public void TestFromUrl() { // set everything to non default values to test that all settings are converted var connectionString = "mongodb://*****:*****@somehost/?authSource=db;" + "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" + "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" + "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;secondaryAcceptableLatency=128;socketTimeout=129;" + "ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" + "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other"; var builder = new MongoUrlBuilder(connectionString); var url = builder.ToMongoUrl(); var settings = MongoClientSettings.FromUrl(url); Assert.AreEqual(url.ConnectionMode, settings.ConnectionMode); Assert.AreEqual(url.ConnectTimeout, settings.ConnectTimeout); Assert.AreEqual(1, settings.Credentials.Count()); Assert.AreEqual(url.Username, settings.Credentials.Single().Username); Assert.AreEqual(url.AuthenticationMechanism, settings.Credentials.Single().Mechanism); Assert.AreEqual(url.AuthenticationSource, settings.Credentials.Single().Source); Assert.AreEqual(new PasswordEvidence(url.Password), settings.Credentials.Single().Evidence); Assert.AreEqual(url.GssapiServiceName, settings.Credentials.Single().GetMechanismProperty<string>("SERVICE_NAME", null)); Assert.AreEqual(url.GuidRepresentation, settings.GuidRepresentation); Assert.AreEqual(url.IPv6, settings.IPv6); Assert.AreEqual(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime); Assert.AreEqual(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime); Assert.AreEqual(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize); Assert.AreEqual(url.MinConnectionPoolSize, settings.MinConnectionPoolSize); Assert.AreEqual(url.ReadPreference, settings.ReadPreference); Assert.AreEqual(url.ReplicaSetName, settings.ReplicaSetName); Assert.AreEqual(url.SecondaryAcceptableLatency, settings.SecondaryAcceptableLatency); Assert.IsTrue(url.Servers.SequenceEqual(settings.Servers)); Assert.AreEqual(url.SocketTimeout, settings.SocketTimeout); Assert.AreEqual(null, settings.SslSettings); Assert.AreEqual(url.UseSsl, settings.UseSsl); Assert.AreEqual(url.VerifySslCertificate, settings.VerifySslCertificate); Assert.AreEqual(url.ComputedWaitQueueSize, settings.WaitQueueSize); Assert.AreEqual(url.WaitQueueTimeout, settings.WaitQueueTimeout); Assert.AreEqual(url.GetWriteConcern(true), settings.WriteConcern); }
private void InitiateDatabase() { var connectionString = ConfigurationManager.ConnectionStrings["Mongo.ConnectionString"].ConnectionString; var mongoUrlBuilder = new MongoUrlBuilder(connectionString); mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl()); var TaskCatDBName = ConfigurationManager.AppSettings["TaskCat.DbName"]; Database = mongoClient.GetDatabase(string.IsNullOrWhiteSpace(TaskCatDBName) ? DatabaseNames.TASKCAT_DB : TaskCatDBName); var shadowCatConnectionString = ConfigurationManager.ConnectionStrings["ShadowCat.ConnectionString"].ConnectionString; if (string.Equals(connectionString, shadowCatConnectionString)) ShadowCatDatabase = Database; else { var shadowCatUrlBuilder = new MongoUrlBuilder(shadowCatConnectionString); shadowCatMongoClient = new MongoClient(shadowCatUrlBuilder.ToMongoUrl()); if (shadowCatUrlBuilder.DatabaseName == "admin" || string.IsNullOrWhiteSpace(shadowCatUrlBuilder.DatabaseName)) //Load default shadowcat database name ShadowCatDatabase = shadowCatMongoClient.GetDatabase(DatabaseNames.SHADOWCAT_DEFAULT_DB); else ShadowCatDatabase = shadowCatMongoClient.GetDatabase(shadowCatUrlBuilder.DatabaseName); } }
public void TestFromUrl() { // set everything to non default values to test that all settings are converted var connectionString = "mongodb://*****:*****@somehost/?authSource=db;" + "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" + "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" + "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;secondaryAcceptableLatency=128;socketTimeout=129;" + "ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" + "w=1;fsync=true;journal=true;w=2;wtimeout=131"; var builder = new MongoUrlBuilder(connectionString); var url = builder.ToMongoUrl(); var settings = MongoServerSettings.FromUrl(url); Assert.AreEqual(url.ConnectionMode, settings.ConnectionMode); Assert.AreEqual(url.ConnectTimeout, settings.ConnectTimeout); Assert.AreEqual(1, settings.CredentialsStore.Count); Assert.AreEqual(url.Username, settings.CredentialsStore.Single().Username); Assert.AreEqual(url.AuthenticationProtocol, settings.CredentialsStore.Single().AuthenticationProtocol); Assert.AreEqual(url.AuthenticationSource, settings.CredentialsStore.Single().Source); Assert.AreEqual(url.Password, ((PasswordEvidence)settings.CredentialsStore.Single().Evidence).Password); Assert.AreEqual(url.GuidRepresentation, settings.GuidRepresentation); Assert.AreEqual(url.IPv6, settings.IPv6); Assert.AreEqual(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime); Assert.AreEqual(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime); Assert.AreEqual(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize); Assert.AreEqual(url.MinConnectionPoolSize, settings.MinConnectionPoolSize); Assert.AreEqual(url.ReadPreference, settings.ReadPreference); Assert.AreEqual(url.ReplicaSetName, settings.ReplicaSetName); Assert.AreEqual(url.SecondaryAcceptableLatency, settings.SecondaryAcceptableLatency); Assert.IsTrue(url.Servers.SequenceEqual(settings.Servers)); Assert.AreEqual(url.SocketTimeout, settings.SocketTimeout); Assert.AreEqual(url.UseSsl, settings.UseSsl); Assert.AreEqual(url.VerifySslCertificate, settings.VerifySslCertificate); Assert.AreEqual(url.ComputedWaitQueueSize, settings.WaitQueueSize); Assert.AreEqual(url.WaitQueueTimeout, settings.WaitQueueTimeout); #pragma warning disable 618 Assert.AreEqual(url.GetWriteConcern(MongoDefaults.SafeMode.Enabled), settings.WriteConcern); #pragma warning restore }
// private methods private IEnumerable<MongoUrl> EnumerateBuiltAndParsedUrls( MongoUrlBuilder built, string connectionString) { yield return built.ToMongoUrl(); yield return new MongoUrl(connectionString); }
//========================================================================= // // 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); } }
private void InitializeDatabase() { lock (lockObject) { var urlBuilder = new MongoUrlBuilder(ConnectionString); var client = new MongoClient(urlBuilder.ToMongoUrl()); this.database = client.GetServer().GetDatabase(urlBuilder.DatabaseName); } }
public MongoUrl ToMongoUrl() { var builder = new MongoUrlBuilder { Servers = Servers, DatabaseName = DatabaseName, Credentials = MongoCredentials.Create(Username, Password), ConnectionMode = ConnectionMode, ReplicaSetName = ReplicaSetName, SafeMode = SafeMode, SlaveOk = SlaveOk }; return builder.ToMongoUrl(); }