Example #1
0
        // methods
        /// <inheritdoc/>
        public UpdateMessage ReadMessage()
        {
            var jsonReader      = CreateJsonReader();
            var messageContext  = BsonDeserializationContext.CreateRoot(jsonReader);
            var messageDocument = BsonDocumentSerializer.Instance.Deserialize(messageContext);

            var opcode = messageDocument["opcode"].AsString;

            if (opcode != "update")
            {
                throw new FormatException("Opcode is not update.");
            }

            var requestId      = messageDocument["requestId"].ToInt32();
            var databaseName   = messageDocument["database"].AsString;
            var collectionName = messageDocument["collection"].AsString;
            var query          = messageDocument["query"].AsBsonDocument;
            var update         = messageDocument["update"].AsBsonDocument;
            var isMulti        = messageDocument.GetValue("isMulti", false).ToBoolean();
            var isUpsert       = messageDocument.GetValue("isUpsert", false).ToBoolean();

            return(new UpdateMessage(
                       requestId,
                       new CollectionNamespace(databaseName, collectionName),
                       query,
                       update,
                       NoOpElementNameValidator.Instance,
                       isMulti,
                       isUpsert));
        }
Example #2
0
        public DeleteMessage ReadMessage()
        {
            if (_binaryReader == null)
            {
                throw new InvalidOperationException("No binaryReader was provided.");
            }

            var streamReader = _binaryReader.StreamReader;

            var messageSize        = streamReader.ReadInt32();
            var requestId          = streamReader.ReadInt32();
            var responseTo         = streamReader.ReadInt32();
            var opcode             = (Opcode)streamReader.ReadInt32();
            var reserved           = streamReader.ReadInt32();
            var fullCollectionName = streamReader.ReadCString();
            var flags   = (DeleteFlags)streamReader.ReadInt32();
            var context = BsonDeserializationContext.CreateRoot <BsonDocument>(_binaryReader);
            var query   = BsonDocumentSerializer.Instance.Deserialize(context);

            var firstDot       = fullCollectionName.IndexOf('.');
            var databaseName   = fullCollectionName.Substring(0, firstDot);
            var collectionName = fullCollectionName.Substring(firstDot + 1);
            var isMulti        = !flags.HasFlag(DeleteFlags.Single);

            return(new DeleteMessage(
                       requestId,
                       databaseName,
                       collectionName,
                       query,
                       isMulti));
        }
        public void Deserialize_should_support_duplicate_element_names_in_full_document()
        {
            var json    = "{ fullDocument : { x : 1, x : 2 } }";
            var subject = CreateSubject();

            ChangeStreamDocument <BsonDocument> result;

            using (var reader = new JsonReader(json))
            {
                var context = BsonDeserializationContext.CreateRoot(reader);
                result = subject.Deserialize(context);
            }

            var fullDocument = result.FullDocument;

            fullDocument.ElementCount.Should().Be(2);
            var firstElement = fullDocument.GetElement(0);

            firstElement.Name.Should().Be("x");
            firstElement.Value.Should().Be(1);
            var secondElement = fullDocument.GetElement(1);

            secondElement.Name.Should().Be("x");
            secondElement.Value.Should().Be(2);
        }
Example #4
0
        public static async void InsertGrades(IMongoDatabase db)
        {
            string jsonPath = @"C:\Codec\MongoDB\Uni\week_2_crud.bf5486e303a0\homework_2_1\grades.json";

            try
            {
                await db.DropCollectionAsync("grades");

                var collection = db.GetCollection <Grades>("grades");

                using (var streamReader = new StreamReader(jsonPath))
                {
                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context  = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            await collection.InsertOneAsync(document);
                        }
                    }
                }
                Console.WriteLine("Successfully Uploaded Grades");
                Console.WriteLine("Querying all documents");

                await QueryAllDocuments(db, "grades");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception \n\n");
                Console.WriteLine(ex.Message);
            }
        }
