/// <summary>
        /// Creates a new instance of MongoDatabaseSettings.
        /// </summary>
        /// <param name="databaseName">The name of the database.</param>
        /// <param name="credentials">The credentials to access the database.</param>
        /// <param name="guidRepresentation">The representation for Guids.</param>
        /// <param name="readPreference">The read preference.</param>
        /// <param name="writeConcern">The write concern to use.</param>
        public MongoDatabaseSettings(
            string databaseName,
            MongoCredentials credentials,
            GuidRepresentation guidRepresentation,
            ReadPreference readPreference,
            WriteConcern writeConcern)
        {
            if (databaseName == null)
            {
                throw new ArgumentNullException("databaseName");
            }
            if (databaseName == "admin" && credentials != null && !credentials.Admin)
            {
                throw new ArgumentOutOfRangeException("credentials", "Credentials for the admin database must have the admin flag set to true.");
            }
            if (readPreference == null)
            {
                throw new ArgumentNullException("readPreference");
            }
            if (writeConcern == null)
            {
                throw new ArgumentNullException("writeConcern");
            }

            _databaseName = databaseName;
            _credentials = credentials;
            _guidRepresentation = guidRepresentation;
            _readPreference = readPreference;
            _writeConcern = writeConcern;
        }
 // constructors
 /// <summary>
 /// Creates a new instance of MongoUrlBuilder.
 /// </summary>
 public MongoUrlBuilder()
 {
     _connectionMode = ConnectionMode.Automatic;
     _connectTimeout = MongoDefaults.ConnectTimeout;
     _databaseName = null;
     _defaultCredentials = null;
     _fsync = null;
     _guidRepresentation = MongoDefaults.GuidRepresentation;
     _ipv6 = false;
     _journal = null;
     _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
     _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
     _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
     _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
     _readPreference = null;
     _replicaSetName = null;
     _secondaryAcceptableLatency = MongoDefaults.SecondaryAcceptableLatency;
     _servers = null;
     _slaveOk = null;
     _socketTimeout = MongoDefaults.SocketTimeout;
     _useSsl = false;
     _verifySslCertificate = true;
     _w = null;
     _waitQueueMultiple = MongoDefaults.WaitQueueMultiple;
     _waitQueueSize = MongoDefaults.WaitQueueSize;
     _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
     _wTimeout = null;
 }
 /// <summary>
 /// Initializes a new instance of the BsonBinaryWriterSettings class.
 /// </summary>
 /// <param name="closeOutput">Whether to close the output stream when the writer is closed.</param>
 /// <param name="fixOldBinarySubTypeOnOutput">Whether to fix old binary data subtype on output.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="maxDocumentSize">The max document size.</param>
 public BsonBinaryWriterSettings(bool closeOutput, bool fixOldBinarySubTypeOnOutput, GuidRepresentation guidRepresentation, int maxDocumentSize)
     : base(guidRepresentation)
 {
     _closeOutput = closeOutput;
     _fixOldBinarySubTypeOnOutput = fixOldBinarySubTypeOnOutput;
     _maxDocumentSize = maxDocumentSize;
 }
