예제 #1
0
        public void ReadBytes()
        {
            byte[] data = HexToBytes("2B-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-05-32-00-0C-00-00-00-02-48-65-6C-6C-6F-20-77-6F-72-6C-64-21-00");

            MemoryStream ms = new MemoryStream(data);
            BsonReader reader = new BsonReader(ms, true, DateTimeKind.Utc);

            Assert.Equal(true, reader.ReadRootValueAsArray);
            Assert.Equal(DateTimeKind.Utc, reader.DateTimeKindHandling);

            Assert.True(reader.Read());
            Assert.Equal(JsonToken.StartArray, reader.TokenType);

            Assert.True(reader.Read());
            Assert.Equal(JsonToken.String, reader.TokenType);
            Assert.Equal("a", reader.Value);
            Assert.Equal(typeof(string), reader.ValueType);

            Assert.True(reader.Read());
            Assert.Equal(JsonToken.String, reader.TokenType);
            Assert.Equal("b", reader.Value);
            Assert.Equal(typeof(string), reader.ValueType);

            byte[] encodedStringData = reader.ReadAsBytes();
            Assert.NotNull(encodedStringData);
            Assert.Equal(JsonToken.Bytes, reader.TokenType);
            Assert.Equal(encodedStringData, reader.Value);
            Assert.Equal(typeof(byte[]), reader.ValueType);

            Assert.True(reader.Read());
            Assert.Equal(JsonToken.EndArray, reader.TokenType);

            Assert.False(reader.Read());
            Assert.Equal(JsonToken.None, reader.TokenType);

            string decodedString = Encoding.UTF8.GetString(encodedStringData, 0, encodedStringData.Length);
            Assert.Equal("Hello world!", decodedString);
        }
예제 #2
0
        public void GuidsShouldBeProperlyDeserialised_AsBytes_ReadAhead()
        {
            Guid g = new Guid("822C0CE6-CC42-4753-A3C3-26F0684A4B88");

            MemoryStream ms = new MemoryStream();
            BsonWriter writer = new BsonWriter(ms);
            writer.WriteStartObject();
            writer.WritePropertyName("TheGuid");
            writer.WriteValue(g);
            writer.WriteEndObject();
            writer.Flush();

            byte[] bytes = ms.ToArray();

            BsonReader reader = new BsonReader(new MemoryStream(bytes));
            Assert.True(reader.Read());
            Assert.True(reader.Read());

            Assert.Equal(g.ToByteArray(), reader.ReadAsBytes());
            Assert.Equal(JsonToken.Bytes, reader.TokenType);
            Assert.Equal(typeof(byte[]), reader.ValueType);
            Assert.Equal(g.ToByteArray(), (byte[])reader.Value);

            Assert.True(reader.Read());
            Assert.False(reader.Read());

            JsonSerializer serializer = new JsonSerializer();
            serializer.MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead;
            BytesTestClass b = serializer.Deserialize<BytesTestClass>(new BsonReader(new MemoryStream(bytes)));
            Assert.Equal(g.ToByteArray(), b.TheGuid);
        }