/// <summary>
        /// Configures the cluster to trace command events to the specified <paramref name="traceSource"/>.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="traceSource">The trace source.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder TraceCommandsWith(this ClusterBuilder builder, TraceSource traceSource)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(traceSource, nameof(traceSource));

            return(builder.Subscribe(new TraceSourceCommandEventSubscriber(traceSource)));
        }
        // static methods
        public static ClusterBuilder ConfigureCluster()
        {
            var builder = new ClusterBuilder()
                .ConfigureWithConnectionString(__connectionString)
                .ConfigureCluster(c => c.With(serverSelectionTimeout: TimeSpan.FromMilliseconds(500)));

            if (__connectionString.Ssl.HasValue && __connectionString.Ssl.Value)
            {
                var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");
                if (certificateFilename != null)
                {
                    builder.ConfigureSsl(ssl =>
                    {
                        var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");
                        X509Certificate cert;
                        if (password == null)
                        {
                            cert = new X509Certificate2(certificateFilename);
                        }
                        else
                        {
                            cert = new X509Certificate2(certificateFilename, password);
                        }
                        return ssl.With(
                            clientCertificates: new[] { cert });
                    });
                }
            }

            return builder;
        }
        // methods
        public static ClusterBuilder ConfigureCluster()
        {
            var builder = new ClusterBuilder().ConfigureWithConnectionString(__connectionString);

            if (__connectionString.Ssl.HasValue && __connectionString.Ssl.Value)
            {
                var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");
                if (certificateFilename != null)
                {
                    // TODO: configure SSL
                    //builder.ConfigureSsl(ssl =>
                    //{
                    //    var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");
                    //    X509Certificate cert;
                    //    if (password == null)
                    //    {
                    //        cert = new X509Certificate2(certificateFilename);
                    //    }
                    //    else
                    //    {
                    //        cert = new X509Certificate2(certificateFilename, password);
                    //    }
                    //    ssl.AddClientCertificate(cert);
                    //});
                }
            }

            return builder;
        }
        public void CreateServerMonitorFactory_should_return_expected_result(int connectTimeoutMilliseconds, int heartbeatTimeoutMilliseconds, int expectedServerMonitorConnectTimeoutMilliseconds, int expectedServerMonitorSocketTimeoutMilliseconds)
        {
            var connectTimeout   = TimeSpan.FromMilliseconds(connectTimeoutMilliseconds);
            var authenticators   = new[] { new DefaultAuthenticator(new UsernamePasswordCredential("source", "username", "password")) };
            var heartbeatTimeout = TimeSpan.FromMilliseconds(heartbeatTimeoutMilliseconds);
            var expectedServerMonitorConnectTimeout = TimeSpan.FromMilliseconds(expectedServerMonitorConnectTimeoutMilliseconds);
            var expectedServerMonitorSocketTimeout  = TimeSpan.FromMilliseconds(expectedServerMonitorSocketTimeoutMilliseconds);
            var subject = new ClusterBuilder()
                          .ConfigureTcp(s => s.With(connectTimeout: connectTimeout))
                          .ConfigureConnection(s => s.With(authenticators: authenticators))
                          .ConfigureServer(s => s.With(heartbeatTimeout: heartbeatTimeout));

            var result = (ServerMonitorFactory)subject.CreateServerMonitorFactory();

            var serverMonitorConnectionFactory  = (BinaryConnectionFactory)result._connectionFactory();
            var serverMonitorConnectionSettings = serverMonitorConnectionFactory._settings();

            serverMonitorConnectionSettings.Authenticators.Should().HaveCount(0);

            var serverMonitorStreamFactory     = (TcpStreamFactory)serverMonitorConnectionFactory._streamFactory();
            var serverMonitorTcpStreamSettings = serverMonitorStreamFactory._settings();

            serverMonitorTcpStreamSettings.ConnectTimeout.Should().Be(expectedServerMonitorConnectTimeout);
            serverMonitorTcpStreamSettings.ReadTimeout.Should().Be(expectedServerMonitorSocketTimeout);
            serverMonitorTcpStreamSettings.WriteTimeout.Should().Be(expectedServerMonitorSocketTimeout);

            var eventSuscriber = result._eventSubscriber();

            var serverSettings = result._settings();
        }
