Example #1
0
        public static string Serialize(Message msg)
        {
#if !DEBUG //this is because its easier to log json than bson bytes
            using (MemoryStream memory = new MemoryStream())
                using (BsonDataWriter writer = new BsonDataWriter(memory))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(writer, msg);
                    return(Convert.ToBase64String(memory.ToArray()));
                }
#else
            return(JsonConvert.SerializeObject(msg));
#endif
        }
Example #2
0
        public void WriteEmptyStrings()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartObject();
            writer.WritePropertyName("");
            writer.WriteValue("");
            writer.WriteEndObject();

            string bson = BytesToHex(ms.ToArray());

            Assert.AreEqual("0C-00-00-00-02-00-01-00-00-00-00-00", bson);
        }
Example #3
0
        public override async Task HandleAuthorizationRequest([NotNull] HandleAuthorizationRequestContext context)
        {
            var options = (OpenIddictOptions)context.Options;

            // If no request_id parameter can be found in the current request, assume the OpenID Connect request
            // was not serialized yet and store the entire payload in the distributed cache to make it easier
            // to flow across requests and internal/external authentication/registration workflows.
            if (options.EnableRequestCaching && string.IsNullOrEmpty(context.Request.RequestId))
            {
                // Generate a request identifier. Note: using a crypto-secure
                // random number generator is not necessary in this case.
                context.Request.RequestId = Guid.NewGuid().ToString();

                // Store the serialized authorization request parameters in the distributed cache.
                var stream = new MemoryStream();
                using (var writer = new BsonDataWriter(stream))
                {
                    writer.CloseOutput = false;

                    var serializer = JsonSerializer.CreateDefault();
                    serializer.Serialize(writer, context.Request);
                }

                // Note: the cache key is always prefixed with a specific marker
                // to avoid collisions with the other types of cached requests.
                var key = OpenIddictConstants.Environment.AuthorizationRequest + context.Request.RequestId;

                await options.Cache.SetAsync(key, stream.ToArray(), new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = context.Options.SystemClock.UtcNow + TimeSpan.FromMinutes(30),
                    SlidingExpiration  = TimeSpan.FromMinutes(10)
                });

                // Create a new authorization request containing only the request_id parameter.
                var address = QueryHelpers.AddQueryString(
                    uri: context.HttpContext.Request.Scheme + "://" + context.HttpContext.Request.Host +
                    context.HttpContext.Request.PathBase + context.HttpContext.Request.Path,
                    name: OpenIdConnectConstants.Parameters.RequestId, value: context.Request.RequestId);

                context.HttpContext.Response.Redirect(address);

                // Mark the response as handled
                // to skip the rest of the pipeline.
                context.HandleResponse();

                return;
            }

            context.SkipHandler();
        }
Example #4
0
        public byte[] getBytes()
        {
            MemoryStream ms = new MemoryStream();

            using (BsonDataWriter writer = new BsonDataWriter(ms))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(writer, this);
            }
            var res = ms.ToArray();

            ms.Close();
            return(res);
        }
        byte[] SerializeObject <T>(T value)
        {
            var settings = Locator.Current.GetService <JsonSerializerSettings>() ?? new JsonSerializerSettings();

            settings.ContractResolver = new JsonDateTimeContractResolver(settings?.ContractResolver); // This will make us use ticks instead of json ticks for DateTime.
            var ms         = new MemoryStream();
            var serializer = JsonSerializer.Create(settings);
            var writer     = new BsonDataWriter(ms);

            serializer.Serialize(writer, new ObjectWrapper <T> {
                Value = value
            });
            return(ms.ToArray());
        }
        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();
            }
        }
Example #7
0
        public static byte[] SerializeBson <T>(T obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (BsonDataWriter writer = new BsonDataWriter(ms))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(writer, obj);
                }

                //string data = Convert.ToBase64String(ms.ToArray());
                return(ms.ToArray());
            }
        }
        public void WriteSingleObject()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartObject();
            writer.WritePropertyName("Blah");
            writer.WriteValue(1);
            writer.WriteEndObject();

            string bson = BytesToHex(ms.ToArray());

            Assert.AreEqual("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00", bson);
        }
