Пример #1
0
        public void RoundTrip()
        {
            using (var ms = new MemoryStream())
            {
                using (var writer = new BsonBinaryWriter(ms))
                {
                    var bsContext  = BsonSerializationContext.CreateRoot(writer);
                    var serializer = new MigrationVersionSerializer();
                    var bsArgs     = new BsonSerializationArgs();

                    writer.WriteStartDocument();
                    writer.WriteName("version");
                    serializer.Serialize(bsContext, bsArgs, new MigrationVersion("M20010203040506_foo"));
                    writer.WriteEndDocument();
                }
                ms.Position = 0;
                using (var reader = new BsonBinaryReader(ms))
                {
                    var bsContext  = BsonDeserializationContext.CreateRoot(reader);
                    var serializer = new MigrationVersionSerializer();
                    var bsArgs     = new BsonDeserializationArgs();

                    reader.ReadStartDocument();
                    reader.ReadName().Should().Be("version");
                    var version = serializer.Deserialize(bsContext, bsArgs);
                    version.Should().BeEquivalentTo(new MigrationVersion("M20010203040506_foo"));
                    reader.ReadEndDocument();
                }
            }
        }
        public void BsonBinaryReader_should_support_reading_more_than_2GB()
        {
            RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");

            var binaryData = new BsonBinaryData(new byte[1024 * 1024]);

            var tempFileName = Path.GetTempFileName();

            try
            {
                using (var stream = new FileStream(tempFileName, FileMode.Open))
                {
                    using (var binaryWriter = new BsonBinaryWriter(stream))
                    {
                        while (stream.Position < (long)int.MaxValue * 4)
                        {
                            binaryWriter.WriteStartDocument();
                            binaryWriter.WriteName("x");
                            binaryWriter.WriteBinaryData(binaryData);
                            binaryWriter.WriteEndDocument();
                        }
                    }

                    var endOfFilePosition = stream.Position;
                    stream.Position = 0;

                    using (var binaryReader = new BsonBinaryReader(stream))
                    {
                        while (!binaryReader.IsAtEndOfFile())
                        {
                            binaryReader.ReadStartDocument();
                            var bookmark = binaryReader.GetBookmark();

                            binaryReader.ReadName("x");
                            binaryReader.ReturnToBookmark(bookmark);

                            binaryReader.ReadName("x");
                            var readBinaryData = binaryReader.ReadBinaryData();
                            Assert.Equal(binaryData.Bytes.Length, readBinaryData.Bytes.Length);

                            binaryReader.ReadEndDocument();
                        }
                    }

                    Assert.Equal(endOfFilePosition, stream.Position);
                }
            }
            finally
            {
                try
                {
                    File.Delete(tempFileName);
                }
                catch
                {
                    // ignore exceptions
                }
            }
        }
Пример #3
0
        public void TestFlushAndClose()
        {
            var stream = new MemoryStream();

            using (var bsonWriter = new BsonBinaryWriter(stream))
            {
                bsonWriter.WriteStartDocument();
                bsonWriter.WriteEndDocument();
                bsonWriter.Flush();
                bsonWriter.Close();
            }
        }
Пример #4
0
        public void Test1ChunkPlus1()
        {
            var stream = new MemoryStream();

            using (var bsonWriter = new BsonBinaryWriter(stream))
            {
                bsonWriter.WriteStartDocument();
                bsonWriter.WriteBytes("Data", new byte[16 * 1024 - 15]);
                bsonWriter.WriteEndDocument();
                bsonWriter.Close();
            }
        }