Exemple #5
0
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder configuration, string connectionString)
        {
            Ensure.IsNotNull(configuration, "configuration");
            Ensure.IsNotNullOrEmpty(connectionString, "connectionString");

            var parsedConnectionString = new ConnectionString(connectionString);

            return(ConfigureWithConnectionString(configuration, parsedConnectionString));
        }
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, string connectionString)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNullOrEmpty(connectionString, nameof(connectionString));

            var parsedConnectionString = new ConnectionString(connectionString);

            return(ConfigureWithConnectionString(builder, parsedConnectionString));
        }
Exemple #7
0
        /// <summary>
        /// Configures the cluster builder to use performance counters.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="applicationName">The name of the application.</param>
        /// <param name="install">if set to <c>true</c> install the performance counters first.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder UsePerformanceCounters(this ClusterBuilder builder, string applicationName, bool install = false)
        {
            Ensure.IsNotNull(builder, "builder");

            if (install)
            {
                PerformanceCounterListener.InstallPerformanceCounters();
            }

            return(builder.AddListener(new PerformanceCounterListener(applicationName)));
        }
Exemple #8
0
        public static ClusterBuilder UsePerformanceCounters(this ClusterBuilder configuration, string applicationName, bool install = false)
        {
            Ensure.IsNotNull(configuration, "configuration");

            if (install)
            {
                PerformanceCounterListener.Install();
            }

            return(configuration.AddListener(new PerformanceCounterListener(applicationName)));
        }
        public void StreamFactoryWrappers_should_be_called_in_the_correct_order()
        {
            var subject = new ClusterBuilder();
            var calls   = new List <int>();

            subject.RegisterStreamFactory(factory => { calls.Add(1); return(factory); });
            subject.RegisterStreamFactory(factory => { calls.Add(2); return(factory); });
            subject.RegisterStreamFactory(factory => { calls.Add(3); return(factory); });

            subject._streamFactoryWrapper()(Mock.Of <IStreamFactory>());

            calls.Should().Equal(1, 2, 3);
        }
        /// <summary>
        /// Configures the cluster to write performance counters.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="applicationName">The name of the application.</param>
        /// <param name="install">if set to <c>true</c> install the performance counters first.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder UsePerformanceCounters(this ClusterBuilder builder, string applicationName, bool install = false)
        {
            Ensure.IsNotNull(builder, nameof(builder));

            if (install)
            {
                PerformanceCounterEventSubscriber.InstallPerformanceCounters();
            }

            var subscriber = new PerformanceCounterEventSubscriber(applicationName);

            return(builder.Subscribe(subscriber));
        }
        public static ClusterBuilder ConfigureCluster(ClusterBuilder builder)
        {
            var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
            if (serverSelectionTimeoutString == null)
            {
                serverSelectionTimeoutString = "10000";
            }

            builder = builder
                .ConfigureWithConnectionString(__connectionString)
                .ConfigureCluster(c => c.With(serverSelectionTimeout: TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString))));

            if (__connectionString.Ssl.HasValue && __connectionString.Ssl.Value)
            {
                var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");
                if (certificateFilename != null)
                {
                    builder.ConfigureSsl(ssl =>
                    {
                        var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");
                        X509Certificate cert;
                        if (password == null)
                        {
                            cert = new X509Certificate2(certificateFilename);
                        }
                        else
                        {
                            cert = new X509Certificate2(certificateFilename, password);
                        }
                        return ssl.With(
                            clientCertificates: new[] { cert });
                    });
                }
            }

            var traceSource = new TraceSource("mongodb-tests", SourceLevels.Information);
            traceSource.Listeners.Clear(); // remove the default listener
            var listener = new ConsoleTraceListener();
            traceSource.Listeners.Add(listener);
            builder = builder.TraceWith(traceSource);

            return builder;
        }