Example #5
0
        internal DeleteMessage ReadMessage <TDocument>(IBsonSerializer <TDocument> serializer)
            where TDocument : BsonDocument
        {
            var binaryReader = CreateBinaryReader();
            var stream       = binaryReader.BsonStream;

            stream.ReadInt32(); // messageSize
            var requestId = stream.ReadInt32();

            stream.ReadInt32(); // responseTo
            stream.ReadInt32(); // opcode
            stream.ReadInt32(); // reserved
            var fullCollectionName = stream.ReadCString(Encoding);
            var flags   = (DeleteFlags)stream.ReadInt32();
            var context = BsonDeserializationContext.CreateRoot(binaryReader);
            var query   = serializer.Deserialize(context);

            var isMulti = (flags & DeleteFlags.Single) != DeleteFlags.Single;

            return(new DeleteMessage(
                       requestId,
                       CollectionNamespace.FromFullName(fullCollectionName),
                       query,
                       isMulti));
        }
Example #6
0
        /// <summary>
        /// Writes a raw BSON array.
        /// </summary>
        /// <param name="slice">The byte buffer containing the raw BSON array.</param>
        public virtual void WriteRawBsonArray(IByteBuffer slice)
        {
            // overridden in BsonBinaryWriter to write the raw bytes to the stream
            // for all other streams, deserialize the raw bytes and serialize the resulting array instead

            using (var chunkSource = new InputBufferChunkSource(BsonChunkPool.Default))
                using (var buffer = new MultiChunkBuffer(chunkSource))
                    using (var stream = new ByteBufferStream(buffer))
                    {
                        // wrap the array in a fake document so we can deserialize it
                        var documentLength = slice.Length + 8;
                        buffer.EnsureCapacity(documentLength);
                        stream.WriteInt32(documentLength);
                        stream.WriteBsonType(BsonType.Array);
                        stream.WriteByte((byte)'x');
                        stream.WriteByte(0);
                        stream.WriteSlice(slice);
                        stream.WriteByte(0);
                        buffer.MakeReadOnly();

                        stream.Position = 0;
                        using (var reader = new BsonBinaryReader(stream, BsonBinaryReaderSettings.Defaults))
                        {
                            var deserializationContext = BsonDeserializationContext.CreateRoot(reader);
                            reader.ReadStartDocument();
                            reader.ReadName("x");
                            var array = BsonArraySerializer.Instance.Deserialize(deserializationContext);
                            reader.ReadEndDocument();

                            var serializationContext = BsonSerializationContext.CreateRoot(this);
                            BsonArraySerializer.Instance.Serialize(serializationContext, array);
                        }
                    }
        }
        // public methods
        /// <summary>
        /// Reads the message.
        /// </summary>
        /// <returns>A message.</returns>
        public CompressedMessage ReadMessage()
        {
            var reader          = CreateJsonReader();
            var context         = BsonDeserializationContext.CreateRoot(reader);
            var messageDocument = BsonDocumentSerializer.Instance.Deserialize(context);

            var opcode = (Opcode)messageDocument["opcode"].ToInt32();

            if (opcode != Opcode.Compressed)
            {
                throw new FormatException($"Command message invalid opcode: \"{opcode}\".");
            }

            var compressorId      = (CompressorType)messageDocument["compressorId"].ToInt32();
            var compressedMessage = messageDocument["compressedMessage"].AsString;

            using (var originalTextReader = new StringReader(compressedMessage))
            {
                var jsonEncoderFactory = new JsonMessageEncoderFactory(originalTextReader, _encoderSettings);
                var originalEncoder    = _originalEncoderSelector.GetEncoder(jsonEncoderFactory);
                var originalMessage    = originalEncoder.ReadMessage();

                return(new CompressedMessage(originalMessage, null, compressorId));
            }
        }
        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);
        }
        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>();
        }
        /// <summary>
        /// Creates document.
        /// </summary>
        /// <param name="mongoDoc">The mongo doc.</param>
        /// <returns>
        /// The document.
        /// </returns>
        public ActionResult <object> CreateDocument(MongoDocument mongoDoc)
        {
            MongoClient client     = Helper.GetMongoClient(mongoDoc);
            var         database   = client.GetDatabase(mongoDoc.DatabaseName);
            var         collection = database.GetCollection <BsonDocument>(mongoDoc.CollectionName);

            BsonDocument document = null;

            if (!string.IsNullOrWhiteSpace(mongoDoc.Id))
            {
                ObjectId oid;
                if (ObjectId.TryParse(mongoDoc.Id, out oid))
                {
                    document = collection.Find($"{{ _id: ObjectId('{mongoDoc.Id}') }}").FirstOrDefault();
                }
                else
                {
                    document = collection.Find(x => x["_id"] == mongoDoc.Id).FirstOrDefault();
                }
            }

            if (document == null)
            {
                using (var reader = new MongoDB.Bson.IO.JsonReader(mongoDoc.DocumentData))
                {
                    var context = BsonDeserializationContext.CreateRoot(reader);
                    document = BsonDocumentSerializer.Instance.Deserialize(context);
                }
                collection.InsertOne(document);
            }

            var doc = document.ToString();

            return(CreatedAtAction(nameof(GetByDocumentId), new { id = document["_id"].ToString(), mongoDoc = mongoDoc }, doc));
        }