Пример #5
0
            // protected methods
            protected override void SerializeRequest(BsonBinaryWriter bsonWriter, WriteRequest request)
            {
                var deleteRequest = (DeleteRequest)request;

                bsonWriter.PushMaxDocumentSize(MaxDocumentSize);
                bsonWriter.WriteStartDocument();
                bsonWriter.WriteName("q");
                BsonSerializer.Serialize(bsonWriter, deleteRequest.Query ?? new QueryDocument());
                bsonWriter.WriteInt32("limit", deleteRequest.Limit);
                bsonWriter.WriteEndDocument();
                bsonWriter.PopMaxDocumentSize();
            }
        public void BsonBinaryWriter_should_support_writing_more_than_2GB()
        {
            using (var stream = new NullBsonStream())
                using (var binaryWriter = new BsonBinaryWriter(stream))
                {
                    var bigBinaryData = new BsonBinaryData(new byte[int.MaxValue / 2 - 1000]);
                    for (var i = 0; i < 3; i++)
                    {
                        binaryWriter.WriteStartDocument();
                        binaryWriter.WriteName("x");
                        binaryWriter.WriteBinaryData(bigBinaryData);
                        binaryWriter.WriteEndDocument();
                    }

                    var smallBinaryData = new BsonBinaryData(new byte[2000]);
                    binaryWriter.WriteStartDocument();
                    binaryWriter.WriteName("x");
                    binaryWriter.WriteBinaryData(smallBinaryData);
                    binaryWriter.WriteEndDocument();
                }
        }
        public void BsonWriter_should_fail_on_invalid_child_elements_names(
            [Values(1, 2)]
            int levelsCount,
            [Values(true, false)]
            bool addValidatorOnRoot)
        {
            var levelNames      = Enumerable.Range(0, levelsCount).Select(i => $"level{i}").ToArray();
            var validatorsMocks = CreatePrefixValidatorsNestedMock(levelNames);

            using (var stream = new MemoryStream())
                using (var writer = new BsonBinaryWriter(stream))
                {
                    if (addValidatorOnRoot)
                    {
                        writer.PushElementNameValidator(validatorsMocks[0].Object);
                    }

                    writer.WriteStartDocument();

                    if (!addValidatorOnRoot)
                    {
                        writer.PushElementNameValidator(validatorsMocks[0].Object);
                    }

                    foreach (var levelName in levelNames)
                    {
                        Record.Exception(() => writer.WriteInt32($"wrongname", 1)).Should().BeOfType <BsonSerializationException>();

                        writer.WriteInt32($"{levelName}_int", 1);
                        writer.WriteStartDocument($"{levelName}_nested");
                    }

                    for (int i = 0; i < levelsCount; i++)
                    {
                        writer.WriteEndDocument(); // $"{levelName}_nested"
                    }

                    writer.WriteEndDocument();
                }
        }
Пример #8
0
 private byte[] Serialize <TEnum>(IBsonSerializer <TEnum> serializer, TEnum value)
 {
     using (var stream = new MemoryStream())
         using (var writer = new BsonBinaryWriter(stream))
         {
             var context = BsonSerializationContext.CreateRoot(writer);
             writer.WriteStartDocument();
             writer.WriteName("x");
             serializer.Serialize(context, value);
             writer.WriteEndDocument();
             return(stream.ToArray());
         }
 }
Пример #9
0
        /// <summary>
        /// 写bson
        /// </summary>
        /// <param name="outputFileName"></param>
        public static void WriteBson(string outputFileName)
        {
            //如果存在,则覆盖(注意原来的不截断)
            using (FileStream stream = File.OpenWrite(outputFileName))
            {
                using (BsonBinaryWriter writer = new BsonBinaryWriter(stream))
                {
                    writer.WriteStartDocument();
                    writer.WriteName("a");
                    writer.WriteInt32(1);

                    writer.WriteEndDocument();
                }
            }
        }
