// methods
        protected BsonDocument CreateReadPreferenceDocument(ReadPreference readPreference)
        {
            if (readPreference == null)
            {
                return null;
            }

            BsonArray tagSets = null;
            if (readPreference.TagSets != null)
            {
                tagSets = new BsonArray(readPreference.TagSets.Select(ts => new BsonDocument(ts.Tags.Select(t => new BsonElement(t.Name, t.Value)))));
            }

            return new BsonDocument
            {
                { "mode", BsonUtils.ToCamelCase(readPreference.ReadPreferenceMode.ToString()) },
                { "tags", tagSets, tagSets != null }
            };
        }
Пример #2
0
 // constructors
 /// <summary>
 /// Creates a new instance of MongoUrlBuilder.
 /// </summary>
 public MongoUrlBuilder()
 {
     _authenticationMechanism = MongoDefaults.AuthenticationMechanism;
     _authenticationMechanismProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
     _authenticationSource = null;
     _connectionMode = ConnectionMode.Automatic;
     _connectTimeout = MongoDefaults.ConnectTimeout;
     _databaseName = null;
     _fsync = null;
     _guidRepresentation = MongoDefaults.GuidRepresentation;
     _ipv6 = false;
     _journal = null;
     _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
     _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
     _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
     _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
     _password = null;
     _readConcernLevel = null;
     _readPreference = null;
     _replicaSetName = null;
     _localThreshold = MongoDefaults.LocalThreshold;
     _servers = new[] { new MongoServerAddress("localhost", 27017) };
     _serverSelectionTimeout = MongoDefaults.ServerSelectionTimeout;
     _socketTimeout = MongoDefaults.SocketTimeout;
     _username = null;
     _useSsl = false;
     _verifySslCertificate = true;
     _w = null;
     _waitQueueMultiple = MongoDefaults.WaitQueueMultiple;
     _waitQueueSize = MongoDefaults.WaitQueueSize;
     _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
     _wTimeout = null;
 }