Example #4
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;
 }
 // constructors
 /// <summary>
 /// Creates a new instance of MongoUrlBuilder.
 /// </summary>
 public MongoUrlBuilder()
 {
     _authenticationMechanism = MongoDefaults.AuthenticationMechanism;
     _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;
     _readPreference = null;
     _replicaSetName = null;
     _servers = null;
     _slaveOk = null;
     _socketTimeout = MongoDefaults.SocketTimeout;
     _username = null;
     _useSsl = false;
     _verifySslCertificate = true;
     _w = null;
     _waitQueueMultiple = MongoDefaults.WaitQueueMultiple;
     _waitQueueSize = MongoDefaults.WaitQueueSize;
     _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
     _wTimeout = null;
 }
 /// <summary>
 /// Initializes a new instance of the JsonReaderSettings class.
 /// </summary>
 /// <param name="closeInput">Whether to close the input stream when the reader is closed.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 public JsonReaderSettings(
     bool closeInput,
     GuidRepresentation guidRepresentation
 ) {
     this.closeInput = closeInput;
     this.guidRepresentation = guidRepresentation;
 }
        // constructors
        /// <summary>
        /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead.
        /// </summary>
        public MongoServerSettings()
        {
            _connectionMode = ConnectionMode.Automatic;
            _connectTimeout = MongoDefaults.ConnectTimeout;
            _credentialsStore = new MongoCredentialsStore();
            _defaultCredentials = null;
            _guidRepresentation = MongoDefaults.GuidRepresentation;
            _ipv6 = false;
            _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
            _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
            _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
            _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
            _readPreference = ReadPreference.Primary;
            _replicaSetName = null;
            _secondaryAcceptableLatency = MongoDefaults.SecondaryAcceptableLatency;
            _servers = new List<MongoServerAddress> { new MongoServerAddress("localhost") };
            _socketTimeout = MongoDefaults.SocketTimeout;
            _useSsl = false;
            _verifySslCertificate = true;
            _waitQueueSize = MongoDefaults.ComputedWaitQueueSize;
            _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
#pragma warning disable 612, 618
            _writeConcern = MongoDefaults.SafeMode.WriteConcern;
#pragma warning restore
        }
 /// <summary>
 /// Creates a new instance of MongoDatabaseSettings.
 /// </summary>
 /// <param name="databaseName">The name of the database.</param>
 /// <param name="credentials">The credentials to access the database.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="safeMode">The safe mode to use.</param>
 /// <param name="slaveOk">Whether queries should be sent to secondary servers.</param>
 public MongoDatabaseSettings(string databaseName, MongoCredentials credentials, GuidRepresentation guidRepresentation, SafeMode safeMode, bool slaveOk)
 {
     _databaseName = databaseName;
     _credentials = credentials;
     _guidRepresentation = guidRepresentation;
     _safeMode = safeMode;
     _slaveOk = slaveOk;
 }
 /// <summary>
 /// Initializes a new instance of the BsonBinaryReaderSettings class.
 /// </summary>
 /// <param name="closeInput">Whether to close the input stream when the reader is closed.</param>
 /// <param name="fixOldBinarySubTypeOnInput">Whether to fix occurrences of the old binary subtype on input.</param>
 /// <param name="fixOldDateTimeMaxValueOnInput">Whether to fix occurrences of the old representation of DateTime.MaxValue on input.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="maxDocumentSize">The max document size.</param>
 public BsonBinaryReaderSettings(bool closeInput, bool fixOldBinarySubTypeOnInput, bool fixOldDateTimeMaxValueOnInput, GuidRepresentation guidRepresentation, int maxDocumentSize)
     : base(guidRepresentation)
 {
     this.closeInput = closeInput;
     this.fixOldBinarySubTypeOnInput = fixOldBinarySubTypeOnInput;
     this.fixOldDateTimeMaxValueOnInput = fixOldDateTimeMaxValueOnInput;
     this.maxDocumentSize = maxDocumentSize;
 }
 /// <summary>
 /// Creates a new instance of MongoDatabaseSettings.
 /// </summary>
 /// <param name="databaseName">The name of the database.</param>
 /// <param name="credentials">The credentials to access the database.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="safeMode">The safe mode to use.</param>
 /// <param name="slaveOk">Whether queries should be sent to secondary servers.</param>
 public MongoDatabaseSettings(string databaseName, MongoCredentials credentials, GuidRepresentation guidRepresentation, SafeMode safeMode, ReadPreference readPreference)
 {
     this.databaseName = databaseName;
     this.credentials = credentials;
     this.guidRepresentation = guidRepresentation;
     this.safeMode = safeMode;
     this.readPreference = readPreference;
 }
 // constructors
 /// <summary>
 /// Creates a new instance of MongoDatabaseSettings.
 /// </summary>
 /// <param name="server">The server to inherit settings from.</param>
 /// <param name="databaseName">The name of the database.</param>
 public MongoDatabaseSettings(MongoServer server, string databaseName)
 {
     var serverSettings = server.Settings;
     _databaseName = databaseName;
     _credentials = serverSettings.DefaultCredentials;
     _guidRepresentation = serverSettings.GuidRepresentation;
     _safeMode = serverSettings.SafeMode;
     _slaveOk = serverSettings.SlaveOk;
 }
 // constructors
 /// <summary>
 /// Creates a new instance of MongoDatabaseSettings.
 /// </summary>
 /// <param name="server">The server to inherit settings from.</param>
 /// <param name="databaseName">The name of the database.</param>
 public MongoDatabaseSettings(MongoServer server, string databaseName)
 {
     var serverSettings = server.Settings;
     this.databaseName = databaseName;
     this.credentials = serverSettings.DefaultCredentials;
     this.guidRepresentation = serverSettings.GuidRepresentation;
     this.safeMode = serverSettings.SafeMode;
     this.readPreference = serverSettings.ReadPreference;
 }
        public void ReadJson_should_return_expected_result_when_using_native_bson_reader(string json, GuidRepresentation guidRepresentation, string nullableHexBytes, BsonBinarySubType subType)
        {
            var subject = new BsonBinaryDataConverter();
            var expectedResult = nullableHexBytes == null ? null : new BsonBinaryData(BsonUtils.ParseHexString(nullableHexBytes), subType);

            var result = ReadJsonUsingNativeBsonReader<BsonBinaryData>(subject, ToBson(json, guidRepresentation), mustBeNested: true);

            result.Should().Be(expectedResult);
        }
