Пример #1
0
        public void WriteBytes()
        {
            byte[] data = Encoding.UTF8.GetBytes("Hello world!");

            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartArray();
            writer.WriteValue("a");
            writer.WriteValue("b");
            writer.WriteValue(data);
            writer.WriteEndArray();

            writer.Flush();

            ms.Seek(0, SeekOrigin.Begin);

            string expected = "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-00-48-65-6C-6C-6F-20-77-6F-72-6C-64-21-00";
            string bson     = BytesToHex(ms.ToArray());

            Assert.AreEqual(expected, bson);

            BsonDataReader reader = new BsonDataReader(new MemoryStream(ms.ToArray()));

            reader.ReadRootValueAsArray = true;
            reader.Read();
            reader.Read();
            reader.Read();
            reader.Read();
            Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
            CollectionAssert.AreEquivalent(data, (byte[])reader.Value);
        }
Пример #2
0
 public void Serialize(object value, Stream output)
 {
     using (var writer = new BsonDataWriter(output))
     {
         this.serializer.Serialize(writer, value);
         writer.Flush();
         //output.Position = 0;
     }
 }
Пример #3
0
        protected virtual byte[] PackViewModel(JObject viewModelToken)
        {
            using (var ms = new MemoryStream())
                using (var bsonWriter = new BsonDataWriter(ms))
                {
                    viewModelToken.WriteTo(bsonWriter);
                    bsonWriter.Flush();

                    return(ms.ToArray());
                }
        }
Пример #4
0
 private void SerializeJsonNetBinaryBenchInner(object o, MemoryStream ms)
 {
     for (int i = 0; i < Iterations; i++)
     {
         var s = new Newtonsoft.Json.JsonSerializer();
         var w = new BsonDataWriter(ms);
         s.Serialize(w, o);
         Escape(w);
         w.Flush();
     }
 }
 public byte[] SerializeToBytes(ISerializableObject obj)
 {
     using (var str = new MemoryStream())
     {
         using (var wr = new BsonDataWriter(str))
         {
             var s = new JsonSerializer();
             s.Serialize(wr, (FakePostNode)obj);
             wr.Flush();
         }
         return(str.ToArray());
     }
 }
Пример #6
0
        public void WriteValueOutsideOfObjectOrArray()
        {
            ExceptionAssert.Throws <JsonWriterException>(() =>
            {
                MemoryStream stream = new MemoryStream();

                using (BsonDataWriter writer = new BsonDataWriter(stream))
                {
                    writer.WriteValue("test");
                    writer.Flush();
                }
            }, "Error writing String value. BSON must start with an Object or Array. Path ''.");
        }
Пример #7
0
        void IMessageSerializer.Serialize <T>(Stream stream, SendContext <T> context)
        {
            context.ContentType = EncryptedContentType;

            var envelope = new JsonMessageEnvelope(context, context.Message, TypeMetadataCache <T> .MessageTypeNames);

            using Stream cryptoStream = _streamProvider.GetEncryptStream(stream, context);
            using var jsonWriter      = new BsonDataWriter(cryptoStream);

            _serializer.Serialize(jsonWriter, envelope, typeof(MessageEnvelope));

            jsonWriter.Flush();
        }
Пример #8
0
        public void Serialize <T>(Stream stream, SendContext <T> context)
            where T : class
        {
            context.ContentType = BsonContentType;

            var envelope = new JsonMessageEnvelope(context, context.Message, TypeMetadataCache <T> .MessageTypeNames);

            using (var jsonWriter = new BsonDataWriter(stream))
            {
                _serializer.Value.Serialize(jsonWriter, envelope, typeof(MessageEnvelope));

                jsonWriter.Flush();
            }
        }
        /// <inheritdoc/>
        public virtual byte[] Serialize(object body)
        {
            if (body == null)
            {
                return(null);
            }

            using (var innerStream = new MemoryStream())
                using (var writer = new BsonDataWriter(innerStream))
                {
                    this.serializer.Value.Serialize(writer, body);
                    writer.Flush();
                    return(innerStream.ToArray());
                }
        }
Пример #10
0
 void WriteBsonMessage <T>(T messages)
 {
     using (var buffer = new BufferedStream(stream, 4096, true))
         using (var zip = new DeflateStream(buffer, CompressionMode.Compress, true))
             using (var bson = new BsonDataWriter(zip)
             {
                 CloseOutput = false
             })
             {
                 serializer.Serialize(bson, new MessageEnvelope {
                     Message = messages
                 });
                 bson.Flush();
             }
 }
        void IMessageSerializer.Serialize <T>(Stream stream, SendContext <T> context)
        {
            context.ContentType = EncryptedContentType;

            var envelope = new JsonMessageEnvelope(context, context.Message, TypeMetadataCache <T> .MessageTypeNames);

            using var cryptoStream = _streamProvider.GetEncryptStream(stream, context);
            using (var jsonWriter = new BsonDataWriter(cryptoStream))
            {
                _serializer.Serialize(jsonWriter, envelope, typeof(MessageEnvelope));

                jsonWriter.Flush();

                ((System.Security.Cryptography.CryptoStream)cryptoStream).FlushFinalBlock();
            }
        }