Пример #3
0
        /// <summary>
        /// Parses a URL and sets all settings to match the URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        public void Parse(string url)
        {
            var connectionString = new ConnectionString(url);
            _authenticationMechanism = connectionString.AuthMechanism;
            _authenticationMechanismProperties = connectionString.AuthMechanismProperties.ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
            _authenticationSource = connectionString.AuthSource;
            switch (connectionString.Connect)
            {
                case ClusterConnectionMode.Direct:
                    _connectionMode = Driver.ConnectionMode.Direct;
                    break;
                case ClusterConnectionMode.ReplicaSet:
                    _connectionMode = Driver.ConnectionMode.ReplicaSet;
                    break;
                case ClusterConnectionMode.Sharded:
                    _connectionMode = Driver.ConnectionMode.ShardRouter;
                    break;
                case ClusterConnectionMode.Standalone:
                    _connectionMode = Driver.ConnectionMode.Standalone;
                    break;
                default:
                    _connectionMode = Driver.ConnectionMode.Automatic;
                    break;
            }
            _connectTimeout = connectionString.ConnectTimeout.GetValueOrDefault(MongoDefaults.ConnectTimeout);
            _databaseName = connectionString.DatabaseName;
            _fsync = connectionString.FSync;
            _guidRepresentation = connectionString.UuidRepresentation.GetValueOrDefault(MongoDefaults.GuidRepresentation);
            _ipv6 = connectionString.Ipv6.GetValueOrDefault(false);
            _journal = connectionString.Journal;
            _maxConnectionIdleTime = connectionString.MaxIdleTime.GetValueOrDefault(MongoDefaults.MaxConnectionIdleTime);
            _maxConnectionLifeTime = connectionString.MaxLifeTime.GetValueOrDefault(MongoDefaults.MaxConnectionLifeTime);
            _maxConnectionPoolSize = connectionString.MaxPoolSize.GetValueOrDefault(MongoDefaults.MaxConnectionPoolSize);
            _minConnectionPoolSize = connectionString.MinPoolSize.GetValueOrDefault(MongoDefaults.MinConnectionPoolSize);
            _password = connectionString.Password;
            _readConcernLevel = connectionString.ReadConcernLevel;
            if (connectionString.ReadPreference != null)
            {
                _readPreference = new ReadPreference(connectionString.ReadPreference.Value);
            }
            if (connectionString.ReadPreferenceTags != null)
            {
                if (_readPreference == null)
                {
                    throw new MongoConfigurationException("ReadPreferenceMode is required when using tag sets.");
                }
                _readPreference = _readPreference.With(tagSets: connectionString.ReadPreferenceTags);
            }

            _replicaSetName = connectionString.ReplicaSet;
            _localThreshold = connectionString.LocalThreshold.GetValueOrDefault(MongoDefaults.LocalThreshold);
            _servers = connectionString.Hosts.Select(endPoint =>
            {
                DnsEndPoint dnsEndPoint;
                IPEndPoint ipEndPoint;
                if ((dnsEndPoint = endPoint as DnsEndPoint) != null)
                {
                    return new MongoServerAddress(dnsEndPoint.Host, dnsEndPoint.Port);
                }
                else if ((ipEndPoint = endPoint as IPEndPoint) != null)
                {
                    var address = ipEndPoint.Address.ToString();
                    if (ipEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {
                        address = "[" + address + "]";
                    }
                    return new MongoServerAddress(address, ipEndPoint.Port);
                }
                else
                {
                    throw new NotSupportedException("Only DnsEndPoint and IPEndPoints are supported in the connection string.");
                }
            });
            _serverSelectionTimeout = connectionString.ServerSelectionTimeout.GetValueOrDefault(MongoDefaults.ServerSelectionTimeout);
            _socketTimeout = connectionString.SocketTimeout.GetValueOrDefault(MongoDefaults.SocketTimeout);
            _username = connectionString.Username;
            _useSsl = connectionString.Ssl.GetValueOrDefault(false);
            _verifySslCertificate = connectionString.SslVerifyCertificate.GetValueOrDefault(true);
            _w = connectionString.W;
            if (connectionString.WaitQueueSize != null)
            {
                _waitQueueSize = connectionString.WaitQueueSize.Value;
                _waitQueueMultiple = 0.0;
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                _waitQueueMultiple = connectionString.WaitQueueMultiple.Value;
                _waitQueueSize = 0;
            }
            _waitQueueTimeout = connectionString.WaitQueueTimeout.GetValueOrDefault(MongoDefaults.WaitQueueTimeout);
            _wTimeout = connectionString.WTimeout;
        }
 /// <inheritdoc />
 public virtual IMongoClient WithReadPreference(ReadPreference readPreference)
 {
     throw new NotImplementedException();
 }
 /// <inheritdoc/>
 public override IMongoClient WithReadPreference(ReadPreference readPreference)
 {
     Ensure.IsNotNull(readPreference, nameof(readPreference));
     var newSettings = Settings.Clone();
     newSettings.ReadPreference = readPreference;
     return new MongoClient(_operationExecutor, newSettings);
 }
 public void Constructor_should_set_tagSets_correctly()
 {
     var tagSets = new[] { new TagSet(new[] { new Tag("name1", "value1") }), new TagSet(new[] { new Tag("name2", "value2") }) };
     var readPreference = new ReadPreference(ReadPreferenceMode.Secondary, tagSets);
     readPreference.TagSets.Should().Equal(tagSets);
 }
 public void Constructor_should_copy_tagSets_list()
 {
     var tagSets = new[] { new TagSet(new[] { new Tag("name", "value") }) };
     var readPreference = new ReadPreference(ReadPreferenceMode.Primary, tagSets);
     readPreference.TagSets.Should().NotBeSameAs(tagSets);
 }
 public void WithTagSets_should_return_same_instance_when_the_value_is_the_same()
 {
     var tagSets1 = new[] { new TagSet(new[] { new Tag("name", "value") }) };
     var tagSets2 = new[] { new TagSet(new[] { new Tag("name", "value") }) };
     var readPreference1 = new ReadPreference(ReadPreferenceMode.Primary, tagSets1);
     var readPreference2 = readPreference1.WithTagSets(tagSets2);
     readPreference2.Should().BeSameAs(readPreference1);
 }
        public void Execute_should_find_all_the_documents_matching_the_query_when_max_staleness_is_used(
            [Values(false, true)]
            bool async)
        {
            RequireServer.Check().Supports(Feature.MaxStaleness);
            EnsureTestData();
            var subject = new FindOperation<BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings);
            var readPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred, maxStaleness: TimeSpan.FromSeconds(30));

            // the count could be short temporarily until replication catches up
            List<BsonDocument> result = null;
            SpinWait.SpinUntil(() =>
            {
                var cursor = ExecuteOperation(subject, readPreference, async);
                result = ReadCursorToEnd(cursor, async);
                return result.Count >= 5;
            },
            TimeSpan.FromSeconds(10));

            result.Should().HaveCount(5);
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelSourceReadWriteBinding"/> class.
 /// </summary>
 /// <param name="channelSource">The channel source.</param>
 /// <param name="readPreference">The read preference.</param>
 public ChannelSourceReadWriteBinding(IChannelSourceHandle channelSource, ReadPreference readPreference)
 {
     _channelSource = Ensure.IsNotNull(channelSource, "channelSource");
     _readPreference = Ensure.IsNotNull(readPreference, "readPreference");
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SplitReadWriteBinding"/> class.
 /// </summary>
 /// <param name="cluster">The cluster.</param>
 /// <param name="readPreference">The read preference.</param>
 public SplitReadWriteBinding(ICluster cluster, ReadPreference readPreference)
     : this(new ReadPreferenceBinding(cluster, readPreference), new WritableServerBinding(cluster))
 {
 }
 // constructors
 public ConnectionSourceReadWriteBinding(IConnectionSourceHandle connectionSource, ReadPreference readPreference)
 {
     _connectionSource = Ensure.IsNotNull(connectionSource, "connectionSource");
     _readPreference = Ensure.IsNotNull(readPreference, "readPreference");
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelReadBinding"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="readPreference">The read preference.</param>
 public ChannelReadBinding(IServer server, IChannelHandle channel, ReadPreference readPreference)
 {
     _server = Ensure.IsNotNull(server, "server");
     _channel = Ensure.IsNotNull(channel, "channel");
     _readPreference = Ensure.IsNotNull(readPreference, "readPreference");
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ReadPreferenceBinding"/> class.
 /// </summary>
 /// <param name="cluster">The cluster.</param>
 /// <param name="readPreference">The read preference.</param>
 public ReadPreferenceBinding(ICluster cluster, ReadPreference readPreference)
 {
     _cluster = Ensure.IsNotNull(cluster, "cluster");
     _readPreference = Ensure.IsNotNull(readPreference, "readPreference");
     _serverSelector = new ReadPreferenceServerSelector(readPreference);
 }
 public void WithMode_should_return_same_instance_when_the_value_is_the_same()
 {
     var readPreference1 = new ReadPreference(ReadPreferenceMode.Secondary);
     var readPreference2 = readPreference1.WithMode(ReadPreferenceMode.Secondary);
     readPreference2.Should().BeSameAs(readPreference1);
 }
 public void WithTagSets_should_return_new_instance_when_the_value_is_not_the_same()
 {
     var tagSets1 = new[] { new TagSet(new[] { new Tag("name1", "value1") }) };
     var tagSets2 = new[] { new TagSet(new[] { new Tag("name2", "value2") }) };
     var readPreference1 = new ReadPreference(ReadPreferenceMode.Primary, tagSets1);
     var readPreference2 = readPreference1.WithTagSets(tagSets2);
     readPreference2.Should().NotBeSameAs(readPreference1);
     readPreference2.TagSets.Should().Equal(tagSets2);
 }
 // constructors
 public ConnectionReadBinding(IServer server, IConnectionHandle connection, ReadPreference readPreference)
 {
     _server = Ensure.IsNotNull(server, "server");
     _connection = Ensure.IsNotNull(connection, "connection");
     _readPreference = Ensure.IsNotNull(readPreference, "readPreference");
 }
 public void Constructor_should_assume_empty_tagSets_when_tagSets_parameter_is_missing()
 {
     var readPreference = new ReadPreference(ReadPreferenceMode.Primary);
     readPreference.TagSets.Count.Should().Be(0);
 }
        public void TestWithReadPreference()
        {
            var originalReadPreference = new ReadPreference(ReadPreferenceMode.Secondary);
            var subject = __server.WithReadPreference(originalReadPreference);
            var newReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred);

            var result = subject.WithReadPreference(newReadPreference);

            subject.Settings.ReadPreference.Should().BeSameAs(originalReadPreference);
            result.Settings.ReadPreference.Should().BeSameAs(newReadPreference);
            result.WithReadPreference(originalReadPreference).Settings.Should().Be(subject.Settings);
        }
 public void Constructor_should_set_mode_correctly()
 {
     var readPreference = new ReadPreference(ReadPreferenceMode.Secondary); // use a value that is not the default
     readPreference.Mode.Should().Be(ReadPreferenceMode.Secondary);
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelReadBinding"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="readPreference">The read preference.</param>
 public ChannelReadBinding(IServer server, IChannelHandle channel, ReadPreference readPreference)
 {
     _server = Ensure.IsNotNull(server, nameof(server));
     _channel = Ensure.IsNotNull(channel, nameof(channel));
     _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference));
 }
 public static IReadBinding GetReadBinding(ReadPreference readPreference)
 {
     return new ReadPreferenceBinding(__cluster.Value, readPreference);
 }
        public void CreateCommand_should_return_expected_result_when_readPreference_is_provided(
            [Values(ReadPreferenceMode.PrimaryPreferred, ReadPreferenceMode.Secondary)]
            ReadPreferenceMode value)
        {
            var subject = new FindCommandOperation<BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings);
            var readPreference = new ReadPreference(value);
            var reflector = new Reflector(subject);
            var serverDescription = CreateServerDescription(type: ServerType.ShardRouter);

            var result = reflector.CreateCommand(serverDescription, readPreference);

            var mode = value.ToString();
            var camelCaseMode = char.ToLower(mode[0]) + mode.Substring(1);
            result.Should().Be($"{{ find : '{_collectionNamespace.CollectionName}', readPreference : {{ mode : '{camelCaseMode}' }} }}");
        }
 // public methods
 public BsonDocument CreateCommand(ServerDescription serverDescription, ReadPreference readPreference)
 {
     var methodInfo = _instance.GetType().GetMethod("CreateCommand", BindingFlags.NonPublic | BindingFlags.Instance);
     return (BsonDocument)methodInfo.Invoke(_instance, new object[] { serverDescription, readPreference });
 }
        public void WithReadPreference_should_return_expected_result()
        {
            var originalReadPreference = new ReadPreference(ReadPreferenceMode.Secondary);
            var subject = CreateSubject(_operationExecutor).WithReadPreference(originalReadPreference);
            var newReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred);

            var result = subject.WithReadPreference(newReadPreference);

            subject.Settings.ReadPreference.Should().BeSameAs(originalReadPreference);
            result.Settings.ReadPreference.Should().BeSameAs(newReadPreference);
            result.WithReadPreference(originalReadPreference).Settings.Should().Be(subject.Settings);
        }