Пример #10
0
 // internal methods
 internal override void WriteBodyTo(BsonBuffer buffer)
 {
     using (var bsonWriter = new BsonBinaryWriter(buffer, false, WriterSettings))
     {
         bsonWriter.PushMaxDocumentSize(_maxDocumentSize);
         if (_query == null)
         {
             bsonWriter.WriteStartDocument();
             bsonWriter.WriteEndDocument();
         }
         else
         {
             BsonSerializer.Serialize(bsonWriter, _query.GetType(), _query, DocumentSerializationOptions.SerializeIdFirstInstance);
         }
         bsonWriter.PopMaxDocumentSize();
     }
 }
 // internal methods
 internal override void WriteBodyTo(BsonStreamWriter streamWriter)
 {
     using (var bsonWriter = new BsonBinaryWriter(streamWriter.BaseStream, WriterSettings))
     {
         bsonWriter.PushMaxDocumentSize(_maxDocumentSize);
         if (_query == null)
         {
             bsonWriter.WriteStartDocument();
             bsonWriter.WriteEndDocument();
         }
         else
         {
             BsonSerializer.Serialize(bsonWriter, _query.GetType(), _query, b => b.SerializeIdFirst = true);
         }
         bsonWriter.PopMaxDocumentSize();
     }
 }
        // protected methods
        protected override void WriteBody(BsonBuffer buffer)
        {
            buffer.WriteInt32(0); // reserved
            buffer.WriteCString(new UTF8Encoding(false, true), _collectionFullName);
            buffer.WriteInt32((int)_flags);

            using (var bsonWriter = new BsonBinaryWriter(buffer, false, WriterSettings))
            {
                if (_query == null)
                {
                    bsonWriter.WriteStartDocument();
                    bsonWriter.WriteEndDocument();
                }
                else
                {
                    BsonSerializer.Serialize(bsonWriter, _query.GetType(), _query, DocumentSerializationOptions.SerializeIdFirstInstance);
                }
            }
        }
        public void Serialize_guid_should_have_expected_result_when_guid_representation_is_unspecified_and_mode_is_v2(
            [Values(GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy, GuidRepresentation.Standard, GuidRepresentation.Unspecified)]
            GuidRepresentation defaultGuidRepresentation,
            [Values(GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy, GuidRepresentation.Standard, GuidRepresentation.Unspecified)]
            GuidRepresentation writerGuidRepresentation)
        {
#pragma warning disable 618
            var expectedGuidRepresentation = writerGuidRepresentation != GuidRepresentation.Unspecified ? writerGuidRepresentation : defaultGuidRepresentation;
            if (expectedGuidRepresentation == GuidRepresentation.Unspecified)
            {
                throw new SkipException("Test skipped because expectedGuidRepresentation is Unspecified.");
            }
            BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V2;
            BsonDefaults.GuidRepresentation     = defaultGuidRepresentation;
            var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
            var subject        = new ObjectSerializer(discriminatorConvention, GuidRepresentation.Unspecified);
            var writerSettings = new BsonBinaryWriterSettings();
            if (writerGuidRepresentation != GuidRepresentation.Unspecified)
            {
                writerSettings.GuidRepresentation = writerGuidRepresentation;
            }
            using (var memoryStream = new MemoryStream())
                using (var writer = new BsonBinaryWriter(memoryStream, writerSettings))
                {
                    var context = BsonSerializationContext.CreateRoot(writer);
                    var guid    = Guid.Parse("01020304-0506-0708-090a-0b0c0d0e0f10");

                    writer.WriteStartDocument();
                    writer.WriteName("x");
                    subject.Serialize(context, guid);
                    writer.WriteEndDocument();

                    var bytes             = memoryStream.ToArray();
                    var expectedBytes     = 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 expectedSubType   = GuidConverter.GetSubType(expectedGuidRepresentation);
                    var expectedGuidBytes = GuidConverter.ToBytes(guid, expectedGuidRepresentation);
                    expectedBytes[11] = (byte)expectedSubType;
                    Array.Copy(expectedGuidBytes, 0, expectedBytes, 12, 16);
                    bytes.Should().Equal(expectedBytes);
                }
#pragma warning restore 618
        }
            // protected methods
            protected override void SerializeRequest(BsonBinaryWriter bsonWriter, WriteRequest request)
            {
                var updateRequest = (UpdateRequest)request;

                bsonWriter.PushMaxDocumentSize(MaxWireDocumentSize);
                bsonWriter.WriteStartDocument();
                bsonWriter.WriteName("q");
                BsonSerializer.Serialize(bsonWriter, updateRequest.Query ?? new QueryDocument());
                bsonWriter.WriteName("u");
                BsonSerializer.Serialize(bsonWriter, updateRequest.Update);
                if (updateRequest.IsMultiUpdate.HasValue)
                {
                    bsonWriter.WriteBoolean("multi", updateRequest.IsMultiUpdate.Value);
                }
                if (updateRequest.IsUpsert.HasValue)
                {
                    bsonWriter.WriteBoolean("upsert", updateRequest.IsUpsert.Value);
                }
                bsonWriter.WriteEndDocument();
                bsonWriter.PopMaxDocumentSize();
            }
        public void BsonBinaryWriter_should_support_writing_multiple_documents(
            [Range(0, 3)]
            int numberOfDocuments)
        {
            var document       = new BsonDocument("x", 1);
            var bson           = document.ToBson();
            var expectedResult = Enumerable.Repeat(bson, numberOfDocuments).Aggregate(Enumerable.Empty <byte>(), (a, b) => a.Concat(b)).ToArray();

            using (var stream = new MemoryStream())
                using (var binaryWriter = new BsonBinaryWriter(stream))
                {
                    for (var n = 0; n < numberOfDocuments; n++)
                    {
                        binaryWriter.WriteStartDocument();
                        binaryWriter.WriteName("x");
                        binaryWriter.WriteInt32(1);
                        binaryWriter.WriteEndDocument();
                    }

                    var result = stream.ToArray();
                    result.Should().Equal(expectedResult);
                }
        }
