示例#1
0
 // constructors
 internal MongoReplyMessage(BsonBinaryReaderSettings readerSettings, IBsonSerializer serializer, IBsonSerializationOptions serializationOptions)
     : base(MessageOpcode.Reply)
 {
     _readerSettings       = readerSettings;
     _serializer           = serializer;
     _serializationOptions = serializationOptions;
 }
 public static BsonReader Create(
     BsonBuffer buffer,
     BsonBinaryReaderSettings settings
 )
 {
     return new BsonBinaryReader(buffer, settings);
 }
示例#3
0
        private TResult ProcessCommandResult(ConnectionId connectionId, RawBsonDocument rawBsonDocument)
        {
            var binaryReaderSettings = new BsonBinaryReaderSettings
            {
                Encoding           = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict),
                GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy)
            };

            BsonValue writeConcernError;

            if (rawBsonDocument.TryGetValue("writeConcernError", out writeConcernError))
            {
                var message            = writeConcernError["errmsg"].AsString;
                var response           = rawBsonDocument.Materialize(binaryReaderSettings);
                var writeConcernResult = new WriteConcernResult(response);
                throw new MongoWriteConcernException(connectionId, message, writeConcernResult);
            }

            using (var stream = new ByteBufferStream(rawBsonDocument.Slice, ownsBuffer: false))
                using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(reader);
                    return(_resultSerializer.Deserialize(context));
                }
        }
示例#4
0
 // constructors
 public BulkDeleteOperationArgs(
     string collectionName,
     string databaseName,
     int maxBatchCount,
     int maxBatchLength,
     int maxDocumentSize,
     int maxWireDocumentSize,
     bool isOrdered,
     BsonBinaryReaderSettings readerSettings,
     IEnumerable <DeleteRequest> requests,
     WriteConcern writeConcern,
     BsonBinaryWriterSettings writerSettings)
     : base(
         collectionName,
         databaseName,
         maxBatchCount,
         maxBatchLength,
         maxDocumentSize,
         maxWireDocumentSize,
         isOrdered,
         readerSettings,
         requests.Cast <WriteRequest>(),
         writeConcern,
         writerSettings)
 {
 }