Example #14
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the MongoCollectionSettings class.
 /// </summary>
 /// <param name="database">The database that contains the collection (some collection settings will be inherited from the database settings).</param>
 /// <param name="collectionName">The name of the collection.</param>
 /// <param name="defaultDocumentType">The default document type for the collection.</param>
 protected MongoCollectionSettings(MongoDatabase database, string collectionName, Type defaultDocumentType)
 {
     var databaseSettings = database.Settings;
     _collectionName = collectionName;
     _assignIdOnInsert = MongoDefaults.AssignIdOnInsert;
     _defaultDocumentType = defaultDocumentType;
     _guidRepresentation = databaseSettings.GuidRepresentation;
     _safeMode = databaseSettings.SafeMode;
     _slaveOk = databaseSettings.SlaveOk;
 }
 /// <summary>
 /// Initializes a new instance of the BsonBinaryReaderSettings class.
 /// </summary>
 /// <param name="closeInput">Whether to close the input stream when the reader is closed.</param>
 /// <param name="fixOldBinarySubTypeOnInput">Whether to fix occurrences of the old binary subtype on input.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="maxDocumentSize">The max document size.</param>
 public BsonBinaryReaderSettings(
     bool closeInput,
     bool fixOldBinarySubTypeOnInput,
     GuidRepresentation guidRepresentation,
     int maxDocumentSize
 ) {
     this.closeInput = closeInput;
     this.fixOldBinarySubTypeOnInput = fixOldBinarySubTypeOnInput;
     this.guidRepresentation = guidRepresentation;
     this.maxDocumentSize = maxDocumentSize;
 }
 /// <summary>
 /// Initializes a new instance of the JsonWriterSettings class.
 /// </summary>
 /// <param name="closeOutput">Whether to close the output when the writer is closed.</param>
 /// <param name="encoding">The output Encoding.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="indent">Whether to indent the output.</param>
 /// <param name="indentChars">The indentation characters.</param>
 /// <param name="newLineChars">The new line characters.</param>
 /// <param name="outputMode">The output mode.</param>
 /// <param name="shellVersion">The version of the shell to target.</param>
 public JsonWriterSettings(bool closeOutput, Encoding encoding, GuidRepresentation guidRepresentation, bool indent, string indentChars, string newLineChars, JsonOutputMode outputMode, Version shellVersion)
     : base(guidRepresentation)
 {
     _closeOutput = closeOutput;
     _encoding = encoding;
     _indent = indent;
     _indentChars = indentChars;
     _newLineChars = newLineChars;
     _outputMode = outputMode;
     _shellVersion = shellVersion;
 }
 /// <summary>
 /// Creates a new instance of MongoDatabaseSettings. Usually you would call MongoServer.CreateDatabaseSettings instead.
 /// </summary>
 /// <param name="databaseName">The name of the database.</param>
 /// <param name="credentials">The credentials to access the database.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="safeMode">The safe mode to use.</param>
 /// <param name="slaveOk">Whether queries should be sent to secondary servers.</param>
 public MongoDatabaseSettings(
     string databaseName,
     MongoCredentials credentials,
     GuidRepresentation guidRepresentation,
     SafeMode safeMode,
     bool slaveOk
 ) {
     this.databaseName = databaseName;
     this.credentials = credentials;
     this.guidRepresentation = guidRepresentation;
     this.safeMode = safeMode;
     this.slaveOk = slaveOk;
 }
 /// <summary>
 /// Reads BSON binary data from the reader.
 /// </summary>
 /// <param name="bytes">The binary data.</param>
 /// <param name="subType">The binary data subtype.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 public override void ReadBinaryData(
     out byte[] bytes,
     out BsonBinarySubType subType,
     out GuidRepresentation guidRepresentation
 ) {
     if (disposed) { ThrowObjectDisposedException(); }
     VerifyBsonType("ReadBinaryData", BsonType.Binary);
     state = GetNextState();
     var binaryData = currentValue.AsBsonBinaryData;
     bytes = binaryData.Bytes;
     subType = binaryData.SubType;
     guidRepresentation = binaryData.GuidRepresentation;
 }
 protected MongoCollectionSettings(
     string collectionName,
     bool assignIdOnInsert,
     Type defaultDocumentType,
     GuidRepresentation guidRepresentation,
     SafeMode safeMode,
     bool slaveOk
 ) {
     this.collectionName = collectionName;
     this.assignIdOnInsert = assignIdOnInsert;
     this.defaultDocumentType = defaultDocumentType;
     this.guidRepresentation = guidRepresentation;
     this.safeMode = safeMode;
     this.slaveOk = slaveOk;
 }
 /// <summary>
 /// Initializes a new instance of the JsonWriterSettings class.
 /// </summary>
 /// <param name="closeOutput">Whether to close the output when the writer is closed.</param>
 /// <param name="encoding">The output Encoding.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="indent">Whether to indent the output.</param>
 /// <param name="indentChars">The indentation characters.</param>
 /// <param name="newLineChars">The new line characters.</param>
 /// <param name="outputMode">The output mode.</param>
 public JsonWriterSettings(
     bool closeOutput,
     Encoding encoding,
     GuidRepresentation guidRepresentation,
     bool indent,
     string indentChars,
     string newLineChars,
     JsonOutputMode outputMode
 ) 
     : base(guidRepresentation) {
     this.closeOutput = closeOutput;
     this.encoding = encoding;
     this.indent = indent;
     this.indentChars = indentChars;
     this.newLineChars = newLineChars;
     this.outputMode = outputMode;
 }