Example #11
0
        public InsertMessage <TDocument> ReadMessage()
        {
            var binaryReader  = CreateBinaryReader();
            var streamReader  = binaryReader.StreamReader;
            var startPosition = streamReader.Position;

            var messageSize        = streamReader.ReadInt32();
            var requestId          = streamReader.ReadInt32();
            var responseTo         = streamReader.ReadInt32();
            var opcode             = (Opcode)streamReader.ReadInt32();
            var flags              = (InsertFlags)streamReader.ReadInt32();
            var fullCollectionName = streamReader.ReadCString();
            var documents          = new List <TDocument>();

            while (streamReader.Position < startPosition + messageSize)
            {
                var context  = BsonDeserializationContext.CreateRoot <TDocument>(binaryReader);
                var document = _serializer.Deserialize(context);
                documents.Add(document);
            }

            var documentSource  = new BatchableSource <TDocument>(documents);
            var maxBatchCount   = 0;
            var maxMessageSize  = 0;
            var continueOnError = flags.HasFlag(InsertFlags.ContinueOnError);

            return(new InsertMessage <TDocument>(
                       requestId,
                       CollectionNamespace.FromFullName(fullCollectionName),
                       _serializer,
                       documentSource,
                       maxBatchCount,
                       maxMessageSize,
                       continueOnError));
        }
Example #12
0
        // methods
        public DeleteMessage ReadMessage()
        {
            if (_jsonReader == null)
            {
                throw new InvalidOperationException("No jsonReader was provided.");
            }

            var messageContext  = BsonDeserializationContext.CreateRoot <BsonDocument>(_jsonReader);
            var messageDocument = BsonDocumentSerializer.Instance.Deserialize(messageContext);

            var opcode = messageDocument["opcode"].AsString;

            if (opcode != "delete")
            {
                throw new FormatException("Opcode is not delete.");
            }

            var requestId      = messageDocument["requestId"].ToInt32();
            var databaseName   = messageDocument["database"].AsString;
            var collectionName = messageDocument["collection"].AsString;
            var query          = messageDocument["query"].AsBsonDocument;
            var isMulti        = messageDocument["isMulti"].ToBoolean();

            return(new DeleteMessage(
                       requestId,
                       databaseName,
                       collectionName,
                       query,
                       isMulti));
        }