示例#5
0
        public static List <TDocument> DeserializeBatch <TDocument>(RawBsonArray batch, IBsonSerializer <TDocument> documentSerializer, MessageEncoderSettings messageEncoderSettings)
        {
            var documents = new List <TDocument>();

            var readerSettings = new BsonBinaryReaderSettings();

            if (messageEncoderSettings != null)
            {
                readerSettings.Encoding           = messageEncoderSettings.GetOrDefault(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
                readerSettings.GuidRepresentation = messageEncoderSettings.GetOrDefault(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
            }
            ;

            using (var stream = new ByteBufferStream(batch.Slice, ownsBuffer: false))
                using (var reader = new BsonBinaryReader(stream, readerSettings))
                {
                    // BSON requires that the top level object be a document, but an array looks close enough to a document that we can pretend it is one
                    reader.ReadStartDocument();
                    while (reader.ReadBsonType() != 0)
                    {
                        reader.SkipName(); // skip over the index pseudo names
                        var context  = BsonDeserializationContext.CreateRoot(reader);
                        var document = documentSerializer.Deserialize <TDocument>(context);
                        documents.Add(document);
                    }
                    reader.ReadEndDocument();
                }

            return(documents);
        }
        public void Deserialize_should_throw_when_representation_is_binary_and_guid_representation_is_unspecified(
            GuidRepresentationMode defaultGuidRepresentationMode,
            GuidRepresentation defaultGuidRepresentation,
            GuidRepresentation?readerGuidRepresentation)
        {
            GuidMode.Set(defaultGuidRepresentationMode, defaultGuidRepresentation);

            var subject        = new GuidSerializer(GuidRepresentation.Unspecified);
            var documentBytes  = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var readerSettings = new BsonBinaryReaderSettings();

            if (defaultGuidRepresentationMode == GuidRepresentationMode.V2 && readerGuidRepresentation.HasValue)
            {
#pragma warning disable 618
                readerSettings.GuidRepresentation = readerGuidRepresentation.Value;
#pragma warning restore 618
            }
            var reader = new BsonBinaryReader(new MemoryStream(documentBytes), readerSettings);
            reader.ReadStartDocument();
            reader.ReadName("x");
            var context = BsonDeserializationContext.CreateRoot(reader);
            var args    = new BsonDeserializationArgs();

            var exception = Record.Exception(() => subject.Deserialize(context, args));

            exception.Should().BeOfType <BsonSerializationException>();
        }
 // constructors
 public BulkInsertOperationArgs(
     Action <InsertRequest> assignId,
     bool checkElementNames,
     string collectionName,
     string databaseName,
     int maxBatchCount,
     int maxBatchLength,
     int maxDocumentSize,
     int maxWireDocumentSize,
     bool isOrdered,
     BsonBinaryReaderSettings readerSettings,
     IEnumerable <InsertRequest> requests,
     WriteConcern writeConcern,
     BsonBinaryWriterSettings writerSettings)
     : base(
         collectionName,
         databaseName,
         maxBatchCount,
         maxBatchLength,
         maxDocumentSize,
         maxWireDocumentSize,
         isOrdered,
         readerSettings,
         requests.Cast <WriteRequest>(),
         writeConcern,
         writerSettings)
 {
     _assignId          = assignId;
     _checkElementNames = checkElementNames;
 }
        public void Deserialize_binary_data_should_return_expected_result_when_guid_representation_is_specified(
            [ClassValues(typeof(GuidModeValues))]
            GuidMode mode,
            [Values(-1, GuidRepresentation.Unspecified)]
            GuidRepresentation readerGuidRepresentation,
            [Values(GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy, GuidRepresentation.Standard)]
            GuidRepresentation guidRepresentation)
        {
#pragma warning disable 618
            mode.Set();
            var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
            var subject = new ObjectSerializer(discriminatorConvention, guidRepresentation);
            var bytes   = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var subType = GuidConverter.GetSubType(guidRepresentation);
            bytes[11] = (byte)subType;
            var readerSettings = new BsonBinaryReaderSettings();
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                readerSettings.GuidRepresentation = readerGuidRepresentation == (GuidRepresentation)(-1) ? guidRepresentation : GuidRepresentation.Unspecified;
            }
            using (var memoryStream = new MemoryStream(bytes))
                using (var reader = new BsonBinaryReader(memoryStream, readerSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(reader);

                    reader.ReadStartDocument();
                    reader.ReadName("x");
                    var result = subject.Deserialize <object>(context);

                    var guidBytes      = bytes.Skip(12).Take(16).ToArray();
                    var expectedResult = GuidConverter.FromBytes(guidBytes, guidRepresentation);
                    result.Should().Be(expectedResult);
                }
#pragma warning restore 618
        }
示例#9
0
 internal MongoReplyMessage(
     BsonBinaryReaderSettings readerSettings
     )
     : base(MessageOpcode.Reply)
 {
     this.readerSettings = readerSettings;
 }
        public void ReadBinaryData_subtype_4_should_use_GuidRepresentation_Standard(GuidRepresentation guidRepresentation)
        {
            var settings = new BsonBinaryReaderSettings {
                GuidRepresentation = guidRepresentation
            };
            var bytes = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };

            using (var stream = new MemoryStream(bytes))
                using (var reader = new BsonBinaryReader(stream, settings))
                {
                    reader.ReadStartDocument();
                    var type          = reader.ReadBsonType();
                    var name          = reader.ReadName();
                    var binaryData    = reader.ReadBinaryData();
                    var endOfDocument = reader.ReadBsonType();
                    reader.ReadEndDocument();

                    name.Should().Be("x");
                    type.Should().Be(BsonType.Binary);
                    binaryData.SubType.Should().Be(BsonBinarySubType.UuidStandard);
                    binaryData.Bytes.Should().Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
                    binaryData.GuidRepresentation.Should().Be(GuidRepresentation.Standard);
                    endOfDocument.Should().Be(BsonType.EndOfDocument);
                    stream.Position.Should().Be(stream.Length);
                }
        }
        public void Deserialize_binary_data_should_throw_when_guid_representation_is_specified_and_sub_type_is_not_expected_sub_type(
            [ClassValues(typeof(GuidModeValues))]
            GuidMode mode,
            [Values(GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy, GuidRepresentation.Standard)]
            GuidRepresentation readerGuidRepresentation,
            [Values(GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy, GuidRepresentation.Standard)]
            GuidRepresentation guidRepresentation)
        {
#pragma warning disable 618
            mode.Set();
            var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
            var subject          = new ObjectSerializer(discriminatorConvention, guidRepresentation);
            var bytes            = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var incorrectSubType = guidRepresentation == GuidRepresentation.Standard ? BsonBinarySubType.UuidLegacy : BsonBinarySubType.UuidStandard;
            bytes[11] = (byte)incorrectSubType;
            var readerSettings = new BsonBinaryReaderSettings();
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                readerSettings.GuidRepresentation = readerGuidRepresentation;
            }
            using (var memoryStream = new MemoryStream(bytes))
                using (var reader = new BsonBinaryReader(memoryStream, readerSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(reader);

                    reader.ReadStartDocument();
                    reader.ReadName("x");
                    var exception = Record.Exception(() => subject.Deserialize <object>(context));

                    exception.Should().BeOfType <FormatException>();
                }
#pragma warning restore 618
        }
示例#12
0
        public QueryOperation(
            string databaseName,
            string collectionName,
            BsonBinaryReaderSettings readerSettings,
            BsonBinaryWriterSettings writerSettings,
            int batchSize,
            IMongoFields fields,
            QueryFlags flags,
            int limit,
            BsonDocument options,
            IMongoQuery query,
            ReadPreference readPreference,
            IBsonSerializationOptions serializationOptions,
            IBsonSerializer serializer,
            int skip)
            : base(databaseName, collectionName, readerSettings, writerSettings)
        {
            _batchSize            = batchSize;
            _fields               = fields;
            _flags                = flags;
            _limit                = limit;
            _options              = options;
            _query                = query;
            _readPreference       = readPreference;
            _serializationOptions = serializationOptions;
            _serializer           = serializer;
            _skip = skip;

            // since we're going to block anyway when a tailable cursor is temporarily out of data
            // we might as well do it as efficiently as possible
            if ((_flags & QueryFlags.TailableCursor) != 0)
            {
                _flags |= QueryFlags.AwaitData;
            }
        }
        public void Deserialize_should_throw_when_representation_is_binary_and_sub_type_does_not_match(
            GuidRepresentationMode defaultGuidRepresentationMode,
            GuidRepresentation defaultGuidRepresentation,
            GuidRepresentation serializerGuidRepresentation,
            GuidRepresentation?readerGuidRepresentation,
            BsonBinarySubType expectedSubType)
        {
            GuidMode.Set(defaultGuidRepresentationMode, defaultGuidRepresentation);

            var subject            = new GuidSerializer(serializerGuidRepresentation);
            var documentBytes      = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var nonMatchingSubType = expectedSubType == BsonBinarySubType.UuidLegacy ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;

            documentBytes[11] = (byte)nonMatchingSubType;
            var readerSettings = new BsonBinaryReaderSettings();

            if (defaultGuidRepresentationMode == GuidRepresentationMode.V2 && readerGuidRepresentation.HasValue)
            {
#pragma warning disable 618
                readerSettings.GuidRepresentation = readerGuidRepresentation.Value;
#pragma warning restore 618
            }
            var reader = new BsonBinaryReader(new MemoryStream(documentBytes), readerSettings);
            reader.ReadStartDocument();
            reader.ReadName("x");
            var context = BsonDeserializationContext.CreateRoot(reader);
            var args    = new BsonDeserializationArgs();

            var exception = Record.Exception(() => subject.Deserialize(context, args));

            exception.Should().BeOfType <FormatException>();
        }
 // constructors
 protected BulkWriteOperationArgs(
     string collectionName,
     string databaseName,
     int maxBatchCount,
     int maxBatchLength,
     int maxDocumentSize,
     int maxWireDocumentSize,
     bool isOrdered,
     BsonBinaryReaderSettings readerSettings,
     IEnumerable <WriteRequest> requests,
     WriteConcern writeConcern,
     BsonBinaryWriterSettings writerSettings)
 {
     _collectionName      = collectionName;
     _databaseName        = databaseName;
     _maxBatchCount       = maxBatchCount;
     _maxBatchLength      = maxBatchLength;
     _maxDocumentSize     = maxDocumentSize;
     _maxWireDocumentSize = maxWireDocumentSize;
     _isOrdered           = isOrdered;
     _readerSettings      = readerSettings;
     _requests            = requests;
     _writeConcern        = writeConcern;
     _writerSettings      = writerSettings;
 }
示例#15
0
        internal MongoReplyMessage <TDocument> ReceiveMessage <TDocument>(
            BsonBinaryReaderSettings readerSettings,
            IBsonSerializer <TDocument> serializer)
        {
            if (_state == MongoConnectionState.Closed)
            {
                throw new InvalidOperationException("Connection is closed.");
            }
            lock (_connectionLock)
            {
                try
                {
                    _lastUsedAt = DateTime.UtcNow;
                    var networkStream = GetNetworkStream();
                    var readTimeout   = (int)_serverInstance.Settings.SocketTimeout.TotalMilliseconds;
                    if (readTimeout != 0)
                    {
                        networkStream.ReadTimeout = readTimeout;
                    }

                    using (var byteBuffer = ByteBufferFactory.LoadLengthPrefixedDataFrom(networkStream))
                        using (var stream = new ByteBufferStream(byteBuffer, ownsByteBuffer: true))
                        {
                            var reply = new MongoReplyMessage <TDocument>(readerSettings, serializer);
                            reply.ReadFrom(stream);
                            return(reply);
                        }
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                    throw;
                }
            }
        }
        public void Deserializer_should_return_expected_result_when_representation_is_binary(
            GuidRepresentationMode defaultGuidRepresentationMode,
            GuidRepresentation defaultGuidRepresentation,
            GuidRepresentation serializerGuidRepresentation,
            GuidRepresentation readerGuidRepresentation,
            GuidRepresentation expectedGuidRepresentation)
        {
            GuidMode.Set(defaultGuidRepresentationMode, defaultGuidRepresentation);

            var subject         = new GuidSerializer(serializerGuidRepresentation);
            var documentBytes   = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var documentSubType = GuidConverter.GetSubType(expectedGuidRepresentation);

            documentBytes[11] = (byte)documentSubType;
            var readerSettings = new BsonBinaryReaderSettings();

            if (defaultGuidRepresentationMode == GuidRepresentationMode.V2)
            {
#pragma warning disable 618
                readerSettings.GuidRepresentation = readerGuidRepresentation;
#pragma warning restore 618
            }
            var reader = new BsonBinaryReader(new MemoryStream(documentBytes), readerSettings);
            reader.ReadStartDocument();
            reader.ReadName("x");
            var context = BsonDeserializationContext.CreateRoot(reader);
            var args    = new BsonDeserializationArgs();

            var result = subject.Deserialize(context, args);

            var guidBytes    = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            var expectedGuid = GuidConverter.FromBytes(guidBytes, expectedGuidRepresentation);
            result.Should().Be(expectedGuid);
        }
 // constructors
 public BulkMixedWriteOperation(
     Action <InsertRequest> assignId,
     bool checkElementNames,
     string collectionName,
     string databaseName,
     int maxBatchCount,
     int maxBatchLength,
     bool isOrdered,
     BsonBinaryReaderSettings readerSettings,
     IEnumerable <WriteRequest> requests,
     WriteConcern writeConcern,
     BsonBinaryWriterSettings writerSettings)
 {
     _assignId          = assignId;
     _checkElementNames = checkElementNames;
     _collectionName    = collectionName;
     _databaseName      = databaseName;
     _maxBatchCount     = maxBatchCount;
     _maxBatchLength    = maxBatchLength;
     _isOrdered         = isOrdered;
     _readerSettings    = readerSettings;
     _requests          = requests;
     _writeConcern      = writeConcern;
     _writerSettings    = writerSettings;
 }
 internal MongoReplyMessage <TDocument> ReceiveMessage <TDocument>(
     BsonBinaryReaderSettings readerSettings,
     IBsonSerializationOptions serializationOptions)
 {
     if (_state == MongoConnectionState.Closed)
     {
         throw new InvalidOperationException("Connection is closed.");
     }
     lock (_connectionLock)
     {
         try
         {
             using (var buffer = new BsonBuffer())
             {
                 var networkStream = GetNetworkStream();
                 var readTimeout   = (int)_serverInstance.Settings.SocketTimeout.TotalMilliseconds;
                 if (readTimeout != 0)
                 {
                     networkStream.ReadTimeout = readTimeout;
                 }
                 buffer.LoadFrom(networkStream);
                 var reply = new MongoReplyMessage <TDocument>(readerSettings);
                 reply.ReadFrom(buffer, serializationOptions);
                 return(reply);
             }
         }
         catch (Exception ex)
         {
             HandleException(ex);
             throw;
         }
     }
 }
示例#19
0
 protected ReadOperationBase(
     string databaseName,
     string collectionName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings)
     : base(databaseName, collectionName, readerSettings, writerSettings)
 {
 }
 public BsonBinaryReader(
     BsonBuffer buffer,
     BsonBinaryReaderSettings settings
 ) {
     this.buffer = buffer ?? new BsonBuffer();
     this.disposeBuffer = buffer == null; // only call Dispose if we allocated the buffer
     this.settings = settings;
     context = new BsonBinaryReaderContext(null, BsonReadState.Initial);
 }
 public static BsonReader Create(
     Stream stream,
     BsonBinaryReaderSettings settings
 )
 {
     BsonBuffer buffer = new BsonBuffer();
     buffer.LoadFrom(stream);
     return new BsonBinaryReader(buffer, settings);
 }
示例#22
0
 protected WriteOpcodeOperationBase(
     string databaseName,
     string collectionName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings,
     WriteConcern writeConcern)
     : base(databaseName, collectionName, readerSettings, writerSettings)
 {
     _writeConcern = writeConcern;
 }
示例#23
0
 /// <summary>
 /// Materializes the RawBsonDocument into a regular BsonDocument.
 /// </summary>
 /// <param name="binaryReaderSettings">The binary reader settings.</param>
 /// <returns>A BsonDocument.</returns>
 public BsonDocument Materialize(BsonBinaryReaderSettings binaryReaderSettings)
 {
     ThrowIfDisposed();
     using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
         using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
         {
             var context = BsonDeserializationContext.CreateRoot(reader);
             return(BsonDocumentSerializer.Instance.Deserialize(context));
         }
 }
示例#24
0
        protected WriteConcernResult SendMessageWithWriteConcern(
            MongoConnection connection,
            BsonBuffer buffer,
            int requestId,
            BsonBinaryReaderSettings readerSettings,
            BsonBinaryWriterSettings writerSettings,
            WriteConcern writeConcern)
        {
            CommandDocument getLastErrorCommand = null;

            if (writeConcern.Enabled)
            {
                var fsync    = (writeConcern.FSync == null) ? null : (BsonValue)writeConcern.FSync;
                var journal  = (writeConcern.Journal == null) ? null : (BsonValue)writeConcern.Journal;
                var w        = (writeConcern.W == null) ? null : writeConcern.W.ToGetLastErrorWValue();
                var wTimeout = (writeConcern.WTimeout == null) ? null : (BsonValue)(int)writeConcern.WTimeout.Value.TotalMilliseconds;

                getLastErrorCommand = new CommandDocument
                {
                    { "getlasterror", 1 }, // use all lowercase for backward compatibility
                    { "fsync", fsync, fsync != null },
                    { "j", journal, journal != null },
                    { "w", w, w != null },
                    { "wtimeout", wTimeout, wTimeout != null }
                };

                // piggy back on network transmission for message
                var getLastErrorMessage = new MongoQueryMessage(writerSettings, DatabaseName + ".$cmd", QueryFlags.None, 0, 1, getLastErrorCommand, null);
                getLastErrorMessage.WriteToBuffer(buffer);
            }

            connection.SendMessage(buffer, requestId);

            WriteConcernResult writeConcernResult = null;

            if (writeConcern.Enabled)
            {
                var writeConcernResultSerializer = BsonSerializer.LookupSerializer(typeof(WriteConcernResult));
                var replyMessage = connection.ReceiveMessage <WriteConcernResult>(readerSettings, writeConcernResultSerializer, null);
                if (replyMessage.NumberReturned == 0)
                {
                    throw new MongoCommandException("Command 'getLastError' failed. No response returned");
                }
                writeConcernResult         = replyMessage.Documents[0];
                writeConcernResult.Command = getLastErrorCommand;

                var mappedException = ExceptionMapper.Map(writeConcernResult);
                if (mappedException != null)
                {
                    throw mappedException;
                }
            }

            return(writeConcernResult);
        }
示例#25
0
        public IEnumerator <BsonDocument> GetEnumerator()
        {
            AggregateResult result;

            if (_immediateExecutionResult != null)
            {
                result = _immediateExecutionResult;
                _immediateExecutionResult = null;
            }
            else
            {
                result = _collection.RunAggregateCommand(_operations, _options);
            }

            if (result.CursorId != 0)
            {
                var connectionProvider = new ServerInstanceConnectionProvider(result.ServerInstance);
                var readerSettings     = new BsonBinaryReaderSettings
                {
                    Encoding           = _collection.Settings.ReadEncoding ?? MongoDefaults.ReadEncoding,
                    GuidRepresentation = _collection.Settings.GuidRepresentation
                };
                return(new CursorEnumerator <BsonDocument>(
                           connectionProvider,
                           _collection.FullName,
                           result.ResultDocuments,
                           result.CursorId,
                           _options.BatchSize ?? 0,
                           0,
                           readerSettings,
                           BsonDocumentSerializer.Instance,
                           null));
            }
            else if (result.OutputNamespace != null)
            {
                var ns                 = result.OutputNamespace;
                var firstDot           = ns.IndexOf('.');
                var databaseName       = ns.Substring(0, firstDot);
                var collectionName     = ns.Substring(firstDot + 1);
                var database           = _collection.Database.Server.GetDatabase(databaseName);
                var collectionSettings = new MongoCollectionSettings {
                    ReadPreference = ReadPreference.Primary
                };
                var collection = database.GetCollection <BsonDocument>(collectionName, collectionSettings);
                return(collection.FindAll().GetEnumerator());
            }
            else if (result.ResultDocuments != null)
            {
                return(result.ResultDocuments.GetEnumerator());
            }
            else
            {
                throw new NotSupportedException("Unexpected response to aggregate command.");
            }
        }
示例#26
0
        public SQLiteCollectionManager(SQLiteConnection connection, ICollectionImageHandler imageHandler)
        {
            this.connection   = connection;
            this.ImageHandler = imageHandler;

            this.bsonWriterSettings = new BsonBinaryWriterSettings()
            {
                MaxDocumentSize = 24 * 1024 * 1024
            };
            this.bsonReaderSettings = new BsonBinaryReaderSettings()
            {
                MaxDocumentSize = this.bsonWriterSettings.MaxDocumentSize
            };

            this.Operations = new CollectionManagerOperations(this);

            this.loadSettings             = this.connection.CreateCommand();
            this.loadSettings.CommandText = "SELECT * FROM settings;";

            this.saveSettings             = this.connection.CreateCommand();
            this.saveSettings.CommandText = "DELETE FROM settings; INSERT INTO settings (bson) VALUES (@bson);";
            this.saveSettings.Parameters.Add("bson", DbType.Binary);

            this.loadTrackCaches             = this.connection.CreateCommand();
            this.loadTrackCaches.CommandText = "SELECT * FROM track_info_caches;";

            this.saveTrackCache             = this.connection.CreateCommand();
            this.saveTrackCache.CommandText = "INSERT INTO track_info_caches (bson) VALUES (@bson);";
            this.saveTrackCache.Parameters.Add("bson", DbType.Binary);

            this.loadReleases             = this.connection.CreateCommand();
            this.loadReleases.CommandText = "SELECT * FROM releases;";

            this.countReleases             = this.connection.CreateCommand();
            this.countReleases.CommandText = "SELECT COUNT(*) FROM releases;";

            this.loadReleaseById             = this.connection.CreateCommand();
            this.loadReleaseById.CommandText = "SELECT * FROM releases WHERE id = @id;";
            this.loadReleaseById.Parameters.Add("id", DbType.Int64);

            this.saveRelease             = this.connection.CreateCommand();
            this.saveRelease.CommandText = "INSERT INTO releases (bson) VALUES (@bson);";
            this.saveRelease.Parameters.Add("bson", DbType.Binary);

            this.updateRelease             = this.connection.CreateCommand();
            this.updateRelease.CommandText = "UPDATE releases SET bson = @bson WHERE id = @id;";
            this.updateRelease.Parameters.Add("id", DbType.Int64);
            this.updateRelease.Parameters.Add("bson", DbType.Binary);

            this.deleteRelease             = this.connection.CreateCommand();
            this.deleteRelease.CommandText = "DELETE FROM releases WHERE id = @id;";
            this.deleteRelease.Parameters.Add("id", DbType.Int64);

            this.ReloadSettings();
        }
示例#27
0
 protected DatabaseOperation(
     string databaseName,
     string collectionName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings)
 {
     _databaseName   = databaseName;
     _collectionName = collectionName;
     _readerSettings = (BsonBinaryReaderSettings)readerSettings.FrozenCopy();
     _writerSettings = (BsonBinaryWriterSettings)writerSettings.FrozenCopy();
 }
示例#28
0
        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));
                    }
        }
 public RemoveOperation(
     string databaseName,
     string collectionName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings,
     WriteConcern writeConcern,
     IMongoQuery query,
     RemoveFlags flags)
     : base(databaseName, collectionName, readerSettings, writerSettings, writeConcern)
 {
     _query = query;
     _flags = flags;
 }