Example #9
0
        public void WriteSerializedStore()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            Store s1 = new Store();

            s1.Color     = StoreColor.White;
            s1.Cost      = 999.59m;
            s1.Employees = int.MaxValue - 1;
            s1.Open      = true;
            s1.product.Add(new Product
            {
                ExpiryDate = new DateTime(2000, 9, 28, 3, 59, 58, DateTimeKind.Local),
                Name       = "BSON!",
                Price      = -0.1m,
                Sizes      = new[] { "First", "Second" }
            });
            s1.Establised = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local);

            JsonSerializer serializer = new JsonSerializer();

            serializer.Serialize(writer, s1);

            ms.Seek(0, SeekOrigin.Begin);
            BsonDataReader reader = new BsonDataReader(ms);
            Store          s2     = (Store)serializer.Deserialize(reader, typeof(Store));

            Assert.AreNotEqual(s1, s2);
            Assert.AreEqual(s1.Color, s2.Color);
            Assert.AreEqual(s1.Cost, s2.Cost);
            Assert.AreEqual(s1.Employees, s2.Employees);
            Assert.AreEqual(s1.Escape, s2.Escape);
            Assert.AreEqual(s1.Establised, s2.Establised);
            Assert.AreEqual(s1.Mottos.Count, s2.Mottos.Count);
            Assert.AreEqual(s1.Mottos.First(), s2.Mottos.First());
            Assert.AreEqual(s1.Mottos.Last(), s2.Mottos.Last());
            Assert.AreEqual(s1.Open, s2.Open);
            Assert.AreEqual(s1.product.Count, s2.product.Count);
            Assert.AreEqual(s1.RoomsPerFloor.Length, s2.RoomsPerFloor.Length);
            Assert.AreEqual(s1.Symbol, s2.Symbol);
            Assert.AreEqual(s1.Width, s2.Width);

            MemoryStream   ms1     = new MemoryStream();
            BsonDataWriter writer1 = new BsonDataWriter(ms1);

            serializer.Serialize(writer1, s1);

            CollectionAssert.AreEquivalent(ms.ToArray(), ms1.ToArray());
        }
 public static byte[] Serialize(Type type, object objectToSerialize,
                                bool preserveTypeInfo           = false,
                                List <JsonConverter> converters = null,
                                bool indent = false,
                                Json.JsonSerialize.Newtonsoft.ReferenceLoop referenceLoopHandling = Json.JsonSerialize.Newtonsoft.ReferenceLoop.Ignore)
 {
     using (var ms = new MemoryStream())
         using (var writer = new BsonDataWriter(ms))
         {
             var serializer = JsonSerializer.Create(Json.JsonSerialize.Newtonsoft.PrepareSettings(preserveTypeInfo, converters, indent, referenceLoopHandling));
             serializer.Serialize(writer, objectToSerialize);
             return(ms.ToArray());
         }
 }
Example #11
0
        public void DateTimeZoneHandling()
        {
            MemoryStream ms     = new MemoryStream();
            JsonWriter   writer = new BsonDataWriter(ms)
            {
                DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
            };

            writer.WriteStartArray();
            writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
            writer.WriteEndArray();

            Assert.AreEqual("10-00-00-00-09-30-00-C8-88-07-6B-DC-00-00-00-00", (BitConverter.ToString(ms.ToArray())));
        }
        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();
                }
        }
Example #13
0
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            BsonDataObjectId objectId = (BsonDataObjectId)value;

            BsonDataWriter bsonWriter = writer as BsonDataWriter;

            if (bsonWriter != null)
            {
                bsonWriter.WriteObjectId(objectId.Value);
            }
            else
            {
                writer.WriteValue(objectId.Value);
            }
        }
Example #14
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();
             }
 }
Example #15
0
        public async Task WriteDoubleAsync()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            await writer.WriteStartArrayAsync();

            await writer.WriteValueAsync(99.99d);

            await writer.WriteEndAsync();

            string bson = BytesToHex(ms.ToArray());

            Assert.AreEqual("10-00-00-00-01-30-00-8F-C2-F5-28-5C-FF-58-40-00", bson);
        }
        public override byte[] Execute(List <Contact> list)
        {
            MemoryStream ms = new MemoryStream();

            using (BsonDataWriter writer = new BsonDataWriter(ms))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(writer, list);
            }
            var bytes = ms.ToArray();

            ms.Dispose();

            return(bytes);
        }
        /// <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());
                }
        }
Example #18
0
        public static void SaveToFile(Project_Collection projects, string path)
        {
            MemoryStream ms = new MemoryStream();

            using (BsonDataWriter writer = new BsonDataWriter(ms))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
                serializer.TypeNameHandling           = TypeNameHandling.Auto;
                serializer.Serialize(writer, projects);
            }
            string data = Convert.ToBase64String(ms.ToArray());

            File.WriteAllText(path, data);
        }
        /// <summary>
        /// Saves the bson file.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="fileName">Name of the file.</param>
        private async Task saveBsonFile(Object data, string fileName)
        {
            Directory.CreateDirectory(_path);

            var name     = fileName;
            var fullName = Path.Combine(_path, name);

            var file = new FileStream(fullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

            using (var bson = new BsonDataWriter(file))
            {
                _serializer.Serialize(bson, data);
                await bson.FlushAsync();
            }
        }
Example #20
0
        public void WriteGuid()
        {
            Guid g = new Guid("D821EED7-4B5C-43C9-8AC2-6928E579B705");

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

            writer.WriteStartArray();
            writer.WriteValue(g);
            writer.WriteEnd();

            string bson = BytesToHex(ms.ToArray());

            Assert.AreEqual("1D-00-00-00-05-30-00-10-00-00-00-04-D7-EE-21-D8-5C-4B-C9-43-8A-C2-69-28-E5-79-B7-05-00", bson);
        }
Example #21
0
 /// <summary>
 /// Bson Serializes the object.
 /// </summary>
 /// <param name="value">The obj.</param>
 /// <returns></returns>
 public static byte[] ToBson(this object value)
 {
     using (var output = new MemoryStream())
     {
         var serializer = new JsonSerializer {
             ContractResolver = new CamelCasePropertyNamesContractResolver(),
         };
         using (var writer = new BsonDataWriter(output))
         {
             serializer.Serialize(writer, value);
             output.Flush();
             return(output.ToArray());
         }
     }
 }
Example #22
0
        private byte[] PackBosn(string result)
        {
            ShareData shareData = new ShareData
            {
                Type     = "Text",
                TextData = result
            };
            MemoryStream   ms             = new MemoryStream();
            BsonDataWriter bsonDataWriter = new BsonDataWriter(ms);
            JsonSerializer jsonSerializer = new JsonSerializer();

            jsonSerializer.Serialize(bsonDataWriter, shareData);
            byte[] res = ms.ToArray();
            ms.Close();
            return(res);
        }
Example #23
0
        private byte[] PackBosn(byte[] bs)
        {
            ShareData shareData = new ShareData
            {
                Type    = "Image",
                ImgData = bs
            };
            MemoryStream   ms             = new MemoryStream();
            BsonDataWriter bsonDataWriter = new BsonDataWriter(ms);
            JsonSerializer jsonSerializer = new JsonSerializer();

            jsonSerializer.Serialize(bsonDataWriter, shareData);
            byte[] res = ms.ToArray();
            bsonDataWriter.Close();
            return(res);
        }
 /// <summary>
 /// Encodes the data using a <see cref="Newtonsoft.Json.Bson.BsonDataWriter"/>
 /// </summary>
 /// <param name="data">The object to be serialized</param>
 /// <returns>A byte array representing the object given by <paramref name="data"/></returns>
 public virtual byte[] Encode(T data)
 {
     if (EqualityComparer <T> .Default.Equals(data, default(T)))
     {
         return(new byte[0]);
     }
     using (var ms = new MemoryStream())
     {
         using (var writer = new BsonDataWriter(ms))
         {
             var serializer = new JsonSerializer();
             serializer.Serialize(writer, data);
             return(ms.ToArray());
         }
     }
 }
Example #25
0
        public void WriteRegexPlusContent()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartObject();
            writer.WritePropertyName("regex");
            writer.WriteRegex("abc", "i");
            writer.WritePropertyName("test");
            writer.WriteRegex(string.Empty, null);
            writer.WriteEndObject();

            byte[] expected = HexToBytes("1A-00-00-00-0B-72-65-67-65-78-00-61-62-63-00-69-00-0B-74-65-73-74-00-00-00-00");

            CollectionAssert.AreEquivalent(expected, ms.ToArray());
        }