Example #13
0
        public void Deserialize_should_return_expected_result(
            string json,
            string expectedResumeTokenJson,
            ChangeStreamOperationType expectedOperationType,
            string expectedDatabaseName,
            string expectedCollectionName,
            string expectedDocumentKeyJson,
            string expectedUpdateDescriptionJson,
            string expectedFullDocumentJson
            )
        {
            var subject = CreateSubject();
            var expectedCollectionNamespace = CreateCollectionNamespace(expectedDatabaseName, expectedCollectionName);
            var expectedDocumentKey         = ParseBsonDocument(expectedDocumentKeyJson);
            var expectedFullDocument        = ParseBsonDocument(expectedFullDocumentJson);
            var expectedResumeToken         = ParseBsonDocument(expectedResumeTokenJson);
            var expectedUpdateDescription   = ParseUpdateDescription(expectedUpdateDescriptionJson);

            ChangeStreamDocument <BsonDocument> result;

            using (var reader = new JsonReader(json))
            {
                var context = BsonDeserializationContext.CreateRoot(reader);
                result = subject.Deserialize(context);
            }

            result.CollectionNamespace.Should().Be(expectedCollectionNamespace);
            result.DocumentKey.Should().Be(expectedDocumentKey);
            result.FullDocument.Should().Be(expectedFullDocument);
            result.OperationType.Should().Be(expectedOperationType);
            result.ResumeToken.Should().Be(expectedResumeToken);
            result.UpdateDescription.ShouldBeEquivalentTo(expectedUpdateDescription);
        }
        public void TestCustomDictionarySerializerSerializeAndDeserialize()
        {
            var map = new Dictionary <object, object> {
                { "power", 9001 }
            };
            var serializer = new CustomDictionarySerializer <object, object>();
            var expected   = @"{ ""power"" : 9001 }";

            var json = map.ToJson(writerSettings: null, serializer: serializer);

            Assert.Equal(expected, json);

            var bson = map.ToBson(serializer: serializer);

            using (var buffer = new ByteArrayBuffer(bytes: bson, isReadOnly: true))
                using (var stream = new ByteBufferStream(buffer))
                    using (var bsonReader = new BsonBinaryReader(stream))
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader: bsonReader, configurator: null);

                        var rehydrated = serializer.Deserialize(context);

                        Assert.True(bson.SequenceEqual(rehydrated.ToBson()));
                    }
        }
Example #15
0
        /// <summary>
        /// Tries to get the value of an element of this document.
        /// </summary>
        /// <param name="name">The name of the element.</param>
        /// <param name="value">The value of the element.</param>
        /// <returns>
        /// True if an element with that name was found.
        /// </returns>
        public override bool TryGetValue(string name, out BsonValue value)
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
                using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(bsonReader);

                    bsonReader.ReadStartDocument();
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        if (bsonReader.ReadName() == name)
                        {
                            value = DeserializeBsonValue(context);
                            return(true);
                        }

                        bsonReader.SkipValue();
                    }
                    bsonReader.ReadEndDocument();

                    value = null;
                    return(false);
                }
        }
        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>();
        }
        /// <summary>
        /// Writes a raw BSON array.
        /// </summary>
        /// <param name="slice">The byte buffer containing the raw BSON array.</param>
        public virtual void WriteRawBsonArray(IByteBuffer slice)
        {
            // overridden in BsonBinaryWriter to write the raw bytes to the stream
            // for all other streams, deserialize the raw bytes and serialize the resulting array instead

            var documentLength = slice.Length + 8;

            using (var memoryStream = new MemoryStream(documentLength))
            {
                // wrap the array in a fake document so we can deserialize it
                var streamWriter = new BsonStreamWriter(memoryStream, Utf8Encodings.Strict);
                streamWriter.WriteInt32(documentLength);
                streamWriter.WriteBsonType(BsonType.Array);
                streamWriter.WriteByte((byte)'x');
                streamWriter.WriteByte(0);
                slice.WriteTo(streamWriter.BaseStream);
                streamWriter.WriteByte(0);

                memoryStream.Position = 0;
                using (var bsonReader = new BsonBinaryReader(memoryStream, BsonBinaryReaderSettings.Defaults))
                {
                    var deserializationContext = BsonDeserializationContext.CreateRoot <BsonDocument>(bsonReader);
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadName("x");
                    var array = deserializationContext.DeserializeWithChildContext(BsonArraySerializer.Instance);
                    bsonReader.ReadEndDocument();

                    var serializationContext = BsonSerializationContext.CreateRoot <BsonArray>(this);
                    BsonArraySerializer.Instance.Serialize(serializationContext, array);
                }
            }
        }