Example #21
0
 /// <summary>
 /// Creates a new instance of MongoDatabaseSettings.
 /// </summary>
 /// <param name="databaseName">The name of the database.</param>
 /// <param name="credentials">The credentials to access the database.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="safeMode">The safe mode to use.</param>
 /// <param name="slaveOk">Whether queries should be sent to secondary servers.</param>
 public MongoDatabaseSettings(
     string databaseName,
     MongoCredentials credentials,
     GuidRepresentation guidRepresentation,
     SafeMode safeMode,
     bool slaveOk)
 {
     if (databaseName == "admin" && credentials != null && !credentials.Admin)
     {
         throw new ArgumentOutOfRangeException("Credentials for the admin database must have the admin flag set to true.");
     }
     _databaseName = databaseName;
     _credentials = credentials;
     _guidRepresentation = guidRepresentation;
     _safeMode = safeMode;
     _slaveOk = slaveOk;
 }
 /// <summary>
 /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead.
 /// </summary>
 public MongoServerSettings() {
     connectionMode = ConnectionMode.Direct;
     connectTimeout = MongoDefaults.ConnectTimeout;
     defaultCredentials = null;
     guidRepresentation = MongoDefaults.GuidRepresentation;
     ipv6 = false;
     maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
     maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
     maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
     minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
     replicaSetName = null;
     safeMode = MongoDefaults.SafeMode;
     servers = null;
     slaveOk = false;
     socketTimeout = MongoDefaults.SocketTimeout;
     waitQueueSize = MongoDefaults.ComputedWaitQueueSize;
     waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
 }
        // constructors
        /// <summary>
        /// Creates a new instance of MongoDatabaseSettings.
        /// </summary>
        /// <param name="server">The server to inherit settings from.</param>
        /// <param name="databaseName">The name of the database.</param>
        public MongoDatabaseSettings(MongoServer server, string databaseName)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (databaseName == null)
            {
                throw new ArgumentNullException("databaseName");
            }

            var serverSettings = server.Settings;
            _databaseName = databaseName;
            _credentials = serverSettings.GetCredentials(databaseName);
            _guidRepresentation = serverSettings.GuidRepresentation;
            _readPreference = serverSettings.ReadPreference;
            _writeConcern = serverSettings.WriteConcern;
        }
 /// <summary>
 /// Converts a byte array to a Guid.
 /// </summary>
 /// <param name="bytes">The byte array.</param>
 /// <param name="representation">The representation of the Guid in the byte array.</param>
 /// <returns>A Guid.</returns>
 public static Guid FromBytes(byte[] bytes, GuidRepresentation representation)
 {
     if (bytes.Length != 16)
     {
         var message = string.Format("Length of byte array must be 16, not {0}.", bytes.Length);
         throw new ArgumentException(message);
     }
     bytes = (byte[])bytes.Clone();
     switch (representation)
     {
         case GuidRepresentation.CSharpLegacy:
             if (!BitConverter.IsLittleEndian)
             {
                 Array.Reverse(bytes, 0, 4);
                 Array.Reverse(bytes, 4, 2);
                 Array.Reverse(bytes, 6, 2);
             }
             break;
         case GuidRepresentation.JavaLegacy:
             Array.Reverse(bytes, 0, 8);
             Array.Reverse(bytes, 8, 8);
             if (BitConverter.IsLittleEndian)
             {
                 Array.Reverse(bytes, 0, 4);
                 Array.Reverse(bytes, 4, 2);
                 Array.Reverse(bytes, 6, 2);
             }
             break;
         case GuidRepresentation.PythonLegacy:
         case GuidRepresentation.Standard:
             if (BitConverter.IsLittleEndian)
             {
                 Array.Reverse(bytes, 0, 4);
                 Array.Reverse(bytes, 4, 2);
                 Array.Reverse(bytes, 6, 2);
             }
             break;
         case GuidRepresentation.Unspecified:
             throw new InvalidOperationException("Unable to convert byte array to Guid because GuidRepresentation is Unspecified.");
         default:
             throw new BsonInternalException("Unexpected GuidRepresentation.");
     }
     return new Guid(bytes);
 }
 // constructors
 /// <summary>
 /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead.
 /// </summary>
 public MongoServerSettings()
 {
     _connectionMode = ConnectionMode.Direct;
     _connectTimeout = MongoDefaults.ConnectTimeout;
     _credentialsStore = new MongoCredentialsStore();
     _defaultCredentials = null;
     _guidRepresentation = MongoDefaults.GuidRepresentation;
     _ipv6 = false;
     _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
     _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
     _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
     _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
     _replicaSetName = null;
     _safeMode = MongoDefaults.SafeMode;
     _servers = null;
     _slaveOk = false;
     _socketTimeout = MongoDefaults.SocketTimeout;
     _waitQueueSize = MongoDefaults.ComputedWaitQueueSize;
     _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
 }
 // constructors
 /// <summary>
 /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead.
 /// </summary>
 public MongoServerSettings()
 {
     _connectionMode = ConnectionMode.Direct;
     _connectTimeout = MongoDefaults.ConnectTimeout;
     _credentialsStore = new MongoCredentialsStore();
     _defaultCredentials = null;
     _guidRepresentation = MongoDefaults.GuidRepresentation;
     _ipv6 = false;
     _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
     _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
     _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
     _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
     _readPreference = ReadPreference.Primary;
     _replicaSetName = null;
     _safeMode = MongoDefaults.SafeMode;
     _servers = new List<MongoServerAddress> { new MongoServerAddress("localhost") };
     _serversReadOnly = new ReadOnlyCollection<MongoServerAddress>(_servers);
     _socketTimeout = MongoDefaults.SocketTimeout;
     _waitQueueSize = MongoDefaults.ComputedWaitQueueSize;
     _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
 }
 /// <summary>
 /// Converts a Guid to a byte array.
 /// </summary>
 /// <param name="guid">The Guid.</param>
 /// <param name="representation">The representation of the Guid in the byte array.</param>
 /// <returns>A byte array.</returns>
 public static byte[] ToBytes(Guid guid, GuidRepresentation representation)
 {
     var bytes = (byte[])guid.ToByteArray().Clone();
     switch (representation)
     {
         case GuidRepresentation.CSharpLegacy:
             if (!BitConverter.IsLittleEndian)
             {
                 Array.Reverse(bytes, 0, 4);
                 Array.Reverse(bytes, 4, 2);
                 Array.Reverse(bytes, 6, 2);
             }
             break;
         case GuidRepresentation.JavaLegacy:
             if (BitConverter.IsLittleEndian)
             {
                 Array.Reverse(bytes, 0, 4);
                 Array.Reverse(bytes, 4, 2);
                 Array.Reverse(bytes, 6, 2);
             }
             Array.Reverse(bytes, 0, 8);
             Array.Reverse(bytes, 8, 8);
             break;
         case GuidRepresentation.PythonLegacy:
         case GuidRepresentation.Standard:
             if (BitConverter.IsLittleEndian)
             {
                 Array.Reverse(bytes, 0, 4);
                 Array.Reverse(bytes, 4, 2);
                 Array.Reverse(bytes, 6, 2);
             }
             break;
         case GuidRepresentation.Unspecified:
             throw new InvalidOperationException("Unable to convert Guid to byte array because GuidRepresentation is Unspecified.");
         default:
             throw new BsonInternalException("Unexpected GuidRepresentation.");
     }
     return bytes;
 }
        // constructors
        /// <summary>
        /// Initializes a new instance of the MongoCollectionSettings class.
        /// </summary>
        /// <param name="database">The database that contains the collection (some collection settings will be inherited from the database settings).</param>
        /// <param name="collectionName">The name of the collection.</param>
        /// <param name="defaultDocumentType">The default document type for the collection.</param>
        protected MongoCollectionSettings(MongoDatabase database, string collectionName, Type defaultDocumentType)
        {
            if (database == null)
            {
                throw new ArgumentNullException("database");
            }
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (defaultDocumentType == null)
            {
                throw new ArgumentNullException("defaultDocumentType");
            }

            var databaseSettings = database.Settings;
            _collectionName = collectionName;
            _assignIdOnInsert = MongoDefaults.AssignIdOnInsert;
            _defaultDocumentType = defaultDocumentType;
            _guidRepresentation = databaseSettings.GuidRepresentation;
            _readPreference = databaseSettings.ReadPreference;
            _writeConcern = databaseSettings.WriteConcern;
        }
