Represents .NET style connection strings. We recommend you use URL style connection strings (see MongoUrl and MongoUrlBuilder).
Inheritance: System.Data.Common.DbConnectionStringBuilder
 public void TestDefaults() {
     string connectionString = "server=localhost";
     var builder = new MongoConnectionStringBuilder(connectionString);
     Assert.IsNull(builder.Username);
     Assert.IsNull(builder.Password);
     Assert.AreEqual(1, builder.Servers.Count());
     Assert.AreEqual("localhost", builder.Servers.Single().Host);
     Assert.AreEqual(27017, builder.Servers.Single().Port);
     Assert.IsNull(builder.DatabaseName);
     Assert.AreEqual(ConnectionMode.Direct, builder.ConnectionMode);
     Assert.AreEqual(MongoDefaults.ConnectTimeout, builder.ConnectTimeout);
     Assert.AreEqual(MongoDefaults.GuidRepresentation, builder.GuidRepresentation);
     Assert.AreEqual(false, builder.IPv6);
     Assert.AreEqual(MongoDefaults.MaxConnectionIdleTime, builder.MaxConnectionIdleTime);
     Assert.AreEqual(MongoDefaults.MaxConnectionLifeTime, builder.MaxConnectionLifeTime);
     Assert.AreEqual(MongoDefaults.MaxConnectionPoolSize, builder.MaxConnectionPoolSize);
     Assert.AreEqual(null, builder.ReplicaSetName);
     Assert.IsNull(builder.SafeMode);
     Assert.AreEqual(false, builder.SlaveOk);
     Assert.AreEqual(MongoDefaults.SocketTimeout, builder.SocketTimeout);
     Assert.AreEqual(MongoDefaults.WaitQueueMultiple, builder.WaitQueueMultiple);
     Assert.AreEqual(MongoDefaults.WaitQueueSize, builder.WaitQueueSize);
     Assert.AreEqual(MongoDefaults.WaitQueueTimeout, builder.WaitQueueTimeout);
     Assert.AreEqual(connectionString, builder.ToString());
 }
        public void TestConnectTimeout()
        {
            string connectionString = "server=localhost;connectTimeout=123";
            var builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(TimeSpan.FromSeconds(123), builder.ConnectTimeout);
            Assert.AreEqual(connectionString + "s", builder.ToString()); // "s" units added

            connectionString = "server=localhost;connectTimeout=123ms";
            builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(TimeSpan.FromMilliseconds(123), builder.ConnectTimeout);
            Assert.AreEqual(connectionString, builder.ToString());

            connectionString = "server=localhost;connectTimeout=123s";
            builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(TimeSpan.FromSeconds(123), builder.ConnectTimeout);
            Assert.AreEqual(connectionString, builder.ToString());

            connectionString = "server=localhost;connectTimeout=123m";
            builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(TimeSpan.FromMinutes(123), builder.ConnectTimeout);
            Assert.AreEqual(connectionString, builder.ToString());

            connectionString = "server=localhost;connectTimeout=123h";
            builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(TimeSpan.FromHours(123), builder.ConnectTimeout);
            Assert.AreEqual(connectionString, builder.ToString());
        }
        public void TestDefaults()
        {
            var builder = new MongoConnectionStringBuilder();
            Assert.AreEqual(null, builder.Username);
            Assert.AreEqual(null, builder.Password);
            Assert.AreEqual(null, builder.Server);
            Assert.AreEqual(null, builder.Servers);
            Assert.AreEqual(null, builder.DatabaseName);
            Assert.AreEqual(ConnectionMode.Automatic, builder.ConnectionMode);
            Assert.AreEqual(MongoDefaults.ConnectTimeout, builder.ConnectTimeout);
            Assert.AreEqual(MongoDefaults.GuidRepresentation, builder.GuidRepresentation);
            Assert.AreEqual(false, builder.IPv6);
            Assert.AreEqual(MongoDefaults.MaxConnectionIdleTime, builder.MaxConnectionIdleTime);
            Assert.AreEqual(MongoDefaults.MaxConnectionLifeTime, builder.MaxConnectionLifeTime);
            Assert.AreEqual(MongoDefaults.MaxConnectionPoolSize, builder.MaxConnectionPoolSize);
            Assert.AreEqual(MongoDefaults.MinConnectionPoolSize, builder.MinConnectionPoolSize);
            Assert.AreEqual(null, builder.ReadPreference);
            Assert.AreEqual(null, builder.ReplicaSetName);
            Assert.AreEqual(null, builder.SafeMode);
            Assert.AreEqual(MongoDefaults.SecondaryAcceptableLatency, builder.SecondaryAcceptableLatency);
#pragma warning disable 618
            Assert.AreEqual(false, builder.SlaveOk);
#pragma warning restore
            Assert.AreEqual(MongoDefaults.SocketTimeout, builder.SocketTimeout);
            Assert.AreEqual(false, builder.UseSsl);
            Assert.AreEqual(MongoDefaults.WaitQueueMultiple, builder.WaitQueueMultiple);
            Assert.AreEqual(MongoDefaults.WaitQueueSize, builder.WaitQueueSize);
            Assert.AreEqual(MongoDefaults.WaitQueueTimeout, builder.WaitQueueTimeout);
            Assert.AreEqual(MongoDefaults.ComputedWaitQueueSize, builder.ComputedWaitQueueSize);

            var connectionString = ""; // not actually a valid connection string because it's missing the host
            Assert.AreEqual(connectionString, builder.ToString());
        }
        /// <summary>
        /// Gets a MongoServerSettings object intialized with values from a MongoConnectionStringBuilder.
        /// </summary>
        /// <param name="builder">The MongoConnectionStringBuilder.</param>
        /// <returns>A MongoServerSettings.</returns>
        public static MongoServerSettings FromConnectionStringBuilder(MongoConnectionStringBuilder builder)
        {
            MongoCredentials defaultCredentials = null;

            if (builder.Username != null && builder.Password != null)
            {
                defaultCredentials = new MongoCredentials(builder.Username, builder.Password);
            }

            var serverSettings = new MongoServerSettings();

            serverSettings.ConnectionMode     = builder.ConnectionMode;
            serverSettings.ConnectTimeout     = builder.ConnectTimeout;
            serverSettings.CredentialsStore   = new MongoCredentialsStore();
            serverSettings.DefaultCredentials = defaultCredentials;
            serverSettings.GuidRepresentation = builder.GuidRepresentation;
            serverSettings.IPv6 = builder.IPv6;
            serverSettings.MaxConnectionIdleTime      = builder.MaxConnectionIdleTime;
            serverSettings.MaxConnectionLifeTime      = builder.MaxConnectionLifeTime;
            serverSettings.MaxConnectionPoolSize      = builder.MaxConnectionPoolSize;
            serverSettings.MinConnectionPoolSize      = builder.MinConnectionPoolSize;
            serverSettings.ReadPreference             = (builder.ReadPreference == null) ? ReadPreference.Primary : builder.ReadPreference.Clone();
            serverSettings.ReplicaSetName             = builder.ReplicaSetName;
            serverSettings.SecondaryAcceptableLatency = builder.SecondaryAcceptableLatency;
            serverSettings.Servers              = new List <MongoServerAddress>(builder.Servers);
            serverSettings.SocketTimeout        = builder.SocketTimeout;
            serverSettings.UseSsl               = builder.UseSsl;
            serverSettings.VerifySslCertificate = builder.VerifySslCertificate;
            serverSettings.WaitQueueSize        = builder.ComputedWaitQueueSize;
            serverSettings.WaitQueueTimeout     = builder.WaitQueueTimeout;
#pragma warning disable 618
            serverSettings.WriteConcern = builder.GetWriteConcern(MongoDefaults.SafeMode.Enabled);
#pragma warning restore
            return(serverSettings);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            MongoConnectionStringBuilder builder = new MongoConnectionStringBuilder();
            builder.Server = new MongoServerAddress("localhost", 27017);
            builder.DatabaseName = "douban";

            MongoServer mongo = MongoServer.Create(builder);
            mongo.Connect();
            var db = mongo.GetDatabase("douban");

            SqlConnectionStringBuilder sqlconnbuilder = new SqlConnectionStringBuilder();
            sqlconnbuilder.DataSource = "localhost\\s2012";
            sqlconnbuilder.InitialCatalog = "douban";
            sqlconnbuilder.IntegratedSecurity = true;

            SqlConnection sql = new SqlConnection(sqlconnbuilder.ToString());
            sql.Open();

            var cmd = sql.CreateCommand();

            InsertGroup(mongo, db, cmd);

            //InsertGroupPost(mongo, db, cmd);



        }