Example #18
0
        // methods
        public GetMoreMessage ReadMessage()
        {
            var jsonReader      = CreateJsonReader();
            var messageContext  = BsonDeserializationContext.CreateRoot(jsonReader);
            var messageDocument = BsonDocumentSerializer.Instance.Deserialize(messageContext);

            var opcode = messageDocument["opcode"].AsString;

            if (opcode != "getMore")
            {
                throw new FormatException("Opcode is not getMore.");
            }

            var requestId      = messageDocument["requestId"].ToInt32();
            var databaseName   = messageDocument["database"].AsString;
            var collectionName = messageDocument["collection"].AsString;
            var cursorId       = messageDocument["cursorId"].ToInt32();
            var batchSize      = messageDocument["batchSize"].ToInt32();

            return(new GetMoreMessage(
                       requestId,
                       new CollectionNamespace(databaseName, collectionName),
                       cursorId,
                       batchSize));
        }
        public override T Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var    bookmark = context.Reader.GetBookmark();
            object original;

            using (var originalReader = new FieldHidingBsonReader(context.Reader, fieldName => fieldName == _joinedFieldName))
            {
                var childContext = BsonDeserializationContext.CreateRoot(originalReader);
                original = _sourceSerializer.Deserialize(childContext);
            }

            context.Reader.ReturnToBookmark(bookmark);
            object joined = null;

            context.Reader.ReadStartDocument();
            while (context.Reader.ReadBsonType() != BsonType.EndOfDocument)
            {
                var name = context.Reader.ReadName();
                if (name != _joinedFieldName)
                {
                    context.Reader.SkipValue();
                }
                else
                {
                    joined = _joinedSerializer.Deserialize(context);
                }
            }
            context.Reader.ReadEndDocument();

            return((T)_creator(original, joined));
        }
        // public methods
        /// <summary>
        /// Gets the actual type of an object by reading the discriminator from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The reader.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <returns>The actual type.</returns>
        public Type GetActualType(BsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Document)
            {
                // ensure KnownTypes of nominalType are registered (so IsTypeDiscriminated returns correct answer)
                BsonSerializer.EnsureKnownTypesAreRegistered(nominalType);

                // we can skip looking for a discriminator if nominalType has no discriminated sub types
                if (BsonSerializer.IsTypeDiscriminated(nominalType))
                {
                    var bookmark = bsonReader.GetBookmark();
                    bsonReader.ReadStartDocument();
                    var actualType = nominalType;
                    if (bsonReader.FindElement(_elementName))
                    {
                        var context       = BsonDeserializationContext.CreateRoot <BsonValue>(bsonReader);
                        var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                        if (discriminator.IsBsonArray)
                        {
                            discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                        }
                        actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                    }
                    bsonReader.ReturnToBookmark(bookmark);
                    return(actualType);
                }
            }

            return(nominalType);
        }
Example #21
0
        /// <summary>
        /// Reads a raw BSON array.
        /// </summary>
        /// <returns>The raw BSON array.</returns>
        public virtual IByteBuffer ReadRawBsonArray()
        {
            // overridden in BsonBinaryReader to read the raw bytes from the stream
            // for all other streams, deserialize the array and reserialize it using a BsonBinaryWriter to get the raw bytes

            var deserializationContext = BsonDeserializationContext.CreateRoot(this);
            var array = BsonArraySerializer.Instance.Deserialize(deserializationContext);

            using (var memoryStream = new MemoryStream())
                using (var bsonWriter = new BsonBinaryWriter(memoryStream, BsonBinaryWriterSettings.Defaults))
                {
                    var serializationContext = BsonSerializationContext.CreateRoot(bsonWriter);
                    bsonWriter.WriteStartDocument();
                    var startPosition = memoryStream.Position + 3; // just past BsonType, "x" and null byte
                    bsonWriter.WriteName("x");
                    BsonArraySerializer.Instance.Serialize(serializationContext, array);
                    var endPosition = memoryStream.Position;
                    bsonWriter.WriteEndDocument();

                    byte[] memoryStreamBuffer;
#if NETSTANDARD1_5 || NETSTANDARD1_6
                    memoryStreamBuffer = memoryStream.ToArray();
#else
                    memoryStreamBuffer = memoryStream.GetBuffer();
#endif
                    var buffer = new ByteArrayBuffer(memoryStreamBuffer, (int)memoryStream.Length, isReadOnly: true);
                    return(new ByteBufferSlice(buffer, (int)startPosition, (int)(endPosition - startPosition)));
                }
        }