Example #29
0
 /// <summary>
 /// Initializes a new instance of the BsonReaderSettings class.
 /// </summary>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 protected BsonReaderSettings(
     GuidRepresentation guidRepresentation
     )
 {
     this.guidRepresentation = guidRepresentation;
 }
        public void WriteJson_should_have_expected_result_when_using_native_bson_writer(string nullableHexBytes, BsonBinarySubType subType, string expectedResult, GuidRepresentation resultGuidRepresentation)
        {
            var subject = new BsonBinaryDataConverter();
            var value   = nullableHexBytes == null ? null : new BsonBinaryData(BsonUtils.ParseHexString(nullableHexBytes), subType);

            var result = WriteJsonUsingNativeBsonWriter(subject, value, mustBeNested: true);

            result.Should().Equal(ToBson(expectedResult, resultGuidRepresentation));
        }
        public void ReadJson_should_return_expected_result_when_using_wrapped_bson_reader(string json, GuidRepresentation guidRepresentation, string nullableHexBytes, BsonBinarySubType subType)
        {
            var subject        = new BsonBinaryDataConverter();
            var expectedResult = nullableHexBytes == null ? null : new BsonBinaryData(BsonUtils.ParseHexString(nullableHexBytes), subType);

            var result = ReadJsonUsingWrappedBsonReader <BsonBinaryData>(subject, ToBson(json, guidRepresentation), mustBeNested: true, guidRepresentation: guidRepresentation);

            result.Should().Be(expectedResult);
        }
        protected T ReadJsonUsingWrappedBsonReader <T>(Newtonsoft.Json.JsonConverter converter, byte[] bson, bool mustBeNested = false, GuidRepresentation guidRepresentation = GuidRepresentation.CSharpLegacy)
        {
            var readerSettings = new BsonBinaryReaderSettings {
                GuidRepresentation = guidRepresentation
            };

            using (var stream = new MemoryStream(bson))
                using (var wrappedReader = new BsonBinaryReader(stream, readerSettings))
                    using (var reader = new BsonReaderAdapter(wrappedReader))
                    {
                        return(ReadJson <T>(converter, reader, mustBeNested));
                    }
        }
        /// <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;
        }
Example #34
0
        public void Serialize_Guid_should_have_expected_result(string stringValue, GuidRepresentation guidRepresentation, string expectedResult)
        {
            var value = new Newtonsoft.Json.Linq.JValue(Guid.Parse(stringValue));

            AssertSerializesTheSame(value, guidRepresentation);
        }
 public void WriteBinaryData(
     byte[] bytes,
     BsonBinarySubType subType,
     GuidRepresentation guidRepresentation)
 {
     var binaryData = new BsonBinaryData(bytes, subType, guidRepresentation);
     WriteBinaryData(binaryData);
 }
        // public methods
        /// <summary>
        /// Parses a URL and sets all settings to match the URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        public void Parse(string url)
        {
            ResetValues();
            const string serverPattern = @"((\[[^]]+?\]|[^:,/]+)(:\d+)?)";
            const string pattern       =
                @"^mongodb://" +
                @"((?<username>[^:]+):(?<password>[^@]+)@)?" +
                @"(?<servers>" + serverPattern + "(," + serverPattern + ")*)" +
                @"(/(?<database>[^?]+)?(\?(?<query>.*))?)?$";
            Match match = Regex.Match(url, pattern);

            if (match.Success)
            {
                string username     = Uri.UnescapeDataString(match.Groups["username"].Value);
                string password     = Uri.UnescapeDataString(match.Groups["password"].Value);
                string servers      = match.Groups["servers"].Value;
                string databaseName = match.Groups["database"].Value;
                string query        = match.Groups["query"].Value;

                if (username != "" && password != "")
                {
                    _defaultCredentials = new MongoCredentials(username, password);
                }
                else
                {
                    _defaultCredentials = null;
                }

                if (servers != "")
                {
                    List <MongoServerAddress> addresses = new List <MongoServerAddress>();
                    foreach (string server in servers.Split(','))
                    {
                        var address = MongoServerAddress.Parse(server);
                        addresses.Add(address);
                    }
                    if (addresses.Count == 1)
                    {
                        _connectionMode = ConnectionMode.Direct;
                    }
                    else if (addresses.Count > 1)
                    {
                        _connectionMode = ConnectionMode.ReplicaSet;
                    }
                    _servers = addresses;
                }
                else
                {
                    throw new FormatException("Invalid connection string. Server missing.");
                }

                _databaseName = (databaseName != "") ? databaseName : null;

                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 "connect":
                            _connectionMode = ParseConnectionMode(name, value);
                            break;

                        case "connecttimeout":
                        case "connecttimeoutms":
                            _connectTimeout = ParseTimeSpan(name, value);
                            break;

                        case "fsync":
                            if (_safeMode == null)
                            {
                                _safeMode = new SafeMode(false);
                            }
                            _safeMode.FSync = ParseBoolean(name, 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":
                            if (_safeMode == null)
                            {
                                _safeMode = new SafeMode(false);
                            }
                            SafeMode.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 "replicaset":
                            _replicaSetName = value;
                            _connectionMode = ConnectionMode.ReplicaSet;
                            break;

                        case "safe":
                            if (_safeMode == null)
                            {
                                _safeMode = new SafeMode(false);
                            }
                            SafeMode.Enabled = ParseBoolean(name, value);
                            break;

                        case "slaveok":
                            _slaveOk = ParseBoolean(name, value);
                            break;

                        case "sockettimeout":
                        case "sockettimeoutms":
                            _socketTimeout = ParseTimeSpan(name, value);
                            break;

                        case "w":
                            if (_safeMode == null)
                            {
                                _safeMode = new SafeMode(false);
                            }
                            try
                            {
                                SafeMode.W = ParseInt32(name, value);
                            }
                            catch (FormatException)
                            {
                                SafeMode.WMode = value;
                            }
                            break;

                        case "waitqueuemultiple":
                            _waitQueueMultiple = ParseDouble(name, value);
                            _waitQueueSize     = 0;
                            break;

                        case "waitqueuesize":
                            _waitQueueMultiple = 0;
                            _waitQueueSize     = ParseInt32(name, value);
                            break;

                        case "waitqueuetimeout":
                        case "waitqueuetimeoutms":
                            _waitQueueTimeout = ParseTimeSpan(name, value);
                            break;

                        case "wtimeout":
                        case "wtimeoutms":
                            if (_safeMode == null)
                            {
                                _safeMode = new SafeMode(false);
                            }
                            SafeMode.WTimeout = ParseTimeSpan(name, value);
                            break;
                        }
                    }
                }
            }
            else
            {
                throw new FormatException(string.Format("Invalid connection string '{0}'.", url));
            }
        }
Example #37
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the BsonBinaryDataGuidGenerator class.
 /// </summary>
 /// <param name="guidRepresentation">The GuidRepresentation to use when generating new Id values.</param>
 public BsonBinaryDataGuidGenerator(GuidRepresentation guidRepresentation)
 {
     _guidRepresentation = guidRepresentation;
 }