Example #26
0
        public void WriteOidPlusContent()
        {
            MemoryStream   ms     = new MemoryStream();
            BsonDataWriter writer = new BsonDataWriter(ms);

            writer.WriteStartObject();
            writer.WritePropertyName("_id");
            writer.WriteObjectId(HexToBytes("4ABBED9D1D8B0F0218000001"));
            writer.WritePropertyName("test");
            writer.WriteValue("1234£56");
            writer.WriteEndObject();

            byte[] expected = HexToBytes("29000000075F6964004ABBED9D1D8B0F02180000010274657374000900000031323334C2A335360000");

            CollectionAssert.AreEquivalent(expected, ms.ToArray());
        }
Example #27
0
        public static void WriteBson(BinaryWriter binaryWriter, FacilityType theFacility)
        {
            var serializerSettings = new JsonSerializerSettings
            {
                NullValueHandling  = NullValueHandling.Ignore,
                DateFormatHandling = DateFormatHandling.IsoDateFormat
            };

            serializerSettings.Converters.Add(new StringEnumConverter());
            var serialiser = JsonSerializer.Create(serializerSettings);
            // serialize product to BSON

            var writer = new BsonDataWriter(binaryWriter);

            serialiser.Serialize(writer, theFacility);
        }
Example #28
0
 public static void WriteData <T>(Stream strm, T data)
 {
     using (var writer = new BsonDataWriter(new BinaryWriter(strm, DefaultEncoding, true)))
     {
         if (data is ISerializablePayloadData)
         {
             ((ISerializablePayloadData)data).Serialize(writer);
         }
         else
         {
             Serializer.Serialize(writer, data);
         }
     }
     // var serializer = MessagePackSerializer.Get<T>();
     // serializer.Pack(strm, data);
 }
 private static byte[] ToBson(object obj)
 {
     byte[] result;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         using (BsonDataWriter bsonWriter = new BsonDataWriter(memoryStream))
         {
             JsonSerializer serializer = new JsonSerializer {
                 NullValueHandling = NullValueHandling.Ignore
             };
             serializer.Serialize(bsonWriter, obj);
         }
         result = memoryStream.ToArray();
     }
     return(result);
 }
Example #30
0
 /// <summary>
 /// Creates a comparable bson buffer from token
 /// </summary>
 /// <param name="token"></param>
 /// <returns></returns>
 public static byte[] ToBson(this JToken token)
 {
     using (var ms = new MemoryStream()) {
         using (var writer = new BsonDataWriter(ms)) {
             if (token.Type != JTokenType.Object &&
                 token.Type != JTokenType.Array)
             {
                 token = new JObject {
                     new JProperty("value", token)
                 };
             }
             token.WriteTo(writer);
         }
         return(ms.ToArray());
     }
 }