Пример #12
0
        public void Serialize(object message, Stream stream)
        {
            var jsonSerializer = JsonSerializer.Create(serializerSettings);

            jsonSerializer.Binder = new MessageSerializationBinder(messageMapper);

            var jsonWriter = new BsonDataWriter(stream);

            var objects = new[]
            {
                message
            };

            jsonSerializer.Serialize(jsonWriter, objects);

            jsonWriter.Flush();
        }
Пример #13
0
        public void AutoCompleteOnClose_False()
        {
            MemoryStream ms = new MemoryStream();

            using (BsonDataWriter writer = new BsonDataWriter(ms))
            {
                writer.AutoCompleteOnClose = false;

                writer.WriteStartObject();
                writer.WritePropertyName("Blah");

                writer.Flush();
            }

            // nothing is written because a BSON document needs to be completed before it can be written
            Assert.AreEqual(string.Empty, (BitConverter.ToString(ms.ToArray())));
        }
Пример #14
0
        public void TestClientBson()
        {
            var lst = new List <Client>
            {
                ///////////////////////////////////////////
                // Console Client Credentials Flow Sample
                //////////////////////////////////////////
                new Client
                {
                    ClientId      = "client",
                    ClientSecrets =
                    {
                        new Secret
                        {
                            Type  = IdentityServerConstants.SecretTypes.SharedSecret,
                            Value = "secret".Sha256()
                        }
                    },

                    AllowedGrantTypes = GrantTypes.ClientCredentials.ToList(),
                    AllowedScopes     = new List <string> {
                        "api1", "api2.read_only"
                    }
                },
            };

            var ms         = new MemoryStream();
            var serializer = new JsonSerializer();

            // serialize product to BSON
            var writer = new BsonDataWriter(ms);

            serializer.Serialize(writer, lst);
            writer.Flush();
            ms.Position = 0;

            var reader       = new BsonDataReader(ms, true, DateTimeKind.Unspecified);
            var deserialized = serializer.Deserialize <List <Client> >(reader);

            Assert.IsNotNull(deserialized);
            Assert.IsTrue(deserialized.Count > 0);
            Assert.AreEqual("client", deserialized[0].ClientId);
        }
Пример #15
0
        /// <summary>
        /// Serializes the specified object value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="output">The output.</param>
        public void Serialize(object value, Stream output)
        {
            if (value == null)
            {
                return;
            }

            if (output == null)
            {
                return;
            }

            using (var writer = new BsonDataWriter(output))
            {
                writer.AutoCompleteOnClose = false;
                writer.CloseOutput         = false;
                this.serializer.Serialize(writer, value);
                writer.Flush();
            }
        }
Пример #16
0
        public void WriteArrayBsonFromSite()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartArray();
            writer.WriteValue("a");
            writer.WriteValue("b");
            writer.WriteValue("c");
            writer.WriteEndArray();

            writer.Flush();

            ms.Seek(0, SeekOrigin.Begin);

            string expected = "20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00";
            string bson     = BytesToHex(ms.ToArray());

            Assert.AreEqual(expected, bson);
        }
Пример #17
0
        public IOutgoingMessageBody Serialize(IServiceRemotingResponseMessageBody serviceRemotingResponseMessageBody)
        {
            if (serviceRemotingResponseMessageBody == null)
            {
                return(null);
            }

            using (var ms = new MemoryStream())
            {
                using (var writer = new BsonDataWriter(ms))
                {
                    serializer.Serialize(writer, serviceRemotingResponseMessageBody);
                    writer.Flush();

                    var segment  = new ArraySegment <byte>(ms.ToArray());
                    var segments = new List <ArraySegment <byte> > {
                        segment
                    };
                    return(new OutgoingMessageBody(segments));
                }
            }
        }
Пример #18
0
        public void Serialize <T>(Stream stream, SendContext <T> context)
            where T : class
        {
            try
            {
                context.ContentType = GrpcContentType;

                using var jsonWriter = new BsonDataWriter(stream);

                _serializer.Value.Serialize(jsonWriter, context.Message, typeof(T));

                jsonWriter.Flush();
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
Пример #19
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (selectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(selectedEncoding));
            }

            var response = context.HttpContext.Response;

            using (var bsonWriter = new BsonDataWriter(response.Body)
            {
                CloseOutput = false
            })
            {
                var jsonSerializer = CreateJsonSerializer();
                jsonSerializer.Serialize(bsonWriter, context.Object);
                bsonWriter.Flush();
            }
        }