Example #22
0
        private IEnumerable <BsonElement> MaterializeThisLevel()
        {
            var elements = new List <BsonElement>();

            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
                using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(bsonReader);

                    bsonReader.ReadStartDocument();
                    BsonType bsonType;
                    while ((bsonType = bsonReader.ReadBsonType()) != BsonType.EndOfDocument)
                    {
                        var       name = bsonReader.ReadName();
                        BsonValue value;
                        switch (bsonType)
                        {
                        case BsonType.Array: value = DeserializeLazyBsonArray(bsonReader); break;

                        case BsonType.Document: value = DeserializeLazyBsonDocument(bsonReader); break;

                        default: value = BsonValueSerializer.Instance.Deserialize(context); break;
                        }
                        elements.Add(new BsonElement(name, value));
                    }
                    bsonReader.ReadEndDocument();
                }

            return(elements);
        }
        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));
                }
        }
        // protected methods
        /// <summary>
        /// Deserializes a value.
        /// </summary>
        /// <param name="context">The deserialization context.</param>
        /// <returns>The value.</returns>
        protected override GeoJsonBoundingBox <TCoordinates> DeserializeValue(BsonDeserializationContext context)
        {
            var bsonReader = context.Reader;

            var flattenedArray = BsonArraySerializer.Instance.Deserialize(context.CreateChild(typeof(BsonArray)));

            if ((flattenedArray.Count % 2) != 0)
            {
                throw new FormatException("Bounding box array does not have an even number of values.");
            }
            var half = flattenedArray.Count / 2;

            // create a dummy document with a min and a max and then deserialize the min and max coordinates from there
            var document = new BsonDocument
            {
                { "min", new BsonArray(flattenedArray.Take(half)) },
                { "max", new BsonArray(flattenedArray.Skip(half)) }
            };

            using (var documentReader = new BsonDocumentReader(document))
            {
                var documentContext = BsonDeserializationContext.CreateRoot(documentReader, typeof(BsonDocument));
                documentReader.ReadStartDocument();
                documentReader.ReadName("min");
                var min = documentContext.DeserializeWithChildContext(_coordinatesSerializer);
                documentReader.ReadName("max");
                var max = documentContext.DeserializeWithChildContext(_coordinatesSerializer);
                documentReader.ReadEndDocument();

                return(new GeoJsonBoundingBox <TCoordinates>(min, max));
            }
        }
Example #25
0
        public static BsonArray GetBsonArray(string uri)
        {
            using (HttpClient http = new HttpClient())
            {
                string data = http.GetStringAsync(uri).Result;
                if (data == "unauthorized permission requested")
                {
                    throw new Exceptions.TrelloDriverRequestException("Key or token invalid");
                }
                else if (data == "The requested resource was not found.")
                {
                    throw new Exceptions.TrelloDriverRequestException("Invalid Action id");
                }

                using (var jsonReader = new JsonReader(data))
                {
                    var serializer = new BsonArraySerializer();
                    try
                    {
                        BsonArray array = serializer.Deserialize(BsonDeserializationContext.CreateRoot(jsonReader));
                        return(array);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        throw;
                    }
                }
            }
        }