Ejemplo n.º 6
0
        // factory methods
        /// <summary>
        /// Creates a new instance or returns an existing instance of MongoDatabase. Only one instance
        /// is created for each combination of database settings. Automatically creates an instance
        /// of MongoServer if needed.
        /// </summary>
        /// <param name="builder">Server and database settings in the form of a MongoConnectionStringBuilder.</param>
        /// <returns>
        /// A new or existing instance of MongoDatabase.
        /// </returns>
        public static MongoDatabase Create(MongoConnectionStringBuilder builder)
        {
            var serverSettings = builder.ToServerSettings();
            var databaseName   = builder.DatabaseName;

            return(Create(serverSettings, databaseName));
        }
Ejemplo n.º 7
0
 private void btConnect_Click(object sender, EventArgs e)
 {
     if(!ServerConnection.Connected)
     {
         try
         {
             var connectionString = new MongoConnectionStringBuilder();
             connectionString.Server = new MongoServerAddress(tbServerAddress.Text);
             connectionString.Username = tbUser.Text;
             connectionString.Password = tbPassword.Text;
             connectionString.DatabaseName = "test";
             //new ServerConnection(tbServerAddress.Text);
             new ServerConnection(connectionString);
             //FillComboboxWithDatabaseNames(ServerConnection.Server);
             SetConnectedState();
         }
         catch(Exception ex)
         {
             MessageBox.Show(ex.Message);
             tbServerAddress.Focus();
         }
     }
     else
     {
         //ServerConnection.DatabaseName = cbDatabases.Text;
         ServerConnection.DatabaseName = "test";
         CloseLoginFormOpenMain();
     }
 }