Пример #16
0
        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());
                }
        }
        public void Serialize_should_write_expected_bytes(
            GuidRepresentationMode defaultGuiRepresentationMode,
            GuidRepresentation defaultGuidRepresentation,
            GuidRepresentation serializerGuidRepresentation,
            GuidRepresentation?writerGuidRepresentation,
            BsonBinarySubType expectedSubType,
            GuidRepresentation effectiveGuidRepresentation)
        {
            GuidMode.Set(defaultGuiRepresentationMode, defaultGuidRepresentation);

            var subject        = new GuidSerializer(serializerGuidRepresentation);
            var memoryStream   = new MemoryStream();
            var writerSettings = new BsonBinaryWriterSettings();

            if (defaultGuiRepresentationMode == GuidRepresentationMode.V2 && writerGuidRepresentation.HasValue)
            {
#pragma warning disable 618
                writerSettings.GuidRepresentation = writerGuidRepresentation.Value;
#pragma warning restore 618
            }
            var writer  = new BsonBinaryWriter(memoryStream, writerSettings);
            var context = BsonSerializationContext.CreateRoot(writer);
            var args    = new BsonSerializationArgs();
            var value   = new Guid("01020304-0506-0708-090a-0b0c0d0e0f10");

            writer.WriteStartDocument();
            writer.WriteName("x");
            subject.Serialize(context, args, value);
            writer.WriteEndDocument();
            var result = memoryStream.ToArray();

            var expectedBytes = 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 };
            expectedBytes[11] = (byte)expectedSubType;
            Array.Copy(GuidConverter.ToBytes(value, effectiveGuidRepresentation), 0, expectedBytes, 12, 16);
            result.Should().Equal(expectedBytes);
        }
        public void BsonWriter_should_validate_child_elements_names(
            [Values(1, 2, 3)]
            int levelsCount,
            [Values(true, false)]
            bool addValidatorOnRoot)
        {
            var levelNames      = Enumerable.Range(0, levelsCount).Select(i => $"level{i}").ToArray();
            var validatorsMocks = CreatePrefixValidatorsNestedMock(levelNames);

            using (var stream = new MemoryStream())
                using (var writer = new BsonBinaryWriter(stream))
                {
                    if (addValidatorOnRoot)
                    {
                        writer.PushElementNameValidator(validatorsMocks[0].Object);
                    }

                    writer.WriteStartDocument();

                    if (!addValidatorOnRoot)
                    {
                        writer.PushElementNameValidator(validatorsMocks[0].Object);
                    }

                    foreach (var levelName in levelNames)
                    {
                        writer.WriteInt32($"{levelName}_int", 1);

                        writer.WriteStartDocument($"{levelName}_nested_empty");
                        writer.WriteEndDocument();

                        writer.WriteStartDocument($"{levelName}_nested");
                    }

                    // Add additional level
                    writer.WriteStartDocument($"{levelsCount}_nested");
                    writer.WriteEndDocument(); // $"{levelsCount}_nested"

                    for (int i = 0; i < levelsCount; i++)
                    {
                        writer.WriteEndDocument(); // $"{levelName}_nested"
                    }

                    // Pop validator
                    if (!addValidatorOnRoot)
                    {
                        writer.PopElementNameValidator();
                        writer.WriteInt32("nonvalidatedname", 1);
                    }
                    writer.WriteEndDocument();
                }

            for (int i = 0; i < levelsCount; i++)
            {
                var levelName     = levelNames[i];
                var validatorMock = validatorsMocks[i];

                var children  = new[] { $"{levelName}_nested_empty", $"{levelName}_nested" };
                var fieldsAll = children.Concat(new[] { $"{levelName}_int" }).ToArray();

                foreach (var field in fieldsAll)
                {
                    validatorMock.Verify(v => v.IsValidElementName(field), Times.Once);
                }

                foreach (var child in children)
                {
                    validatorMock.Verify(v => v.GetValidatorForChildContent(child), Times.Once);
                }

                validatorMock.Verify(v => v.IsValidElementName(It.IsNotIn(fieldsAll)), Times.Never);
                validatorMock.Verify(v => v.GetValidatorForChildContent(It.IsNotIn(children)), Times.Never);
            }
        }