示例#30
0
        // methods
        /// <summary>
        /// Creates a binary reader for this encoder.
        /// </summary>
        /// <returns>A binary reader.</returns>
        public BsonBinaryReader CreateBinaryReader()
        {
            var readerSettings = new BsonBinaryReaderSettings();

            if (_encoderSettings != null)
            {
                readerSettings.Encoding = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.ReadEncoding, readerSettings.Encoding);
                readerSettings.FixOldBinarySubTypeOnInput    = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.FixOldBinarySubTypeOnInput, readerSettings.FixOldBinarySubTypeOnInput);
                readerSettings.FixOldDateTimeMaxValueOnInput = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.FixOldBinarySubTypeOnOutput, readerSettings.FixOldDateTimeMaxValueOnInput);
                readerSettings.GuidRepresentation            = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.GuidRepresentation, readerSettings.GuidRepresentation);
                readerSettings.MaxDocumentSize = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.MaxDocumentSize, readerSettings.MaxDocumentSize);
            }
            return(new BsonBinaryReader(_stream, readerSettings));
        }
示例#31
0
        #pragma warning restore

        private TCommandResult RunCommandAs <TCommandResult>(
            IMongoCommand command,
            IBsonSerializer <TCommandResult> resultSerializer) where TCommandResult : CommandResult
        {
            var readerSettings = new BsonBinaryReaderSettings
            {
                Encoding           = _settings.ReadEncoding ?? MongoDefaults.ReadEncoding,
                GuidRepresentation = _settings.GuidRepresentation
            };
            var writerSettings = new BsonBinaryWriterSettings
            {
                Encoding           = _settings.WriteEncoding ?? MongoDefaults.WriteEncoding,
                GuidRepresentation = _settings.GuidRepresentation
            };
            var readPreference = _settings.ReadPreference;

            if (readPreference != ReadPreference.Primary)
            {
                if (_server.ProxyType == MongoServerProxyType.Unknown)
                {
                    _server.Connect();
                }
                if (_server.ProxyType == MongoServerProxyType.ReplicaSet && !CanCommandBeSentToSecondary.Delegate(command.ToBsonDocument()))
                {
                    readPreference = ReadPreference.Primary;
                }
            }
            var flags = (readPreference == ReadPreference.Primary) ? QueryFlags.None : QueryFlags.SlaveOk;

            var commandOperation = new CommandOperation <TCommandResult>(
                _name,
                readerSettings,
                writerSettings,
                command,
                flags,
                null, // options
                readPreference,
                resultSerializer);

            var connection = _server.AcquireConnection(readPreference);

            try
            {
                return(commandOperation.Execute(connection));
            }
            finally
            {
                _server.ReleaseConnection(connection);
            }
        }
示例#32
0
        public void TestMaterialize(
            [Values(0, 1, 2)] int count)
        {
            var array                = new BsonArray(Enumerable.Range(0, count));
            var document             = new BsonDocument("array", array);
            var bytes                = document.ToBson();
            var rawDocument          = new RawBsonDocument(bytes);
            var subject              = (RawBsonArray)rawDocument["array"];
            var binaryReaderSettings = new BsonBinaryReaderSettings();

            var result = subject.Materialize(binaryReaderSettings);

            result.Should().BeOfType <BsonArray>();
            result.Should().Be(array);
        }
示例#33
0
        private TResult ProcessCommandResult(ConnectionId connectionId, RawBsonDocument rawBsonDocument)
        {
            var binaryReaderSettings = new BsonBinaryReaderSettings
            {
                Encoding           = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict),
                GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy)
            };

            using (var stream = new ByteBufferStream(rawBsonDocument.Slice, ownsBuffer: false))
                using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(reader);
                    return(_resultSerializer.Deserialize(context));
                }
        }