Exemple #12
0
        public void Run(int numConcurrentWorkers, Action<ClusterBuilder> configurator)
        {
            try
            {
                var clusterBuilder = new ClusterBuilder();
                configurator(clusterBuilder);

                using (var cluster = clusterBuilder.BuildCluster())
                {
                    RunAsync(numConcurrentWorkers, cluster).GetAwaiter().GetResult();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled exception:");
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }
        public static ClusterBuilder ConfigureCluster(ClusterBuilder builder)
        {
            var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
            if (serverSelectionTimeoutString == null)
            {
                serverSelectionTimeoutString = "30000";
            }

            builder = builder
                .ConfigureWithConnectionString(__connectionString)
                .ConfigureCluster(c => c.With(serverSelectionTimeout: TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString))));

            if (__connectionString.Ssl.HasValue && __connectionString.Ssl.Value)
            {
                var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");
                if (certificateFilename != null)
                {
                    builder.ConfigureSsl(ssl =>
                    {
                        var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");
                        X509Certificate cert;
                        if (password == null)
                        {
                            cert = new X509Certificate2(certificateFilename);
                        }
                        else
                        {
                            cert = new X509Certificate2(certificateFilename, password);
                        }
                        return ssl.With(
                            clientCertificates: new[] { cert });
                    });
                }
            }

            return ConfigureLogging(builder);
        }
        // methods
        private ICluster CreateCluster(ClusterKey clusterKey)
        {
            var builder = new ClusterBuilder()
                .ConfigureCluster(settings => ConfigureCluster(settings, clusterKey))
                .ConfigureServer(settings => ConfigureServer(settings, clusterKey))
                .ConfigureConnectionPool(settings => ConfigureConnectionPool(settings, clusterKey))
                .ConfigureConnection(settings => ConfigureConnection(settings, clusterKey))
                .ConfigureTcp(settings => ConfigureTcp(settings, clusterKey));

            if (clusterKey.UseSsl)
            {
                builder.ConfigureSsl(settings => ConfigureSsl(settings, clusterKey));
            }

            if (clusterKey.ClusterConfigurator != null)
            {
                clusterKey.ClusterConfigurator(builder);
            }

            var cluster = builder.BuildCluster();
            cluster.Initialize();

            return cluster;
        }