Example #38
0
        /// <summary>
        /// Writes BSON binary data to the writer.
        /// </summary>
        /// <param name="bytes">The binary data.</param>
        /// <param name="subType">The binary data subtype.</param>
        /// <param name="guidRepresentation">The representation for Guids.</param>
        public override void WriteBinaryData(
            byte[] bytes,
            BsonBinarySubType subType,
            GuidRepresentation guidRepresentation)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteBinaryData", BsonWriterState.Value, BsonWriterState.Initial);
            }

            if (_jsonWriterSettings.OutputMode == JsonOutputMode.Shell)
            {
                WriteNameHelper(Name);
                switch (subType)
                {
                case BsonBinarySubType.UuidLegacy:
                case BsonBinarySubType.UuidStandard:
                    if (bytes.Length != 16)
                    {
                        var message = string.Format("Length of binary subtype {0} must be 16, not {1}.", subType, bytes.Length);
                        throw new ArgumentException(message);
                    }
                    if (subType == BsonBinarySubType.UuidLegacy && guidRepresentation == GuidRepresentation.Standard)
                    {
                        throw new ArgumentException("GuidRepresentation for binary subtype UuidLegacy must not be Standard.");
                    }
                    if (subType == BsonBinarySubType.UuidStandard && guidRepresentation != GuidRepresentation.Standard)
                    {
                        var message = string.Format("GuidRepresentation for binary subtype UuidStandard must be Standard, not {0}.", guidRepresentation);
                        throw new ArgumentException(message);
                    }
                    if (_jsonWriterSettings.ShellVersion >= new Version(2, 0, 0))
                    {
                        if (guidRepresentation == GuidRepresentation.Unspecified)
                        {
                            var s     = BsonUtils.ToHexString(bytes);
                            var parts = new string[]
                            {
                                s.Substring(0, 8),
                                s.Substring(8, 4),
                                s.Substring(12, 4),
                                s.Substring(16, 4),
                                s.Substring(20, 12)
                            };
                            _textWriter.Write("HexData({0}, \"{1}\")", (int)subType, string.Join("-", parts));
                        }
                        else
                        {
                            string uuidConstructorName;
                            switch (guidRepresentation)
                            {
                            case GuidRepresentation.CSharpLegacy: uuidConstructorName = "CSUUID"; break;

                            case GuidRepresentation.JavaLegacy: uuidConstructorName = "JUUID"; break;

                            case GuidRepresentation.PythonLegacy: uuidConstructorName = "PYUUID"; break;

                            case GuidRepresentation.Standard: uuidConstructorName = "UUID"; break;

                            default: throw new BsonInternalException("Unexpected GuidRepresentation");
                            }
                            var guid = GuidConverter.FromBytes(bytes, guidRepresentation);
                            _textWriter.Write("{0}(\"{1}\")", uuidConstructorName, guid.ToString());
                        }
                    }
                    else
                    {
                        _textWriter.Write("new BinData({0}, \"{1}\")", (int)subType, Convert.ToBase64String(bytes));
                    }
                    break;

                default:
                    _textWriter.Write("new BinData({0}, \"{1}\")", (int)subType, Convert.ToBase64String(bytes));
                    break;
                }
            }
            else
            {
                WriteStartDocument();
                WriteString("$binary", Convert.ToBase64String(bytes));
                WriteString("$type", ((int)subType).ToString("x2"));
                WriteEndDocument();
            }

            State = GetNextState();
        }
Example #39
0
 /// <summary>
 /// Reads a BSON binary data element from the reader.
 /// </summary>
 /// <param name="name">The name of the element.</param>
 /// <param name="bytes">The binary data.</param>
 /// <param name="subType">The binary data subtype.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 public void ReadBinaryData(string name, out byte[] bytes, out BsonBinarySubType subType, out GuidRepresentation guidRepresentation)
 {
     VerifyName(name);
     ReadBinaryData(out bytes, out subType, out guidRepresentation);
 }
Example #40
0
 /// <summary>
 /// Reads BSON binary data from the reader.
 /// </summary>
 /// <param name="bytes">The binary data.</param>
 /// <param name="subType">The binary data subtype.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 public abstract void ReadBinaryData(out byte[] bytes, out BsonBinarySubType subType, out GuidRepresentation guidRepresentation);
Example #41
0
 /// <summary>
 /// Initializes a new instance of the BsonWriterSettings class.
 /// </summary>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 protected BsonWriterSettings(GuidRepresentation guidRepresentation)
 {
     _guidRepresentation = guidRepresentation;
 }
#pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary
        /// <summary>
        /// Writes BSON binary data to the writer.
        /// </summary>
        /// <param name="bytes">The binary data.</param>
        /// <param name="subType">The binary data subtype.</param>
        /// <param name="guidRepresentation">The representation for Guids.</param>
        public override void WriteBinaryData(
            byte[] bytes,
            BsonBinarySubType subType,
            GuidRepresentation guidRepresentation)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("BsonBinaryWriter");
            }
            if (_state != BsonWriterState.Value)
            {
                ThrowInvalidState("WriteBinaryData", BsonWriterState.Value);
            }

            switch (subType)
            {
            case BsonBinarySubType.OldBinary:
                if (_binaryWriterSettings.FixOldBinarySubTypeOnOutput)
                {
                    subType = BsonBinarySubType.Binary;     // replace obsolete OldBinary with new Binary sub type
                }
                break;

            case BsonBinarySubType.UuidLegacy:
            case BsonBinarySubType.UuidStandard:
                if (_binaryWriterSettings.GuidRepresentation != GuidRepresentation.Unspecified)
                {
                    var expectedSubType = (_binaryWriterSettings.GuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
                    if (subType != expectedSubType)
                    {
                        var message = string.Format(
                            "The GuidRepresentation for the writer is {0}, which requires the subType argument to be {1}, not {2}.",
                            _binaryWriterSettings.GuidRepresentation, expectedSubType, subType);
                        throw new BsonSerializationException(message);
                    }
                    if (guidRepresentation != _binaryWriterSettings.GuidRepresentation)
                    {
                        var message = string.Format(
                            "The GuidRepresentation for the writer is {0}, which requires the the guidRepresentation argument to also be {0}, not {1}.",
                            _binaryWriterSettings.GuidRepresentation, guidRepresentation);
                        throw new BsonSerializationException(message);
                    }
                }
                break;
            }

            _buffer.WriteByte((byte)BsonType.Binary);
            WriteNameHelper();
            if (subType == BsonBinarySubType.OldBinary)
            {
                // sub type OldBinary has two sizes (for historical reasons)
                _buffer.WriteInt32(bytes.Length + 4);
                _buffer.WriteByte((byte)subType);
                _buffer.WriteInt32(bytes.Length);
            }
            else
            {
                _buffer.WriteInt32(bytes.Length);
                _buffer.WriteByte((byte)subType);
            }
            _buffer.WriteBytes(bytes);

            _state = GetNextState();
        }
 public BsonDocumentWriterSettings(GuidRepresentation guidRepresentation)
     : base(guidRepresentation)
 {
 }
 /// <summary>
 /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead.
 /// </summary>
 /// <param name="connectionMode">The connection mode (Direct or ReplicaSet).</param>
 /// <param name="connectTimeout">The connect timeout.</param>
 /// <param name="defaultCredentials">The default credentials.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <param name="ipv6">Whether to use IPv6.</param>
 /// <param name="maxConnectionIdleTime">The max connection idle time.</param>
 /// <param name="maxConnectionLifeTime">The max connection life time.</param>
 /// <param name="maxConnectionPoolSize">The max connection pool size.</param>
 /// <param name="minConnectionPoolSize">The min connection pool size.</param>
 /// <param name="replicaSetName">The name of the replica set.</param>
 /// <param name="safeMode">The safe mode.</param>
 /// <param name="servers">The server addresses (normally one unless it is the seed list for connecting to a replica set).</param>
 /// <param name="slaveOk">Whether queries should be sent to secondary servers.</param>
 /// <param name="socketTimeout">The socket timeout.</param>
 /// <param name="waitQueueSize">The wait queue size.</param>
 /// <param name="waitQueueTimeout">The wait queue timeout.</param>
 public MongoServerSettings(ConnectionMode connectionMode, TimeSpan connectTimeout, MongoCredentials defaultCredentials, GuidRepresentation guidRepresentation, bool ipv6, TimeSpan maxConnectionIdleTime, TimeSpan maxConnectionLifeTime, int maxConnectionPoolSize, int minConnectionPoolSize, string replicaSetName, SafeMode safeMode, IEnumerable <MongoServerAddress> servers, bool slaveOk, TimeSpan socketTimeout, int waitQueueSize, TimeSpan waitQueueTimeout)
 {
     this.connectionMode     = connectionMode;
     this.connectTimeout     = connectTimeout;
     this.defaultCredentials = defaultCredentials;
     this.guidRepresentation = guidRepresentation;
     this.ipv6 = ipv6;
     this.maxConnectionIdleTime = maxConnectionIdleTime;
     this.maxConnectionLifeTime = maxConnectionLifeTime;
     this.maxConnectionPoolSize = maxConnectionPoolSize;
     this.minConnectionPoolSize = minConnectionPoolSize;
     this.replicaSetName        = replicaSetName;
     this.safeMode         = safeMode;
     this.servers          = servers;
     this.slaveOk          = slaveOk;
     this.socketTimeout    = socketTimeout;
     this.waitQueueSize    = waitQueueSize;
     this.waitQueueTimeout = waitQueueTimeout;
 }
Example #45
0
 public GuidMode(GuidRepresentationMode guidRepresentationMode, GuidRepresentation guidRepresentation = GuidRepresentation.Unspecified)
 {
     _guidRepresentationMode = guidRepresentationMode;
     _guidRepresentation     = guidRepresentation;
 }
        protected byte[] Serialize <T>(IBsonSerializer <T> serializer, T value, bool mustBeNested = false, GuidRepresentation guidRepresentation = GuidRepresentation.Unspecified)
        {
            using (var memoryStream = new MemoryStream())
                using (var writer = new BsonBinaryWriter(memoryStream, new BsonBinaryWriterSettings {
                    GuidRepresentation = guidRepresentation
                }))
                {
                    if (mustBeNested)
                    {
                        writer.WriteStartDocument();
                        writer.WriteName("x");
                    }

                    var context = BsonSerializationContext.CreateRoot(writer);
                    serializer.Serialize(context, value);

                    if (mustBeNested)
                    {
                        writer.WriteEndDocument();
                    }

                    return(memoryStream.ToArray());
                }
        }
Example #47
0
 // constructors
 public GuidMode()
 {
     _guidRepresentationMode = GuidRepresentationMode.V2;
     _guidRepresentation     = GuidRepresentation.CSharpLegacy;
 }