Ejemplo n.º 8
0
 public MongoBind(string host, int port, string database, string collection)
 {
     var builder = new MongoConnectionStringBuilder {Server = new MongoServerAddress(host, port)};
     Client = new MongoClient(builder.ConnectionString);
     Database = Client.GetServer().GetDatabase(database);
     Collection = Database.GetCollection(collection);
 }
        public void TestToStringOutput()
        {
            var builder = new MongoConnectionStringBuilder { Password = "******", Username = "******", ConnectionLifetime = TimeSpan.FromSeconds (50), MaximumPoolSize = 101, MinimumPoolSize = 202, ConnectionTimeout = TimeSpan.FromSeconds(60)};
            builder.AddServer ("testserver1", 555);
            builder.AddServer ("testserver2");

            Assert.AreEqual ("Username=testusername;Password=testpassword;Server=testserver1:555,testserver2;MaximumPoolSize=101;MinimumPoolSize=202;ConnectionTimeout=60;ConnectionLifetime=50", builder.ToString ());
        }
 public static CountersDatabase Connect(string host, int? port, string dbName)
 {
     MongoConnectionStringBuilder builder = new MongoConnectionStringBuilder();
     builder.SocketTimeout = new TimeSpan(0, 30, 0);
     builder.Server = port.HasValue ? new MongoServerAddress(host, port.Value) : new MongoServerAddress(host);
     MongoServer server = MongoServer.Create(builder);
     server.Connect();
     MongoDatabase db = server.GetDatabase(dbName);
     return new CountersDatabase(server, db);
 }
        public void TestConnectionStringParsingServerWithoutPort()
        {
            var builder = new MongoConnectionStringBuilder ("Username=testuser;Password=testpassword;Server=testserver");
            Assert.AreEqual ("testuser", builder.Username);
            Assert.AreEqual ("testpassword", builder.Password);

            var servers = new List<MongoServerEndPoint> (builder.Servers);
            Assert.AreEqual (1, servers.Count);
            Assert.AreEqual ("testserver", servers[0].Host);
            Assert.AreEqual (MongoServerEndPoint.DefaultPort, servers[0].Port);
        }
 public void TestHostWithPort() {
     string connectionString = "server=mongo.xyz.com:12345";
     var builder = new MongoConnectionStringBuilder(connectionString);
     Assert.IsNull(builder.Username);
     Assert.IsNull(builder.Password);
     Assert.AreEqual(1, builder.Servers.Count());
     Assert.AreEqual("mongo.xyz.com", builder.Servers.Single().Host);
     Assert.AreEqual(12345, builder.Servers.Single().Port);
     Assert.AreEqual(ConnectionMode.Direct, builder.ConnectionMode);
     Assert.AreEqual(null, builder.ReplicaSetName);
     Assert.AreEqual(connectionString, builder.ToString());
 }
        public void TestConnectionMode()
        {
            string connectionString = "server=localhost;connect=direct";
            var builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(ConnectionMode.Direct, builder.ConnectionMode);
            Assert.AreEqual(connectionString, builder.ToString());

            connectionString = "server=localhost;connect=replicaSet";
            builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual(ConnectionMode.ReplicaSet, builder.ConnectionMode);
            Assert.AreEqual(connectionString, builder.ToString());
        }
Ejemplo n.º 14
0
 public MyContext(string connString)
 {
     /*
     var con = new MongoConnectionStringBuilder(connString);
     var server = MongoServer.Create(con);
     DB = server.GetDatabase(con.DatabaseName);
     */
     var con = new MongoConnectionStringBuilder(connString);
     var client = new MongoClient(connString);
     var server = client.GetServer();
     DB = server.GetDatabase(con.DatabaseName);
 }
