/// <summary> /// Sets the read preference. /// </summary> /// <param name="readPreference">The read preference.</param> /// <returns>The cursor (so you can chain method calls to it).</returns> public virtual MongoCursor SetReadPreference(ReadPreference readPreference) { if (_isFrozen) { ThrowFrozen(); } _readPreference = readPreference; return this; }
/// <inheritdoc /> public virtual Task <TResult> RunCommandAsync <TResult>(IClientSessionHandle session, Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); }
/// <summary> /// Lets the server know that this thread is about to begin a series of related operations that must all occur /// on the same connection. The return value of this method implements IDisposable and can be placed in a /// using statement (in which case RequestDone will be called automatically when leaving the using statement). /// </summary> /// <param name="readPreference">The read preference.</param> /// <returns>A helper object that implements IDisposable and calls <see cref="RequestDone"/> from the Dispose method.</returns> internal virtual IDisposable RequestStart(ReadPreference readPreference) { var serverSelector = new ReadPreferenceServerSelector(readPreference); return(RequestStart(serverSelector, readPreference)); }
public static IReadBinding GetReadBinding(ReadPreference readPreference) { return(new ReadPreferenceBinding(__cluster.Value, readPreference)); }
/// <inheritdoc /> public virtual TResult RunCommand <TResult>(Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); }
public static MongoCursor Create(Type documentType, MongoCollection collection, IMongoQuery query, ReadConcern readConcern, ReadPreference readPreference, IBsonSerializer serializer) { var cursorDefinition = typeof(MongoCursor <>); var cursorType = cursorDefinition.MakeGenericType(documentType); var constructorInfo = cursorType.GetTypeInfo().GetConstructor(new Type[] { typeof(MongoCollection), typeof(IMongoQuery), typeof(ReadConcern), typeof(ReadPreference), typeof(IBsonSerializer) }); return((MongoCursor)constructorInfo.Invoke(new object[] { collection, query, readConcern, readPreference, serializer })); }
private async Task <T> ExecuteReadOperation <T>(IReadOperation <T> operation, ReadPreference readPreference, CancellationToken cancellationToken) { using (var binding = new ReadPreferenceBinding(_cluster, readPreference)) { return(await _operationExecutor.ExecuteReadOperationAsync(binding, operation, _settings.OperationTimeout, cancellationToken).ConfigureAwait(false)); } }
/// <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.InvariantCultureIgnoreCase); _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; 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.WithTagSets(connectionString.ReadPreferenceTags); } _replicaSetName = connectionString.ReplicaSet; _secondaryAcceptableLatency = connectionString.SecondaryAcceptableLatency.GetValueOrDefault(MongoDefaults.SecondaryAcceptableLatency); _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) { return(new MongoServerAddress(ipEndPoint.Address.ToString(), ipEndPoint.Port)); } else { throw new NotSupportedException("Only DnsEndPoint and IPEndPoints are supported in the connection string."); } }); _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; }
public void Constructor_should_assume_empty_tagSets_when_tagSets_parameter_is_missing() { var readPreference = new ReadPreference(ReadPreferenceMode.Primary); readPreference.TagSets.Count.Should().Be(0); }
// constructors /// <summary> /// Initializes a new instance of the MongoCursorEnumerator class. /// </summary> /// <param name="cursor">The cursor to be enumerated.</param> public MongoCursorEnumerator(MongoCursor <TDocument> cursor) { _cursor = cursor; _readPreference = _cursor.ReadPreference; }
public virtual IDisposable RequestStart(MongoDatabase initialDatabase, bool slaveOk) { var readPreference = ReadPreference.FromSlaveOk(slaveOk); return(RequestStart(initialDatabase, readPreference)); }
/// <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); _applicationName = connectionString.ApplicationName; _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); _heartbeatInterval = connectionString.HeartbeatInterval ?? ServerSettings.DefaultHeartbeatInterval; _heartbeatTimeout = connectionString.HeartbeatTimeout ?? ServerSettings.DefaultHeartbeatTimeout; _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.HasValue || connectionString.ReadPreferenceTags != null || connectionString.MaxStaleness.HasValue) { if (!connectionString.ReadPreference.HasValue) { throw new MongoConfigurationException("readPreference mode is required when using tag sets or max staleness."); } _readPreference = new ReadPreference(connectionString.ReadPreference.Value, connectionString.ReadPreferenceTags, connectionString.MaxStaleness); } _replicaSetName = connectionString.ReplicaSet; _retryWrites = connectionString.RetryWrites; _localThreshold = connectionString.LocalThreshold.GetValueOrDefault(MongoDefaults.LocalThreshold); _scheme = connectionString.Scheme; _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; }
/// <summary> /// Lets the server know that this thread is about to begin a series of related operations that must all occur /// on the same connection. The return value of this method implements IDisposable and can be placed in a /// using statement (in which case RequestDone will be called automatically when leaving the using statement). /// </summary> /// <param name="initialDatabase">One of the databases involved in the related operations.</param> /// <param name="readPreference">The read preference.</param> /// <returns>A helper object that implements IDisposable and calls <see cref="RequestDone"/> from the Dispose method.</returns> public virtual IDisposable RequestStart(MongoDatabase initialDatabase, ReadPreference readPreference) { var serverSelector = new ReadPreferenceServerSelector(readPreference); return(RequestStart(serverSelector, readPreference)); }
public override Task <TResult> RunCommandAsync <TResult>(Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(command, "command"); readPreference = readPreference ?? ReadPreference.Primary; var renderedCommand = command.Render(_settings.SerializerRegistry); var messageEncoderSettings = GetMessageEncoderSettings(); if (readPreference == ReadPreference.Primary) { var operation = new WriteCommandOperation <TResult>(_databaseNamespace, renderedCommand.Document, renderedCommand.ResultSerializer, messageEncoderSettings); return(ExecuteWriteOperation <TResult>(operation, cancellationToken)); } else { var operation = new ReadCommandOperation <TResult>(_databaseNamespace, renderedCommand.Document, renderedCommand.ResultSerializer, messageEncoderSettings); return(ExecuteReadOperation <TResult>(operation, readPreference, cancellationToken)); } }
public virtual IDisposable RequestStart(bool slaveOk) { return(_server.RequestStart(this, ReadPreference.FromSlaveOk(slaveOk))); }
public void Constructor_should_set_mode_correctly() { var readPreference = new ReadPreference(ReadPreferenceMode.Secondary); // use a value that is not the default readPreference.ReadPreferenceMode.Should().Be(ReadPreferenceMode.Secondary); }
/// <summary> /// Lets the server know that this thread is about to begin a series of related operations that must all occur /// on the same connection. The return value of this method implements IDisposable and can be placed in a /// using statement (in which case RequestDone will be called automatically when leaving the using statement). /// </summary> /// <param name="readPreference">The read preference.</param> /// <returns>A helper object that implements IDisposable and calls <see cref="RequestDone"/> from the Dispose method.</returns> public virtual IDisposable RequestStart(ReadPreference readPreference) { return(_server.RequestStart(this, readPreference)); }
/// <inheritdoc /> public abstract IMongoCollection <TDocument> WithReadPreference(ReadPreference readPreference);
/// <summary> /// Initializes a new instance of the <see cref="MongoCursor"/> class. /// </summary> /// <param name="collection">The collection.</param> /// <param name="query">The query.</param> /// <param name="readConcern">The read concern.</param> /// <param name="readPreference">The read preference.</param> /// <param name="serializer">The serializer.</param> protected MongoCursor(MongoCollection collection, IMongoQuery query, ReadConcern readConcern, ReadPreference readPreference, IBsonSerializer serializer) : this(collection, query, readPreference, serializer) { _readConcern = readConcern; }
private TResult ExecuteReadOperation <TResult>(IReadOperation <TResult> operation, ReadPreference readPreference, CancellationToken cancellationToken) { using (var binding = new ReadPreferenceBinding(_cluster, readPreference)) { return(_operationExecutor.ExecuteReadOperation(binding, operation, cancellationToken)); } }
/// <summary> /// Parses a URL and sets all settings to match the URL. /// </summary> /// <param name="url">The URL.</param> public void Parse(string url) { const string serverPattern = @"((\[[^]]+?\]|[^:,/?#]+)(:\d+)?)"; const string pattern = @"^mongodb://" + @"((?<username>[^:]+)(:(?<password>.*?))?@)?" + @"(?<servers>" + serverPattern + @"(," + serverPattern + ")*)?" + @"(/(?<database>[^?]+)?(\?(?<query>.*))?)?$"; Match match = Regex.Match(url, pattern); if (match.Success) { var usernameGroup = match.Groups["username"]; if (usernameGroup.Success) { _username = Uri.UnescapeDataString(usernameGroup.Value); } var passwordGroup = match.Groups["password"]; if (passwordGroup.Success) { _password = Uri.UnescapeDataString(passwordGroup.Value); } string servers = match.Groups["servers"].Value; var databaseGroup = match.Groups["database"]; if (databaseGroup.Success) { _databaseName = databaseGroup.Value; } string query = match.Groups["query"].Value; if (servers != "") { List <MongoServerAddress> addresses = new List <MongoServerAddress>(); foreach (string server in servers.Split(',')) { var address = MongoServerAddress.Parse(server); addresses.Add(address); } _servers = addresses; } if (!string.IsNullOrEmpty(query)) { foreach (var pair in query.Split('&', ';')) { var parts = pair.Split('='); if (parts.Length != 2) { throw new FormatException(string.Format("Invalid connection string '{0}'.", parts)); } var name = parts[0]; var value = parts[1]; switch (name.ToLower()) { case "authmechanism": _authenticationMechanism = value; break; case "authsource": _authenticationSource = value; break; case "connect": ConnectionMode = ParseConnectionMode(name, value); break; case "connecttimeout": case "connecttimeoutms": ConnectTimeout = ParseTimeSpan(name, value); break; case "fsync": FSync = ParseBoolean(name, value); break; case "gssapiservicename": _gssapiServiceName = value; break; case "guids": case "uuidrepresentation": GuidRepresentation = (GuidRepresentation)Enum.Parse(typeof(GuidRepresentation), value, true); // ignoreCase break; case "ipv6": IPv6 = ParseBoolean(name, value); break; case "j": case "journal": Journal = ParseBoolean(name, value); break; case "maxidletime": case "maxidletimems": MaxConnectionIdleTime = ParseTimeSpan(name, value); break; case "maxlifetime": case "maxlifetimems": MaxConnectionLifeTime = ParseTimeSpan(name, value); break; case "maxpoolsize": MaxConnectionPoolSize = ParseInt32(name, value); break; case "minpoolsize": MinConnectionPoolSize = ParseInt32(name, value); break; case "readpreference": if (_readPreference == null) { _readPreference = new ReadPreference(ReadPreferenceMode.Primary); } _readPreference = _readPreference.WithMode(ParseReadPreferenceMode(name, value)); break; case "readpreferencetags": if (_readPreference == null) { _readPreference = new ReadPreference(ReadPreferenceMode.Primary); } _readPreference = _readPreference.WithTagSets(_readPreference.TagSets.Concat(new[] { ParseReplicaSetTagSet(name, value) })); break; case "replicaset": ReplicaSetName = value; break; case "safe": var safe = Convert.ToBoolean(value); if (_w == null) { W = safe ? 1 : 0; } else { if (safe) { // don't overwrite existing W value unless it's 0 var wCount = _w as WriteConcern.WCount; if (wCount != null && wCount.Value == 0) { W = 1; } } else { W = 0; } } break; case "secondaryacceptablelatency": case "secondaryacceptablelatencyms": SecondaryAcceptableLatency = ParseTimeSpan(name, value); break; case "slaveok": if (_readPreference != null) { throw new InvalidOperationException("SlaveOk cannot be set because ReadPreference already has a value."); } _slaveOk = ParseBoolean(name, value); break; case "sockettimeout": case "sockettimeoutms": SocketTimeout = ParseTimeSpan(name, value); break; case "ssl": UseSsl = ParseBoolean(name, value); break; case "sslverifycertificate": VerifySslCertificate = ParseBoolean(name, value); break; case "w": W = WriteConcern.WValue.Parse(value); break; case "waitqueuemultiple": WaitQueueMultiple = ParseDouble(name, value); break; case "waitqueuesize": WaitQueueSize = ParseInt32(name, value); break; case "waitqueuetimeout": case "waitqueuetimeoutms": WaitQueueTimeout = ParseTimeSpan(name, value); break; case "wtimeout": case "wtimeoutms": WTimeout = ParseTimeSpan(name, value); break; default: var message = string.Format("Invalid option '{0}'.", name); throw new ArgumentException(message, "url"); } } } } else { throw new FormatException(string.Format("Invalid connection string '{0}'.", url)); } }
public override Task <TResult> RunCommandAsync <TResult>(Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken)) { return(UsingImplicitSessionAsync(session => RunCommandAsync(session, command, readPreference, cancellationToken), cancellationToken)); }
// private methods private TResult ExecuteReadOperation <TResult>(IClientSessionHandle session, IReadOperation <TResult> operation, ReadPreference readPreference = null) { readPreference = readPreference ?? _settings.ReadPreference ?? ReadPreference.Primary; using (var binding = GetReadBinding(readPreference, session)) { return(_operationExecutor.ExecuteReadOperation(binding, operation, CancellationToken.None)); } }
public override Task <TResult> RunCommandAsync <TResult>(IClientSessionHandle session, Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(command, nameof(command)); var operation = CreateRunCommandOperation(command); var effectiveReadPreference = ReadPreferenceResolver.GetEffectiveReadPreference(session, readPreference, ReadPreference.Primary); return(ExecuteReadOperationAsync(session, operation, effectiveReadPreference, cancellationToken)); }
/// <inheritdoc /> public abstract Task <TResult> RunCommandAsync <TResult>(Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = default(CancellationToken));
private T ExecuteReadOperation <T>(IClientSessionHandle session, IReadOperation <T> operation, ReadPreference readPreference, CancellationToken cancellationToken) { using (var binding = CreateReadBinding(session, readPreference)) { return(_operationExecutor.ExecuteReadOperation(binding, operation, cancellationToken)); } }
/// <inheritdoc /> public virtual IMongoDatabase WithReadPreference(ReadPreference readPreference) { throw new NotImplementedException(); }
private async Task <T> ExecuteReadOperationAsync <T>(IClientSessionHandle session, IReadOperation <T> operation, ReadPreference readPreference, CancellationToken cancellationToken) { using (var binding = CreateReadBinding(session, readPreference)) { return(await _operationExecutor.ExecuteReadOperationAsync(binding, operation, cancellationToken).ConfigureAwait(false)); } }
// private methods private TResult ExecuteReadOperation <TResult>(IReadOperation <TResult> operation, ReadPreference readPreference = null) { readPreference = readPreference ?? _settings.ReadPreference ?? ReadPreference.Primary; using (var binding = _server.GetReadBinding(readPreference)) { return(operation.Execute(binding, CancellationToken.None)); } }
private T ExecuteReadOperation <T>(IClientSessionHandle session, IReadOperation <T> operation, ReadPreference readPreference, CancellationToken cancellationToken) { using (var binding = new ReadPreferenceBinding(_cluster, readPreference, session.ToCoreSession())) { return(_operationExecutor.ExecuteReadOperation(binding, operation, cancellationToken)); } }