Пример #20
0
        public void WriteNestedArray()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartObject();

            writer.WritePropertyName("_id");
            writer.WriteValue(HexToBytes("4A-78-93-79-17-22-00-00-00-00-61-CF"));

            writer.WritePropertyName("a");
            writer.WriteStartArray();
            for (int i = 1; i <= 8; i++)
            {
                double value = (i != 5)
                    ? Convert.ToDouble(i)
                    : 5.78960446186581E+77d;

                writer.WriteValue(value);
            }
            writer.WriteEndArray();

            writer.WritePropertyName("b");
            writer.WriteValue("test");

            writer.WriteEndObject();

            writer.Flush();

            ms.Seek(0, SeekOrigin.Begin);

            string expected = "87-00-00-00-05-5F-69-64-00-0C-00-00-00-00-4A-78-93-79-17-22-00-00-00-00-61-CF-04-61-00-5D-00-00-00-01-30-00-00-00-00-00-00-00-F0-3F-01-31-00-00-00-00-00-00-00-00-40-01-32-00-00-00-00-00-00-00-08-40-01-33-00-00-00-00-00-00-00-10-40-01-34-00-00-00-00-00-00-00-14-50-01-35-00-00-00-00-00-00-00-18-40-01-36-00-00-00-00-00-00-00-1C-40-01-37-00-00-00-00-00-00-00-20-40-00-02-62-00-05-00-00-00-74-65-73-74-00-00";
            string bson     = BytesToHex(ms.ToArray());

            Assert.AreEqual(expected, bson);
        }
        public void Serialize <T>(Stream stream, SendContext <T> context)
            where T : class
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            context.ContentType = EncryptedMessageSerializer.EncryptedContentType;
            var jsonMessageEnvelope = new JsonMessageEnvelope(context, context.Message, TypeMetadataCache <T> .MessageTypeNames);

            using (var transform = this.CreateAndSetEncryptionContext(context.Headers, context.CancellationToken).ConfigureAwait(false).GetAwaiter().GetResult())
                using (var encryptStream = new DisposingCryptoStream(stream, transform, CryptoStreamMode.Write))
                    using (var bsonWriter = new BsonDataWriter(encryptStream))
                    {
                        this.serializer.Serialize(bsonWriter, jsonMessageEnvelope, typeof(MessageEnvelope));
                        bsonWriter.Flush();
                    }
        }
        public void Serialize <T>(Stream stream, SendContext <T> context)
            where T : class
        {
            try
            {
                var envelope = JObject.FromObject(_envelope, SerializerCache.Serializer);

                if (_message != null)
                {
                    JToken message = JObject.FromObject(_message, SerializerCache.Serializer);
                    envelope["message"] = message.Merge(envelope["message"]);
                }

                context.ContentType = ContentType;

                envelope["sourceAddress"] = context.SourceAddress;

                if (context.MessageId.HasValue)
                {
                    envelope["messageId"] = context.MessageId.Value.ToString();
                }

                if (context.RequestId.HasValue)
                {
                    envelope["requestId"] = context.RequestId.Value.ToString();
                }

                if (context.CorrelationId.HasValue)
                {
                    envelope["correlationId"] = context.CorrelationId.Value.ToString();
                }

                if (context.ConversationId.HasValue)
                {
                    envelope["conversationId"] = context.ConversationId.Value.ToString();
                }

                if (context.InitiatorId.HasValue)
                {
                    envelope["initiatorId"] = context.InitiatorId.Value.ToString();
                }

                if (context.SourceAddress != null)
                {
                    envelope["sourceAddress"] = context.SourceAddress.ToString();
                }

                if (context.DestinationAddress != null)
                {
                    envelope["destinationAddress"] = context.DestinationAddress.ToString();
                }

                if (context.ResponseAddress != null)
                {
                    envelope["responseAddress"] = context.ResponseAddress.ToString();
                }

                if (context.FaultAddress != null)
                {
                    envelope["faultAddress"] = context.FaultAddress.ToString();
                }

                if (context.TimeToLive.HasValue)
                {
                    envelope["expirationTime"] = DateTime.UtcNow + context.TimeToLive;
                }

                if (_useEncryption == false)
                {
                    using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
                        using (var jsonWriter = new JsonTextWriter(writer))
                        {
                            jsonWriter.Formatting = Formatting.Indented;

                            SerializerCache.Serializer.Serialize(jsonWriter, envelope, typeof(MessageEnvelope));

                            jsonWriter.Flush();
                            writer.Flush();
                        }
                }
                else
                {
                    using var cryptoStream = _streamProvider.GetEncryptStream(stream, context);
                    using var jsonWriter   = new BsonDataWriter(cryptoStream);

                    BsonMessageSerializer.Serializer.Serialize(jsonWriter, envelope, typeof(MessageEnvelope));

                    jsonWriter.Flush();
                }
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }