public void WriteValues() { MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); writer.WriteStartArray(); writer.WriteValue(long.MaxValue); writer.WriteValue((ulong)long.MaxValue); writer.WriteValue(int.MaxValue); writer.WriteValue((uint)int.MaxValue); writer.WriteValue(byte.MaxValue); writer.WriteValue(sbyte.MaxValue); writer.WriteValue('a'); writer.WriteValue(decimal.MaxValue); writer.WriteValue(double.MaxValue); writer.WriteValue(float.MaxValue); writer.WriteValue(true); writer.WriteValue(new byte[] { 0, 1, 2, 3, 4 }); writer.WriteValue(new DateTimeOffset(2000, 12, 29, 12, 30, 0, TimeSpan.Zero)); writer.WriteValue(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc)); writer.WriteEnd(); string bson = MiscellaneousUtils.BytesToHex(ms.ToArray()); Assert.AreEqual("8C-00-00-00-12-30-00-FF-FF-FF-FF-FF-FF-FF-7F-12-31-00-FF-FF-FF-FF-FF-FF-FF-7F-10-32-00-FF-FF-FF-7F-10-33-00-FF-FF-FF-7F-10-34-00-FF-00-00-00-10-35-00-7F-00-00-00-02-36-00-02-00-00-00-61-00-01-37-00-00-00-00-00-00-00-F0-45-01-38-00-FF-FF-FF-FF-FF-FF-EF-7F-01-39-00-00-00-00-E0-FF-FF-EF-47-08-31-30-00-01-05-31-31-00-05-00-00-00-02-00-01-02-03-04-09-31-32-00-40-C5-E2-BA-E3-00-00-00-09-31-33-00-40-C5-E2-BA-E3-00-00-00-00", bson); }
/// <inheritdoc /> public override Task ExecuteResultAsync(ActionContext context) { var response = context.HttpContext.Response; response.ContentType = ContentType.Bson; if (StatusCode != null) { response.StatusCode = StatusCode.Value; } var serializerSettings = _serializerSettings; if (serializerSettings == null) { serializerSettings = context .HttpContext .RequestServices .GetRequiredService<IOptions<MvcJsonOptions>>() .Value .SerializerSettings; } using (var bsonWriter = new BsonWriter(response.Body)) { bsonWriter.CloseOutput = false; var jsonSerializer = JsonSerializer.Create(serializerSettings); jsonSerializer.Serialize(bsonWriter, Value); } return Task.FromResult(true); }
public void Export(Stream stream) { using (BsonWriter writer = new BsonWriter(stream)) { _jsonSerializer.Serialize(writer, _cardsByID); } }
public static async Task<byte[]> PackFileTransferMessageAsync(SongTransferMessage message) { byte[] serialized; using (var ms = new MemoryStream()) { using (var writer = new BsonWriter(ms)) { var serializer = new JsonSerializer(); await Task.Run(() => serializer.Serialize(writer, message)); } // Don't return earlier here, we don't know of the BsonWriter is finished. serialized = ms.ToArray(); } byte[] length = BitConverter.GetBytes(serialized.Length); // We have a fixed size of 4 bytes var returnData = new byte[length.Length + serialized.Length]; // We could simply call .ToArray() everywhere, but with Buffer.BlockCopy, we are // reducing memory pressure and CPU time on mobile devices by an order of magnitude Buffer.BlockCopy(length, 0, returnData, 0, length.Length); Buffer.BlockCopy(serialized, 0, returnData, length.Length, serialized.Length); return returnData; }
public bool SendCmdRequest(CmdRequest request) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.Connect("127.0.0.1", Port); using (NetworkStream stream = new NetworkStream(socket)) { using (BsonWriter writer = new BsonWriter(stream)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, request); writer.Flush(); writer.Close(); } stream.Close(); } } catch(Exception ex) { Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex); return false; } return true; }
public void DateTimeKindHandling() { DateTime value = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); writer.WriteStartObject(); writer.WritePropertyName("DateTime"); writer.WriteValue(value); writer.WriteEndObject(); byte[] bson = ms.ToArray(); JObject o; BsonReader reader; reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Utc); o = (JObject)JToken.ReadFrom(reader); Assert.AreEqual(value, (DateTime)o["DateTime"]); reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Local); o = (JObject)JToken.ReadFrom(reader); Assert.AreEqual(value.ToLocalTime(), (DateTime)o["DateTime"]); reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Unspecified); o = (JObject)JToken.ReadFrom(reader); Assert.AreEqual(DateTime.SpecifyKind(value.ToLocalTime(), DateTimeKind.Unspecified), (DateTime)o["DateTime"]); }
protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context) { var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; // NOTE: we don't dispose or close these as they would // close the stream, which is used by the rest of the pipeline. var writer = default(JsonWriter); if (contentHeaders.ContentType.MediaType == "application/bson") writer = new BsonWriter(stream); else writer = new JsonTextWriter(new StreamWriter(stream)); if (UsesQueryComposition) { serializer.Serialize(writer, ((IEnumerable)value).OfType<object>().ToList()); } else { serializer.Serialize(writer, value); } writer.Flush(); }
public void UseBsonSerializer() { var message = GetMyJsonTestMessage(); var serializer = new JsonSerializer(); byte[] serializedMessage; using (var stream = new MemoryStream()) using (var writer = new BsonWriter(stream)) { serializer.Serialize(writer, message); serializedMessage = stream.GetBuffer(); } MyJsonTestMessage deserializedMessage; using (var stream = new MemoryStream(serializedMessage)) using (var reader = new BsonReader(stream)) { deserializedMessage = serializer.Deserialize<MyJsonTestMessage>(reader); } Console.Out.WriteLine(deserializedMessage.GetHashCode() == message.GetHashCode()); }
public override void Serialize(Stream stream, object instance) { using (var writer = new BsonWriter(stream)) { base.Serialize(writer, instance); } }
public static void Serialize(Stream stream, object instance) { using (var writer = new BsonWriter(stream)) { serializer.Serialize(writer, instance); } }
public static byte[] Serialize(object[] methodParams) { List<String> complexParams = new List<String>(); object[] payload = new object[methodParams.Length + 1]; //elements int count = 1; foreach (object param in methodParams) { payload[count] = param; complexParams.Add(param.GetType().FullName); count++; } //header type payload[0] = complexParams; using (MemoryStream memoryStream = new MemoryStream(4096)) { using (BsonWriter bsonWriter = new BsonWriter(memoryStream)) { BsonObject bson = new BsonObject(); bson.Payload = payload; JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(bsonWriter, bson); } return memoryStream.ToArray(); } }
private void WriteBson(BsonWriter writer, Regex regex) { // Regular expression - The first cstring is the regex pattern, the second // is the regex options string. Options are identified by characters, which // must be stored in alphabetical order. Valid options are 'i' for case // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. string options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) options += "i"; if (HasFlag(regex.Options, RegexOptions.Multiline)) options += "m"; if (HasFlag(regex.Options, RegexOptions.Singleline)) options += "s"; options += "u"; if (HasFlag(regex.Options, RegexOptions.ExplicitCapture)) options += "x"; writer.WriteRegex(regex.ToString(), options); }
protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context) { var serializer = new JsonSerializer(); using (var writer = new BsonWriter(stream.PreventClose())) { serializer.Serialize(writer, value); writer.Flush(); } }
/// <summary> /// Called during serialization to create the <see cref="BsonWriter"/>. /// </summary> /// <param name="stream">The <see cref="Stream"/> to write to.</param> /// <returns>The <see cref="BsonWriter"/> used during serialization.</returns> protected virtual BsonWriter CreateBsonWriter(Stream stream) { var bsonWriter = new BsonWriter(stream) { CloseOutput = false }; return bsonWriter; }
public override void Serialize(Stream output, object graph) { if (graph == null) return; var writer = new BsonWriter(output) { DateTimeKindHandling = DateTimeKind.Utc }; this.Serialize(writer, graph); }
public static void Write(FileStream stream, object value) { using (var bw = new Newtonsoft.Json.Bson.BsonWriter(stream)) { var serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(bw, value); } }
public void PerformBinarySerialisation(System.IO.Stream outputStream, object graph, string jsCallbackName) { //MemoryStream ms = new MemoryStream(); JsonSerializer serializer = new JsonSerializer(); // serialize product to BSON BsonWriter writer = new BsonWriter(outputStream); serializer.Serialize(writer, graph); }
public virtual byte[] Serialize(object obj) { using (var outStream = new MemoryStream()) using (var bsonWriter = new BsonWriter(outStream)) { CreateSerializer().Serialize(bsonWriter, obj); return outStream.ToArray(); } }
private static byte[] SerializeInternal(object o) { using (var ms = new MemoryStream()) using (var writer = new BsonWriter(ms)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, o); return ms.ToArray(); } }
public void Serialize(Stream s, object item) { //Condition.Requires(s, "s").IsNotNull(); //Condition.Requires(item, "item").IsNotNull(); using (var w = new BsonWriter(s)) { Serializer.Serialize(w, item); } }
protected virtual byte[] Serialize(object obj) { using (var ms = new MemoryStream()) { var bw = new BsonWriter(ms); Serializer.Serialize(bw, obj); bw.Close(); return ms.ToArray(); } }
public void Execute(ClientInformation client, Stream clientStream) { using (var reader = new BsonReader(clientStream)) using (var writer = new BsonWriter(clientStream)) { try { Log.Info("Deserializing JSON-RPC request"); var request = serializer.Deserialize<JsonRpcRequest>(reader); if (request == null) throw new ArgumentException("No JSON-RPC request was sent"); var activityName = string.Format("{0} : {1}", client.RemoteAddress, request.Id); using (Log.BeginActivity(activityName, request.ActivityId)) { try { Log.Info("Validating request"); if (string.IsNullOrWhiteSpace(request.Service)) throw new ArgumentException("No service name was specified in the JSON-RPC request"); if (string.IsNullOrWhiteSpace(request.Method)) throw new ArgumentException("No service method was specified in the JSON-RPC request"); Log.InfoFormat("Resolving service {0}", request.Service); var serviceType = services.GetService(request.Service); if (serviceType == null) { throw new ArgumentException(string.Format("The service type {0} is not implemented on this server", request.Service)); } Log.InfoFormat("Constructing service {0}", serviceType.FullName); JsonRpcResponse response; using (var lease = serviceFactory.CreateService(serviceType)) { var service = lease.Service; response = serviceInvoker.Invoke(service, request); } SendResponse(writer, response); } catch (Exception ex) { SendResponse(writer, CreateError(ex, request)); } } } catch (Exception ex) { SendResponse(writer, CreateError(ex, null)); } } }
public byte[] Serialize(object item) { using (var s = new MemoryStream()) { using (var w = new BsonWriter(s)) { Serializer.Serialize(w, item); } return s.ToArray(); } }
/// <summary> /// Saves a user to the file. /// </summary> /// <param name="user">The user to be saved.</param> public async void SaveUser(User user) { StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; var file = await local.CreateFileAsync("user", CreationCollisionOption.ReplaceExisting); var fileStream = await file.OpenStreamForWriteAsync(); using (var writer = new BsonWriter(new BinaryWriter(fileStream))) { var serializer = new JsonSerializer(); serializer.Serialize(writer, user); } }
private static long WriteNewtonsoftBson(string path) { FileStream fs = File.OpenWrite(path); using (var bsonWriter = new BsonWriter(fs) { CloseOutput = false }) { var jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(bsonWriter, GetTestObjects()); bsonWriter.Flush(); } fs.Close(); return new FileInfo(path).Length; }
public static byte[] GetBytes(this StoredEvent<JObject> storedEvent) { var output = new MemoryStream(); var writer = new BinaryWriter(output); writer.Write(storedEvent.EventIdentifier.ToByteArray()); writer.Write(storedEvent.EventTimeStamp.Ticks); writer.Write(storedEvent.EventName); writer.Write(storedEvent.EventVersion.ToString()); var bsonWriter = new BsonWriter(output); storedEvent.Data.WriteTo(bsonWriter); return output.ToArray(); }
static byte[] BSON(object data) { var stream = new System.IO.MemoryStream(); using (var writer = new BsonWriter(stream)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, data); } return stream.ToArray(); }
public IRavenMQPublisher Add(string queue, object msg, JObject metadata) { var memoryStream = new MemoryStream(); using(var bsonWriter = new BsonWriter(memoryStream)) ToJson(msg).WriteTo(bsonWriter); return AddRaw(new IncomingMessage { Data = memoryStream.ToArray(), Metadata = metadata, Queue = queue, }); }
internal static Stream ToStream(this JObject jsonObject) { if (jsonObject == null) return Stream.Null; var stream = new MemoryStream(); var writer = new BsonWriter(stream); jsonObject.WriteTo(writer); stream.Position = 0; return stream; }
public void WriteSingleObject() { MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(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); }
public static Stream Serialize(JObject obj) { var stream = new MemoryStream(); using (var jsonWriter = new BsonWriter(stream)) { jsonWriter.CloseOutput = false; obj.WriteTo(jsonWriter); } stream.Position = 0; return stream; }