Example #48
0
 /// <summary>
 /// Initializes a new instance of the BsonBinaryData class.
 /// </summary>
 /// <param name="guid">A Guid.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 public BsonBinaryData(Guid guid, GuidRepresentation guidRepresentation)
     : this(GuidConverter.ToBytes(guid, guidRepresentation), (guidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy, guidRepresentation)
 {
 }
Example #49
0
        // public static methods
        public static void Set(GuidRepresentationMode guidRepresentationMode, GuidRepresentation guidRepresentation = GuidRepresentation.Unspecified)
        {
            var mode = new GuidMode(guidRepresentationMode, guidRepresentation);

            mode.Set();
        }
Example #50
0
 /// <summary>
 /// Creates a new BsonBinaryData.
 /// </summary>
 /// <param name="guid">A Guid.</param>
 /// <param name="guidRepresentation">The representation for Guids.</param>
 /// <returns>A BsonBinaryData.</returns>
 public static BsonBinaryData Create(Guid guid, GuidRepresentation guidRepresentation)
 {
     return(new BsonBinaryData(guid, guidRepresentation));
 }
        protected byte[] WriteJsonUsingWrappedBsonWriter(Newtonsoft.Json.JsonConverter converter, object value, bool mustBeNested = false, GuidRepresentation guidRepresentation = GuidRepresentation.CSharpLegacy)
        {
            var wrappedWriterSettings = new BsonBinaryWriterSettings {
                GuidRepresentation = guidRepresentation
            };

            using (var stream = new MemoryStream())
                using (var wrappedWriter = new BsonBinaryWriter(stream, wrappedWriterSettings))
                    using (var writer = new BsonWriterAdapter(wrappedWriter))
                    {
                        WriteJson(converter, value, writer, mustBeNested);
                        return(stream.ToArray());
                    }
        }
Example #52
0
 public virtual void SetGuidRepresentation(GuidRepresentation guidRepresentation)
 {
     MongoDefaults.GuidRepresentation = guidRepresentation;
 }
        public void WriteJson_should_have_expected_result_when_using_wrapped_json_writer(string nullableHexBytes, BsonBinarySubType subType, string expectedResult, GuidRepresentation resultGuidRepresentation)
        {
            var subject = new BsonBinaryDataConverter();
            var value   = nullableHexBytes == null ? null : new BsonBinaryData(BsonUtils.ParseHexString(nullableHexBytes), subType, resultGuidRepresentation);

            var result = WriteJsonUsingWrappedJsonWriter(subject, value);

            result.Should().Be(expectedResult);
        }
Example #54
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);

            _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;
        }
        public void ReadJson_should_throw_when_reading_a_guid_using_native_bson_reader(string json, GuidRepresentation guidRepresentation)
        {
            var subject = new BsonBinaryDataConverter();

            Action action = () => { var _ = ReadJsonUsingNativeBsonReader <BsonBinaryData>(subject, ToBson(json, guidRepresentation), mustBeNested: true); };

            action.ShouldThrow <Newtonsoft.Json.JsonReaderException>();
        }
        public void When_uuidRepresentation_is_specified(string connectionString, GuidRepresentation representation)
        {
            var subject = new ConnectionString(connectionString);

            subject.UuidRepresentation.Should().Be(representation);
        }
Example #57
0
 public JsonReaderSettings(bool closeInput, GuidRepresentation guidRepresentation)
     : base(guidRepresentation)
 {
     _closeInput = closeInput;
 }
Example #58
0
        // constructors
        /// <summary>
        /// Creates a new instance of MongoUrl.
        /// </summary>
        /// <param name="url">The URL containing the settings.</param>
        public MongoUrl(string url)
        {
            _originalUrl = url;

            var builder = new MongoUrlBuilder(url); // parses url
            _allowInsecureTls = builder.AllowInsecureTls;
            _applicationName = builder.ApplicationName;
            _authenticationMechanism = builder.AuthenticationMechanism;
            _authenticationMechanismProperties = builder.AuthenticationMechanismProperties;
            _authenticationSource = builder.AuthenticationSource;
            _compressors = builder.Compressors;
#pragma warning disable CS0618 // Type or member is obsolete
            if (builder.ConnectionModeSwitch == ConnectionModeSwitch.UseConnectionMode)
            {
                _connectionMode = builder.ConnectionMode;
            }
            _connectionModeSwitch = builder.ConnectionModeSwitch;
#pragma warning restore CS0618 // Type or member is obsolete
            _connectTimeout = builder.ConnectTimeout;
            _databaseName = builder.DatabaseName;
#pragma warning disable CS0618 // Type or member is obsolete
            if (builder.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
            {
                _directConnection = builder.DirectConnection;
            }
#pragma warning restore CS0618 // Type or member is obsolete
            _fsync = builder.FSync;
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                _guidRepresentation = builder.GuidRepresentation;
            }
#pragma warning restore 618
            _heartbeatInterval = builder.HeartbeatInterval;
            _heartbeatTimeout = builder.HeartbeatTimeout;
            _ipv6 = builder.IPv6;
            _isResolved = builder.Scheme != ConnectionStringScheme.MongoDBPlusSrv;
            _journal = builder.Journal;
            _localThreshold = builder.LocalThreshold;
            _maxConnectionIdleTime = builder.MaxConnectionIdleTime;
            _maxConnectionLifeTime = builder.MaxConnectionLifeTime;
            _maxConnectionPoolSize = builder.MaxConnectionPoolSize;
            _minConnectionPoolSize = builder.MinConnectionPoolSize;
            _password = builder.Password;
            _readConcernLevel = builder.ReadConcernLevel;
            _readPreference = builder.ReadPreference;
            _replicaSetName = builder.ReplicaSetName;
            _retryReads = builder.RetryReads;
            _retryWrites = builder.RetryWrites;
            _scheme = builder.Scheme;
            _servers = builder.Servers;
            _serverSelectionTimeout = builder.ServerSelectionTimeout;
            _socketTimeout = builder.SocketTimeout;
            _tlsDisableCertificateRevocationCheck = builder.TlsDisableCertificateRevocationCheck;
            _username = builder.Username;
            _useTls = builder.UseTls;
            _w = builder.W;
#pragma warning disable 618
            _waitQueueMultiple = builder.WaitQueueMultiple;
            _waitQueueSize = builder.WaitQueueSize;
#pragma warning restore 618
            _waitQueueTimeout = builder.WaitQueueTimeout;
            _wTimeout = builder.WTimeout;
            _url = builder.ToString(); // keep canonical form
        }
 public void WriteBinaryData(
     string name,
     byte[] bytes,
     BsonBinarySubType subType,
     GuidRepresentation guidRepresentation)
 {
     WriteName(name);
     WriteBinaryData(bytes, subType, guidRepresentation);
 }
Example #60
0
 /// <summary>
 /// Writes a BSON binary data element to the writer.
 /// </summary>
 /// <param name="name">The name of the element.</param>
 /// <param name="bytes">The binary data.</param>
 /// <param name="subType">The binary data subtype.</param>
 /// <param name="guidRepresentation">The respresentation for Guids.</param>
 public abstract void WriteBinaryData(
     string name,
     byte[] bytes,
     BsonBinarySubType subType,
     GuidRepresentation guidRepresentation
     );