Exemple #15
0
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder configuration, ConnectionString connectionString)
        {
            Ensure.IsNotNull(configuration, "configuration");
            Ensure.IsNotNull(connectionString, "connectionString");

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                // TODO: nowhere to set this
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                configuration.ConfigureTcp(s => s.WithAddressFamily(AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                configuration.ConfigureTcp(s => s
                                           .WithReadTimeout(connectionString.SocketTimeout.Value)
                                           .WithWriteTimeout(connectionString.SocketTimeout.Value));
            }

            if (connectionString.Ssl != null)
            {
                // TODO: nowhere to set this
            }

            // Connection
            if (connectionString.Username != null)
            {
                // TODO: nowhere to set this...
            }
            if (connectionString.MaxIdleTime != null)
            {
                configuration.ConfigureConnection(s => s.WithMaxIdleTime(connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                configuration.ConfigureConnection(s => s.WithMaxLifeTime(connectionString.MaxLifeTime.Value));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.WithMaxConnections(connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.WithMinConnections(connectionString.MinPoolSize.Value));
            }
            if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = maxConnections * connectionString.WaitQueueMultiple.Value;
                configuration.ConfigureConnectionPool(s => s.WithWaitQueueSize(waitQueueSize));
            }
            if (connectionString.WaitQueueTimeout != null)
            {
                configuration.ConfigureConnectionPool(s => s.WithWaitQueueTimeout(connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            if (connectionString.Hosts.Count > 0)
            {
                configuration.ConfigureCluster(s => s.WithEndPoints(connectionString.Hosts));
            }
            if (connectionString.ReplicaSet != null)
            {
                configuration.ConfigureCluster(s => s
                                               .WithReplicaSetName(connectionString.ReplicaSet));
            }

            return(configuration);
        }
 /// <summary>
 /// Configures a cluster builder from a connection string.
 /// </summary>
 /// <param name="builder">The cluster builder.</param>
 /// <param name="connectionString">The connection string.</param>
 /// <returns>A reconfigured cluster builder.</returns>
 public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, ConnectionString connectionString)
 {
     return(ConfigureWithConnectionString(builder, connectionString, serverApi: null));
 }
 private static void ConfigureCluster(ClusterBuilder cb)
 {
     cb.UsePerformanceCounters("test", true);
 }
        public static ClusterBuilder ConfigureLogging(ClusterBuilder builder)
        {
            var environmentVariable = Environment.GetEnvironmentVariable("MONGO_LOGGING");
            if (environmentVariable == null)
            {
                return builder;
            }

            SourceLevels defaultLevel;
            if (!Enum.TryParse<SourceLevels>(environmentVariable, ignoreCase: true, result: out defaultLevel))
            {
                return builder;
            }

            __traceSource = new TraceSource("mongodb-tests", defaultLevel);
            __traceSource.Listeners.Clear(); // remove the default listener
            #if NETSTANDARD1_6
            var listener = new TextWriterTraceListener(Console.Out);
            #else
            var listener = new ConsoleTraceListener();
            #endif
            listener.TraceOutputOptions = TraceOptions.DateTime;
            __traceSource.Listeners.Add(listener);
            return builder.TraceWith(__traceSource);
        }
 internal static Func <IStreamFactory, IStreamFactory> _streamFactoryWrapper(this ClusterBuilder obj) => (Func <IStreamFactory, IStreamFactory>)Reflector.GetFieldValue(obj, nameof(_streamFactoryWrapper));
 internal static IServerMonitorFactory CreateServerMonitorFactory(this ClusterBuilder obj) => (IServerMonitorFactory)Reflector.Invoke(obj, nameof(CreateServerMonitorFactory));
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder configuration, ConnectionString connectionString)
        {
            Ensure.IsNotNull(configuration, "configuration");
            Ensure.IsNotNull(connectionString, "connectionString");

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                configuration.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                configuration.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                configuration.ConfigureTcp(s => s.With(
                                               readTimeout: connectionString.SocketTimeout.Value,
                                               writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Ssl != null)
            {
                configuration.ConfigureSsl(ssl =>
                {
                    if (connectionString.SslVerifyCertificate.GetValueOrDefault(true))
                    {
                        ssl = ssl.With(
                            serverCertificateValidationCallback: new RemoteCertificateValidationCallback((obj, cert, chain, errors) => true));
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticator = CreateAuthenticator(connectionString);
                configuration.ConfigureConnection(s => s.With(authenticators: new[] { authenticator }));
            }

            if (connectionString.MaxIdleTime != null)
            {
                configuration.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                configuration.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.With(maxConnections: connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
            if (connectionString.WaitQueueSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = (int)Math.Round(maxConnections * connectionString.WaitQueueMultiple.Value);
                configuration.ConfigureConnectionPool(s => s.With(waitQueueSize: waitQueueSize));
            }
            if (connectionString.WaitQueueTimeout != null)
            {
                configuration.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            if (connectionString.Hosts.Count > 0)
            {
                configuration.ConfigureCluster(s => s.With(endPoints: Optional.Create <IEnumerable <EndPoint> >(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                configuration.ConfigureCluster(s => s.With(
                                                   replicaSetName: connectionString.ReplicaSet));
            }

            return(configuration);
        }
Exemple #22
0
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <param name="serverApi">The server API.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(
            this ClusterBuilder builder,
            ConnectionString connectionString,
            ServerApi serverApi)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(connectionString, nameof(connectionString));

            if (!connectionString.IsResolved)
            {
                bool resolveHosts;
#pragma warning disable CS0618 // Type or member is obsolete
                if (connectionString.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    resolveHosts = connectionString.DirectConnection.GetValueOrDefault();
                }
                else
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    resolveHosts = connectionString.Connect == ClusterConnectionMode.Direct || connectionString.Connect == ClusterConnectionMode.Standalone;
#pragma warning restore CS0618 // Type or member is obsolete
                }

                connectionString = connectionString.Resolve(resolveHosts);
            }

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.HeartbeatInterval.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatInterval: connectionString.HeartbeatInterval.Value));
            }
            if (connectionString.HeartbeatTimeout.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatTimeout: connectionString.HeartbeatTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                builder = builder.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(
                                                   readTimeout: connectionString.SocketTimeout.Value,
                                                   writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Tls != null)
            {
                builder = builder.ConfigureSsl(ssl =>
                {
                    if (connectionString.TlsInsecure.GetValueOrDefault(false))
                    {
                        ssl = ssl.With(serverCertificateValidationCallback: new RemoteCertificateValidationCallback(AcceptAnySslCertificate));
                    }
                    if (connectionString.TlsDisableCertificateRevocationCheck.HasValue)
                    {
                        ssl = ssl.With(
                            checkCertificateRevocation: !connectionString.TlsDisableCertificateRevocationCheck.Value);
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticatorFactory = new AuthenticatorFactory(() => CreateAuthenticator(connectionString, serverApi));
                builder = builder.ConfigureConnection(s => s.With(authenticatorFactories: new[] { authenticatorFactory }));
            }
            if (connectionString.ApplicationName != null)
            {
                builder = builder.ConfigureConnection(s => s.With(applicationName: connectionString.ApplicationName));
            }
            if (connectionString.LoadBalanced)
            {
                builder = builder.ConfigureConnection(s => s.With(loadBalanced: connectionString.LoadBalanced));
            }
            if (connectionString.MaxIdleTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            if (connectionString.Compressors != null)
            {
                builder = builder.ConfigureConnection(s => s.With(compressors: connectionString.Compressors.ToArray()));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                var effectiveMaxConnections = ConnectionStringConversions.GetEffectiveMaxConnections(connectionString.MaxPoolSize.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(maxConnections: effectiveMaxConnections));
            }
            if (connectionString.MinPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
#pragma warning disable 618
            if (connectionString.WaitQueueSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var effectiveMaxConnections = ConnectionStringConversions.GetEffectiveMaxConnections(connectionString.MaxPoolSize) ?? new ConnectionPoolSettings().MaxConnections;
                var computedWaitQueueSize   = ConnectionStringConversions.GetComputedWaitQueueSize(effectiveMaxConnections, connectionString.WaitQueueMultiple.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: computedWaitQueueSize));
            }
#pragma warning restore 618
            if (connectionString.WaitQueueTimeout != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
#pragma warning disable CS0618 // Type or member is obsolete
            var connectionModeSwitch = connectionString.ConnectionModeSwitch;
            var connectionMode       = connectionModeSwitch == ConnectionModeSwitch.UseConnectionMode ? connectionString.Connect : default;
            var directConnection     = connectionModeSwitch == ConnectionModeSwitch.UseDirectConnection ? connectionString.DirectConnection : default;
            builder = builder.ConfigureCluster(
                s =>
                s.With(
                    connectionMode: connectionMode,
                    connectionModeSwitch: connectionModeSwitch,
                    directConnection: directConnection,
                    scheme: connectionString.Scheme,
                    loadBalanced: connectionString.LoadBalanced));
#pragma warning restore CS0618 // Type or member is obsolete
            if (connectionString.Hosts.Count > 0)
            {
                builder = builder.ConfigureCluster(s => s.With(endPoints: Optional.Enumerable(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                builder = builder.ConfigureCluster(s => s.With(replicaSetName: connectionString.ReplicaSet));
            }
            if (connectionString.ServerSelectionTimeout != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverSelectionTimeout: connectionString.ServerSelectionTimeout.Value));
            }
            if (serverApi != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverApi: serverApi));
            }

            return(builder);
        }
Exemple #23
0
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, ConnectionString connectionString)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(connectionString, nameof(connectionString));

            if (!connectionString.IsResolved)
            {
                var connectionMode = connectionString.Connect;
                var resolveHosts   = connectionMode == ClusterConnectionMode.Direct || connectionMode == ClusterConnectionMode.Standalone;
                connectionString = connectionString.Resolve(resolveHosts);
            }

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.HeartbeatInterval.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatInterval: connectionString.HeartbeatInterval.Value));
            }
            if (connectionString.HeartbeatTimeout.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatTimeout: connectionString.HeartbeatTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                builder = builder.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(
                                                   readTimeout: connectionString.SocketTimeout.Value,
                                                   writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Tls != null)
            {
                builder = builder.ConfigureSsl(ssl =>
                {
                    if (connectionString.TlsInsecure.GetValueOrDefault(false))
                    {
                        ssl = ssl.With(serverCertificateValidationCallback: new RemoteCertificateValidationCallback(AcceptAnySslCertificate));
                    }
                    if (connectionString.TlsDisableCertificateRevocationCheck.HasValue)
                    {
                        ssl = ssl.With(
                            checkCertificateRevocation: !connectionString.TlsDisableCertificateRevocationCheck.Value);
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticatorFactory = new AuthenticatorFactory(() => CreateAuthenticator(connectionString));
                builder = builder.ConfigureConnection(s => s.With(authenticatorFactories: new[] { authenticatorFactory }));
            }
            if (connectionString.ApplicationName != null)
            {
                builder = builder.ConfigureConnection(s => s.With(applicationName: connectionString.ApplicationName));
            }
            if (connectionString.MaxIdleTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            if (connectionString.Compressors != null)
            {
                builder = builder.ConfigureConnection(s => s.With(compressors: connectionString.Compressors.ToArray()));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(maxConnections: connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
#pragma warning disable 618
            if (connectionString.WaitQueueSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = (int)Math.Round(maxConnections * connectionString.WaitQueueMultiple.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: waitQueueSize));
            }
#pragma warning restore 618
            if (connectionString.WaitQueueTimeout != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            builder = builder.ConfigureCluster(s => s.With(connectionMode: connectionString.Connect));
            if (connectionString.Hosts.Count > 0)
            {
                builder = builder.ConfigureCluster(s => s.With(endPoints: Optional.Enumerable(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                builder = builder.ConfigureCluster(s => s.With(
                                                       connectionMode: ClusterConnectionMode.ReplicaSet,
                                                       replicaSetName: connectionString.ReplicaSet));
            }
            if (connectionString.ServerSelectionTimeout != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverSelectionTimeout: connectionString.ServerSelectionTimeout.Value));
            }

            return(builder);
        }
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder configuration, ConnectionString connectionString)
        {
            Ensure.IsNotNull(configuration, "configuration");
            Ensure.IsNotNull(connectionString, "connectionString");

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                // TODO: nowhere to set this
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                configuration.ConfigureTcp(s => s.WithAddressFamily(AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                configuration.ConfigureTcp(s => s
                                           .WithReadTimeout(connectionString.SocketTimeout.Value)
                                           .WithWriteTimeout(connectionString.SocketTimeout.Value));
            }

            if (connectionString.Ssl != null)
            {
                configuration.ConfigureSsl(ssl =>
                {
                    if (connectionString.SslVerifyCertificate.GetValueOrDefault(true))
                    {
                        ssl = ssl.With(
                            serverCertificateValidator: new RemoteCertificateValidationCallback((obj, cert, chain, errors) => true));
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticator = CreateAuthenticator(connectionString);
                configuration.ConfigureConnection(s => s.WithAuthenticators(new[] { authenticator }));
            }

            if (connectionString.MaxIdleTime != null)
            {
                configuration.ConfigureConnection(s => s.WithMaxIdleTime(connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                configuration.ConfigureConnection(s => s.WithMaxLifeTime(connectionString.MaxLifeTime.Value));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.WithMaxConnections(connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                configuration.ConfigureConnectionPool(s => s.WithMinConnections(connectionString.MinPoolSize.Value));
            }
            if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = maxConnections * connectionString.WaitQueueMultiple.Value;
                configuration.ConfigureConnectionPool(s => s.WithWaitQueueSize(waitQueueSize));
            }
            if (connectionString.WaitQueueTimeout != null)
            {
                configuration.ConfigureConnectionPool(s => s.WithWaitQueueTimeout(connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            if (connectionString.Hosts.Count > 0)
            {
                configuration.ConfigureCluster(s => s.WithEndPoints(connectionString.Hosts));
            }
            if (connectionString.ReplicaSet != null)
            {
                configuration.ConfigureCluster(s => s
                                               .WithReplicaSetName(connectionString.ReplicaSet));
            }

            return(configuration);
        }
 public static ClusterBuilder ConfigureLogging(ClusterBuilder builder)
 {
     var traceSource = new TraceSource("mongodb-tests", SourceLevels.Information);
     traceSource.Listeners.Clear(); // remove the default listener
     var listener = new ConsoleTraceListener();
     traceSource.Listeners.Add(listener);
     return builder.TraceWith(traceSource);
 }
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, ConnectionString connectionString)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(connectionString, nameof(connectionString));

            connectionString = connectionString.Resolve();

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.HeartbeatInterval.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatInterval: connectionString.HeartbeatInterval.Value));
            }
            if (connectionString.HeartbeatTimeout.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatTimeout: connectionString.HeartbeatTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                builder = builder.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(
                                                   readTimeout: connectionString.SocketTimeout.Value,
                                                   writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Ssl != null)
            {
                builder = builder.ConfigureSsl(ssl =>
                {
                    if (!connectionString.SslVerifyCertificate.GetValueOrDefault(true))
                    {
                        ssl = ssl.With(
                            serverCertificateValidationCallback: new RemoteCertificateValidationCallback(AcceptAnySslCertificate));
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticator = CreateAuthenticator(connectionString);
                builder = builder.ConfigureConnection(s => s.With(authenticators: new[] { authenticator }));
            }
            if (connectionString.ApplicationName != null)
            {
                builder = builder.ConfigureConnection(s => s.With(applicationName: connectionString.ApplicationName));
            }
            if (connectionString.MaxIdleTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(maxConnections: connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
            if (connectionString.WaitQueueSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = (int)Math.Round(maxConnections * connectionString.WaitQueueMultiple.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: waitQueueSize));
            }
            if (connectionString.WaitQueueTimeout != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            builder = builder.ConfigureCluster(s => s.With(connectionMode: connectionString.Connect));
            if (connectionString.Hosts.Count > 0)
            {
                builder = builder.ConfigureCluster(s => s.With(endPoints: Optional.Enumerable(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                builder = builder.ConfigureCluster(s => s.With(
                                                       connectionMode: ClusterConnectionMode.ReplicaSet,
                                                       replicaSetName: connectionString.ReplicaSet));
            }
            if (connectionString.ServerSelectionTimeout != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverSelectionTimeout: connectionString.ServerSelectionTimeout.Value));
            }

            return(builder);
        }
Exemple #27
0
        private static void ConfigureCluster(ClusterBuilder cb)
        {
#if NET45
            cb.UsePerformanceCounters("test", true);
#endif
        }