Example #26
0
        // methods
        /// <summary>
        /// Reads the message.
        /// </summary>
        /// <returns>A message.</returns>
        public DeleteMessage ReadMessage()
        {
            var jsonReader      = CreateJsonReader();
            var messageContext  = BsonDeserializationContext.CreateRoot(jsonReader);
            var messageDocument = BsonDocumentSerializer.Instance.Deserialize(messageContext);

            var opcode = messageDocument["opcode"].AsString;

            if (opcode != "delete")
            {
                throw new FormatException("Opcode is not delete.");
            }

            var requestId      = messageDocument["requestId"].ToInt32();
            var databaseName   = messageDocument["database"].AsString;
            var collectionName = messageDocument["collection"].AsString;
            var query          = messageDocument["query"].AsBsonDocument;
            var isMulti        = messageDocument["isMulti"].ToBoolean();

            return(new DeleteMessage(
                       requestId,
                       new CollectionNamespace(databaseName, collectionName),
                       query,
                       isMulti));
        }
        /***************************************************/
        /**** Interface Methods                         ****/
        /***************************************************/

        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            Type actualType = nominalType;

            // the BsonReader is sitting at the value whose actual type needs to be found
            BsonType bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Document)
            {
                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();

                if (bsonReader.FindElement(ElementName))
                {
                    var context       = BsonDeserializationContext.CreateRoot(bsonReader);
                    var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                    if (discriminator.IsBsonArray)
                    {
                        discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                    }
                    if (BsonSerializer.IsTypeDiscriminated(nominalType))
                    {
                        actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                    }
                }
                bsonReader.ReturnToBookmark(bookmark);
            }

            return(actualType);
        }
Example #28
0
        /// <summary>
        /// Gets the value of an element.
        /// </summary>
        /// <param name="index">The zero based index of the element.</param>
        /// <returns>
        /// The value of the element.
        /// </returns>
        public override BsonValue GetValue(int index)
        {
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }
            ThrowIfDisposed();

            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
                using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(bsonReader);

                    bsonReader.ReadStartDocument();
                    var i = 0;
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        bsonReader.SkipName();
                        if (i == index)
                        {
                            return(DeserializeBsonValue(context));
                        }

                        bsonReader.SkipValue();
                        i++;
                    }
                    bsonReader.ReadEndDocument();

                    throw new ArgumentOutOfRangeException("index");
                }
        }
Example #29
0
        public UpdateMessage ReadMessage()
        {
            var binaryReader = CreateBinaryReader();
            var streamReader = binaryReader.StreamReader;

            streamReader.ReadInt32(); // messageSize
            var requestId = streamReader.ReadInt32();

            streamReader.ReadInt32(); // responseTo
            streamReader.ReadInt32(); // opcode
            streamReader.ReadInt32(); // reserved
            var fullCollectionName = streamReader.ReadCString();
            var flags   = (UpdateFlags)streamReader.ReadInt32();
            var context = BsonDeserializationContext.CreateRoot(binaryReader);
            var query   = BsonDocumentSerializer.Instance.Deserialize(context);
            var update  = BsonDocumentSerializer.Instance.Deserialize(context);

            var isMulti  = (flags & UpdateFlags.Multi) == UpdateFlags.Multi;
            var isUpsert = (flags & UpdateFlags.Upsert) == UpdateFlags.Upsert;

            return(new UpdateMessage(
                       requestId,
                       CollectionNamespace.FromFullName(fullCollectionName),
                       query,
                       update,
                       NoOpElementNameValidator.Instance,
                       isMulti,
                       isUpsert));
        }
Example #30
0
        private IReadOnlyList <IAsyncCursor <TDocument> > CreateCursors(IChannelSourceHandle channelSource, BsonDocument command, BsonDocument result)
        {
            var cursors = new List <AsyncCursor <TDocument> >();

            foreach (var cursorDocument in result["cursors"].AsBsonArray.Select(v => v["cursor"].AsBsonDocument))
            {
                var cursorId   = cursorDocument["id"].ToInt64();
                var firstBatch = cursorDocument["firstBatch"].AsBsonArray.Select(v =>
                {
                    var bsonDocument = (BsonDocument)v;
                    using (var reader = new BsonDocumentReader(bsonDocument))
                    {
                        var context  = BsonDeserializationContext.CreateRoot(reader);
                        var document = _serializer.Deserialize(context);
                        return(document);
                    }
                })
                                 .ToList();

                var cursor = new AsyncCursor <TDocument>(
                    channelSource.Fork(),
                    _collectionNamespace,
                    command,
                    firstBatch,
                    cursorId,
                    _batchSize ?? 0,
                    0, // limit
                    _serializer,
                    _messageEncoderSettings);

                cursors.Add(cursor);
            }

            return(cursors);
        }