Ejemplo n.º 15
0
 static MongoHelper()
 {
     if (Configuration.ConnectionString.StartsWith("mongodb://"))
     {
         IsConnectionUrl = true;
         ConnectionUrl = new MongoUrlBuilder(Configuration.ConnectionString);
     }
     else
     {
         ConnectionString = new MongoConnectionStringBuilder(Configuration.ConnectionString);
     }
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Creates a new instance or returns an existing instance of MongoDatabase. Only one instance
 /// is created for each combination of database settings. Automatically creates an instance
 /// of MongoServer if needed.
 /// </summary>
 /// <param name="connectionString">Server and database settings in the form of a connection string.</param>
 /// <returns>
 /// A new or existing instance of MongoDatabase.
 /// </returns>
 public static MongoDatabase Create(string connectionString)
 {
     if (connectionString.StartsWith("mongodb://"))
     {
         MongoUrl url = MongoUrl.Create(connectionString);
         return(Create(url));
     }
     else
     {
         MongoConnectionStringBuilder builder = new MongoConnectionStringBuilder(connectionString);
         return(Create(builder));
     }
 }
Ejemplo n.º 17
0
 public static MongoServer Create(string connectionString)
 {
     if (connectionString.StartsWith("mongodb://", StringComparison.Ordinal))
     {
         var url = MongoUrl.Create(connectionString);
         return(Create(url));
     }
     else
     {
         var builder = new MongoConnectionStringBuilder(connectionString);
         return(Create(builder));
     }
 }
Ejemplo n.º 18
0
 // private static methods
 private static MongoClientSettings ParseConnectionString(string connectionString)
 {
     if (connectionString.StartsWith("mongodb://"))
     {
         var url = new MongoUrl(connectionString);
         return MongoClientSettings.FromUrl(url);
     }
     else
     {
         var builder = new MongoConnectionStringBuilder(connectionString);
         return MongoClientSettings.FromConnectionStringBuilder(builder);
     }
 }
Ejemplo n.º 19
0
 // private static methods
 private static MongoClientSettings ParseConnectionString(string connectionString)
 {
     if (connectionString.StartsWith("mongodb://"))
     {
         var url = new MongoUrl(connectionString);
         return(MongoClientSettings.FromUrl(url));
     }
     else
     {
         var builder = new MongoConnectionStringBuilder(connectionString);
         return(MongoClientSettings.FromConnectionStringBuilder(builder));
     }
 }
        public void TestOneIPv6AddressWithPort()
        {
            var connectionString = "mongodb://[::1:]:1234/?w=1";
            var url = new MongoUrl(connectionString);
            Assert.AreEqual("[::1:]", url.Server.Host);
            Assert.AreEqual(1234, url.Server.Port);
            Assert.AreEqual(true, url.SafeMode.Enabled);

            connectionString = "server=[::1:]:1234;w=1";
            var builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual("[::1:]", builder.Server.Host);
            Assert.AreEqual(1234, builder.Server.Port);
            Assert.AreEqual(true, builder.SafeMode.Enabled);
        }
   public void CREATE_CLIENT()
   {
 
       MongoConnectionStringBuilder builder = new MongoConnectionStringBuilder();
       builder.Journal = true;
       builder.Server = new MongoServerAddress("localhost");
       string connectionString = builder.ToString();
      
       client = new MongoClient(connectionString);
       
       //client.GetServer().GetDatabase("EventStore").Drop();
       BsonClassMap.RegisterClassMap<Events.SampleEvent>();
       BsonClassMap.RegisterClassMap<Events.SampleID>();
   }
 public void TestTwoHosts() {
     string connectionString = "server=mongo1.xyz.com,mongo2.xyz.com";
     var builder = new MongoConnectionStringBuilder(connectionString);
     Assert.IsNull(builder.Username);
     Assert.IsNull(builder.Password);
     Assert.AreEqual(2, builder.Servers.Count());
     Assert.AreEqual("mongo1.xyz.com", builder.Servers.First().Host);
     Assert.AreEqual(27017, builder.Servers.First().Port);
     Assert.AreEqual("mongo2.xyz.com", builder.Servers.Skip(1).Single().Host);
     Assert.AreEqual(27017, builder.Servers.Skip(1).Single().Port);
     Assert.AreEqual(ConnectionMode.ReplicaSet, builder.ConnectionMode);
     Assert.AreEqual(null, builder.ReplicaSetName);
     Assert.AreEqual(connectionString, builder.ToString());
 }
Ejemplo n.º 23
0
        public void TestOneIPv6Address()
        {
            var connectionString = "mongodb://[::1:]/?safe=true";
            var url = new MongoUrl(connectionString);
            Assert.AreEqual("[::1:]", url.Server.Host);
            Assert.AreEqual(27017, url.Server.Port);
            Assert.AreEqual(true, url.SafeMode.Enabled);

            connectionString = "server=[::1:];safe=true";
            var builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual("[::1:]", builder.Server.Host);
            Assert.AreEqual(27017, builder.Server.Port);
            Assert.AreEqual(true, builder.SafeMode.Enabled);
        }
        public void TestConnectionStringParsing()
        {
            var builder = new MongoConnectionStringBuilder ("Username=testuser;Password=testpassword;Server=testserver:555;ConnectionLifetime=50;MaximumPoolSize=101;MinimumPoolSize=202;Pooled=false");
            Assert.AreEqual ("testuser", builder.Username);
            Assert.AreEqual ("testpassword", builder.Password);
            Assert.AreEqual (101, builder.MaximumPoolSize);
            Assert.AreEqual (202, builder.MinimumPoolSize);
            Assert.AreEqual (TimeSpan.FromSeconds (50), builder.ConnectionLifetime);
            Assert.AreEqual (false, builder.Pooled);

            var servers = new List<MongoServerEndPoint>(builder.Servers);
            Assert.AreEqual (1, servers.Count);
            Assert.AreEqual ("testserver", servers[0].Host);
            Assert.AreEqual (555, servers[0].Port);
        }
        public void TestHostWithPort()
        {
            var builder = new MongoConnectionStringBuilder() { Server = new MongoServerAddress("mongo.xyz.com", 12345) };
            Assert.IsNull(builder.Username);
            Assert.IsNull(builder.Password);
            Assert.AreEqual(1, builder.Servers.Count());
            Assert.AreEqual("mongo.xyz.com", builder.Server.Host);
            Assert.AreEqual(12345, builder.Server.Port);
            Assert.AreEqual(null, builder.DatabaseName);
            Assert.AreEqual(ConnectionMode.Automatic, builder.ConnectionMode);

            var connectionString = "server=mongo.xyz.com:12345";
            Assert.AreEqual(connectionString, builder.ToString());
            Assert.AreEqual(connectionString, new MongoConnectionStringBuilder(connectionString).ToString());
        }
        public void TestDefaults()
        {
            var builder = new MongoConnectionStringBuilder ();
            Assert.IsNull (builder.Username);
            Assert.IsNull (builder.Password);
            Assert.AreEqual (builder.MaximumPoolSize, MongoConnectionStringBuilder.DefaultMaximumPoolSize);
            Assert.AreEqual (builder.MinimumPoolSize, MongoConnectionStringBuilder.DefaultMinimumPoolSize);
            Assert.AreEqual (builder.ConnectionLifetime, MongoConnectionStringBuilder.DefaultConnectionLifeTime);
            Assert.AreEqual (builder.ConnectionTimeout, MongoConnectionStringBuilder.DefaultConnectionTimeout);
            Assert.AreEqual (builder.Pooled, MongoConnectionStringBuilder.DefaultPooled);

            var servers = new List<MongoServerEndPoint> (builder.Servers);
            Assert.AreEqual (1, servers.Count);
            Assert.AreEqual (MongoServerEndPoint.DefaultPort, servers[0].Port);
            Assert.AreEqual (MongoServerEndPoint.DefaultHost, servers[0].Host);
        }
 public void TestAll()
 {
     string connectionString = "server=localhost;connect=replicaSet;replicaSet=name;slaveOk=true;safe=true;fsync=true;j=true;w=2;wtimeout=2s;guids=PythonLegacy";
     var builder = new MongoConnectionStringBuilder(connectionString);
     Assert.IsNull(builder.Username);
     Assert.IsNull(builder.Password);
     Assert.AreEqual(1, builder.Servers.Count());
     Assert.AreEqual("localhost", builder.Server.Host);
     Assert.AreEqual(27017, builder.Server.Port);
     Assert.AreEqual(null, builder.DatabaseName);
     Assert.AreEqual(ConnectionMode.ReplicaSet, builder.ConnectionMode);
     Assert.AreEqual("name", builder.ReplicaSetName);
     Assert.AreEqual(GuidRepresentation.PythonLegacy, builder.GuidRepresentation);
     Assert.AreEqual(new SafeMode(true) { FSync = true, J = true, W = 2, WTimeout = TimeSpan.FromSeconds(2) }, builder.SafeMode);
     Assert.AreEqual(true, builder.SlaveOk);
     Assert.AreEqual(connectionString, builder.ToString());
 }
Ejemplo n.º 28
0
		internal static MongoServer GetMongoServer()
		{
			var serverAddress = (ServerPort != 0)
				? new MongoServerAddress(ServerHost, ServerPort)
				: new MongoServerAddress(ServerHost);
			var connectionStringBuilder = new MongoConnectionStringBuilder
			{
				Server = serverAddress,
				ConnectTimeout = ConnectTimeout,
				SocketTimeout = SocketTimeout,
				WaitQueueTimeout = WaitQueueTimeout,
				SafeMode = (SafeMode)
					? MongoDB.Driver.SafeMode.True
					: MongoDB.Driver.SafeMode.False
			};
			return MongoServer
				.Create(connectionStringBuilder.ToServerSettings());
		}
Ejemplo n.º 29
0
        public void TestOneIPv6AddressWithDefaultCredentials()
        {
            var connectionString = "mongodb://*****:*****@[::1:]/?safe=true";
            var url = new MongoUrl(connectionString);
            Assert.AreEqual("[::1:]", url.Server.Host);
            Assert.AreEqual(27017, url.Server.Port);
            Assert.AreEqual("username", url.DefaultCredentials.Username);
            Assert.AreEqual("password", url.DefaultCredentials.Password);
            Assert.AreEqual(true, url.SafeMode.Enabled);

            connectionString = "server=[::1:];username=username;password=password;safe=true";
            var builder = new MongoConnectionStringBuilder(connectionString);
            Assert.AreEqual("[::1:]", builder.Server.Host);
            Assert.AreEqual(27017, builder.Server.Port);
            Assert.AreEqual("username", builder.Username);
            Assert.AreEqual("password", builder.Password);
            Assert.AreEqual(true, builder.SafeMode.Enabled);
        }
        /// <summary>
        /// Gets a MongoServerSettings object intialized with values from a MongoConnectionStringBuilder.
        /// </summary>
        /// <param name="builder">The MongoConnectionStringBuilder.</param>
        /// <returns>A MongoServerSettings.</returns>
        public static MongoServerSettings FromConnectionStringBuilder(MongoConnectionStringBuilder builder)
        {
            var credential = MongoCredential.FromComponents(
                builder.AuthenticationMechanism,
                builder.AuthenticationSource ?? builder.DatabaseName,
                builder.Username,
                builder.Password);

            var serverSettings = new MongoServerSettings();

            serverSettings.ConnectionMode = builder.ConnectionMode;
            serverSettings.ConnectTimeout = builder.ConnectTimeout;
            if (credential != null)
            {
                if (!string.IsNullOrEmpty(builder.GssapiServiceName))
                {
                    credential = credential.WithMechanismProperty("SERVICE_NAME", builder.GssapiServiceName);
                }
                serverSettings.Credentials = new[] { credential };
            }
            serverSettings.GuidRepresentation = builder.GuidRepresentation;
            serverSettings.IPv6 = builder.IPv6;
            serverSettings.MaxConnectionIdleTime      = builder.MaxConnectionIdleTime;
            serverSettings.MaxConnectionLifeTime      = builder.MaxConnectionLifeTime;
            serverSettings.MaxConnectionPoolSize      = builder.MaxConnectionPoolSize;
            serverSettings.MinConnectionPoolSize      = builder.MinConnectionPoolSize;
            serverSettings.ReadEncoding               = null; // ReadEncoding must be provided in code
            serverSettings.ReadPreference             = (builder.ReadPreference == null) ? ReadPreference.Primary : builder.ReadPreference.Clone();
            serverSettings.ReplicaSetName             = builder.ReplicaSetName;
            serverSettings.SecondaryAcceptableLatency = builder.SecondaryAcceptableLatency;
            serverSettings.Servers              = new List <MongoServerAddress>(builder.Servers);
            serverSettings.SocketTimeout        = builder.SocketTimeout;
            serverSettings.SslSettings          = null; // SSL settings must be provided in code
            serverSettings.UseSsl               = builder.UseSsl;
            serverSettings.VerifySslCertificate = builder.VerifySslCertificate;
            serverSettings.WaitQueueSize        = builder.ComputedWaitQueueSize;
            serverSettings.WaitQueueTimeout     = builder.WaitQueueTimeout;
#pragma warning disable 618
            serverSettings.WriteConcern = builder.GetWriteConcern(MongoDefaults.SafeMode.Enabled);
#pragma warning restore
            serverSettings.WriteEncoding = null; // WriteEncoding must be provided in code
            return(serverSettings);
        }
Ejemplo n.º 31
0
 public static MongoDatabase Connect()
 {
     try
     {
         var connectionString = new MongoConnectionStringBuilder
         {
             DatabaseName = "admin",
             Password = Password,
             Username = Username,
             Server = new MongoServerAddress(Server, Port)
         };
         var server = MongoServer.Create(connectionString);
         return server.GetDatabase(Database);
     }
     catch (Exception ex)
     {
         Logger.WriteErrorLog(ex);
         return null;
     }
 }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public MongoDatabaseProvider CreateProvider(
      IDictionary<string, string> options) {
      string connection_string;
      string database = options.GetString(kDatabaseOption);
      if (!options.TryGetValue(kConnectionStringOption, out connection_string)) {
        var builder = new MongoConnectionStringBuilder();
        string user_name, password;
        options.TryGetValue(kUserNameOption, out user_name);
        options.TryGetValue(kPasswordOption, out password);

        user_name = options.GetString(kUserNameOption, null);
        if (user_name != null) {
          builder.Username = user_name;
          builder.Password = options.GetString(kPasswordOption);
          builder.DatabaseName = database;
        }

        var servers = new List<MongoServerAddress>();
        foreach (KeyValuePair<string, string> pair in options) {
          if (pair.Value.CompareOrdinal(kHostOption)) {
            string host = pair.Value;
            int index = host.IndexOf(":");
            if (index == -1) {
              servers.Add(new MongoServerAddress(host));
            }
            servers.Add(new MongoServerAddress(host.Substring(0, index)));
          }
        }

        if (servers.Count == 0) {
          throw new KeyNotFoundException(
            "At least one host should be specified.");
        }
        builder.Servers = servers;
        connection_string = builder.ToString();
      }
      var client = new MongoClient(connection_string);
      var server = client.GetServer();
      return new MongoDatabaseProvider(server, database);
    }
Ejemplo n.º 33
0
        /// <summary>
        /// MongoDB 서버에 접속하기 위한 <see cref="MongoConnectionStringBuilder"/>를 빌드 합니다.
        /// </summary>
        /// <param name="serverName">Mongo Server IP 또는 DNS 명</param>
        /// <param name="port">Port</param>
        /// <param name="databaseName">MongoDB의 database 명</param>
        /// <param name="username">사용자명</param>
        /// <param name="password">비밀번호</param>
        /// <returns><see cref="MongoConnectionStringBuilder"/> 인스턴스</returns>
        public static MongoConnectionStringBuilder GetMongoConnectionBuilder(string serverName, int? port, string databaseName,
                                                                             string username, string password) {
            serverName.ShouldNotBeWhiteSpace("serverName");

            var builder = new MongoConnectionStringBuilder
                          {
                              Server = port.HasValue
                                           ? new MongoServerAddress(serverName, port.Value)
                                           : new MongoServerAddress(serverName),
                              SafeMode = SafeMode.True,
                              DatabaseName = databaseName ?? DefaultDatabaseName
                          };


            if(username.IsNotWhiteSpace())
                builder.Username = username;

            if(password.IsNotWhiteSpace())
                builder.Password = password;

            return builder;
        }
        // public static methods
        /// <summary>
        /// Gets a MongoClientSettings object intialized with values from a connection string builder.
        /// </summary>
        /// <param name="builder">The connection string builder.</param>
        /// <returns>A MongoClientSettings.</returns>
        public static MongoClientSettings FromConnectionStringBuilder(MongoConnectionStringBuilder builder)
        {
            var credential = MongoCredential.FromComponents(
                builder.AuthenticationMechanism,
                builder.AuthenticationSource ?? builder.DatabaseName,
                builder.Username,
                builder.Password);

            var clientSettings = new MongoClientSettings();

            clientSettings.ConnectionMode = builder.ConnectionMode;
            clientSettings.ConnectTimeout = builder.ConnectTimeout;
            if (credential != null)
            {
                clientSettings.Credentials = new[] { credential };
            }
            clientSettings.GuidRepresentation = builder.GuidRepresentation;
            clientSettings.IPv6 = builder.IPv6;
            clientSettings.MaxConnectionIdleTime      = builder.MaxConnectionIdleTime;
            clientSettings.MaxConnectionLifeTime      = builder.MaxConnectionLifeTime;
            clientSettings.MaxConnectionPoolSize      = builder.MaxConnectionPoolSize;
            clientSettings.MinConnectionPoolSize      = builder.MinConnectionPoolSize;
            clientSettings.ReadEncoding               = null; // ReadEncoding must be provided in code
            clientSettings.ReadPreference             = (builder.ReadPreference == null) ? ReadPreference.Primary : builder.ReadPreference.Clone();
            clientSettings.ReplicaSetName             = builder.ReplicaSetName;
            clientSettings.SecondaryAcceptableLatency = builder.SecondaryAcceptableLatency;
            clientSettings.Servers              = new List <MongoServerAddress>(builder.Servers);
            clientSettings.SocketTimeout        = builder.SocketTimeout;
            clientSettings.SslSettings          = null; // SSL settings must be provided in code
            clientSettings.UseSsl               = builder.UseSsl;
            clientSettings.VerifySslCertificate = builder.VerifySslCertificate;
            clientSettings.WaitQueueSize        = builder.ComputedWaitQueueSize;
            clientSettings.WaitQueueTimeout     = builder.WaitQueueTimeout;
            clientSettings.WriteConcern         = builder.GetWriteConcern(true); // WriteConcern is enabled by default for MongoClient
            clientSettings.WriteEncoding        = null;                          // WriteEncoding must be provided in code
            return(clientSettings);
        }
        public void TestFromMongoConnectionStringBuilder()
        {
            // set everything to non default values to test that all settings are converted
            var connectionString =
                "server=somehost;username=user1;password=password1;" +
                "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2|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 MongoConnectionStringBuilder(connectionString);

            var settings = MongoClientSettings.FromConnectionStringBuilder(builder);
            Assert.AreEqual(builder.ConnectionMode, settings.ConnectionMode);
            Assert.AreEqual(builder.ConnectTimeout, settings.ConnectTimeout);
            Assert.AreEqual("{}", settings.CredentialsStore.ToString());
            Assert.AreEqual(new MongoCredentials("user1", "password1"), settings.DefaultCredentials);
            Assert.AreEqual(builder.GuidRepresentation, settings.GuidRepresentation);
            Assert.AreEqual(builder.IPv6, settings.IPv6);
            Assert.AreEqual(builder.MaxConnectionIdleTime, settings.MaxConnectionIdleTime);
            Assert.AreEqual(builder.MaxConnectionLifeTime, settings.MaxConnectionLifeTime);
            Assert.AreEqual(builder.MaxConnectionPoolSize, settings.MaxConnectionPoolSize);
            Assert.AreEqual(builder.MinConnectionPoolSize, settings.MinConnectionPoolSize);
            Assert.AreEqual(builder.ReadPreference, settings.ReadPreference);
            Assert.AreEqual(builder.ReplicaSetName, settings.ReplicaSetName);
            Assert.AreEqual(builder.SecondaryAcceptableLatency, settings.SecondaryAcceptableLatency);
            Assert.IsTrue(builder.Servers.SequenceEqual(settings.Servers));
            Assert.AreEqual(builder.SocketTimeout, settings.SocketTimeout);
            Assert.AreEqual(builder.UseSsl, settings.UseSsl);
            Assert.AreEqual(builder.VerifySslCertificate, settings.VerifySslCertificate);
            Assert.AreEqual(builder.ComputedWaitQueueSize, settings.WaitQueueSize);
            Assert.AreEqual(builder.WaitQueueTimeout, settings.WaitQueueTimeout);
            Assert.AreEqual(builder.GetWriteConcern(false), settings.WriteConcern);
        }
Ejemplo n.º 36
0
 public static MongoServer Create(MongoConnectionStringBuilder builder)
 {
     return(Create(MongoServerSettings.FromConnectionStringBuilder(builder)));
 }
        public void TestSlaveOk(bool? slaveOk, string formatString, string[] values)
        {
#pragma warning disable 618
            var built = new MongoConnectionStringBuilder { Server = _localhost };
            if (slaveOk != null) { built.SlaveOk = slaveOk.Value; }

            var canonicalConnectionString = string.Format(formatString, values[0]);
            foreach (var builder in EnumerateBuiltAndParsedBuilders(built, formatString, values))
            {
                Assert.AreEqual(slaveOk ?? false, builder.SlaveOk);
                Assert.AreEqual(canonicalConnectionString, builder.ToString());
            }
#pragma warning restore
        }
        public void TestServers(string[] hosts, object[] ports, string formatString, string[] serverAliases)
        {
            var servers = (hosts == null) ? null : new List<MongoServerAddress>();
            if (hosts != null)
            {
                Assert.AreEqual(hosts.Length, ports.Length);
                for (var i = 0; i < hosts.Length; i++)
                {
                    var server = (hosts[i] == null) ? null : (ports[i] == null) ? new MongoServerAddress(hosts[i]) : new MongoServerAddress(hosts[i], (int)ports[i]);
                    servers.Add(server);
                }
            }
            var built = new MongoConnectionStringBuilder { Servers = servers };

            var canonicalConnectionString = string.Format(formatString, "server");
            foreach (var builder in EnumerateBuiltAndParsedBuilders(built, formatString, serverAliases))
            {
                Assert.AreEqual(servers, builder.Servers);
                Assert.AreEqual(canonicalConnectionString, builder.ToString());
            }
        }