/// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, DateTimeOffset value) { var bsonWriter = context.Writer; // note: the DateTime portion cannot be serialized as a BsonType.DateTime because it is NOT in UTC switch (_representation) { case BsonType.Array: bsonWriter.WriteStartArray(); bsonWriter.WriteInt64(value.Ticks); bsonWriter.WriteInt32((int)value.Offset.TotalMinutes); bsonWriter.WriteEndArray(); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", BsonUtils.ToMillisecondsSinceEpoch(value.UtcDateTime)); bsonWriter.WriteInt64("Ticks", value.Ticks); bsonWriter.WriteInt32("Offset", (int)value.Offset.TotalMinutes); bsonWriter.WriteEndDocument(); break; case BsonType.String: bsonWriter.WriteString(XmlConvert.ToString(value)); break; default: var message = string.Format("'{0}' is not a valid DateTimeOffset representation.", _representation); throw new BsonSerializationException(message); } }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var dateTimeOffset = (DateTimeOffset)value; var representationSerializationOptions = EnsureSerializationOptions <RepresentationSerializationOptions>(options); switch (representationSerializationOptions.Representation) { case BsonType.Array: bsonWriter.WriteStartArray(); bsonWriter.WriteInt64(dateTimeOffset.UtcTicks); bsonWriter.WriteInt32((int)dateTimeOffset.Offset.TotalMinutes); bsonWriter.WriteEndArray(); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", BsonUtils.ToMillisecondsSinceEpoch(dateTimeOffset.UtcDateTime)); bsonWriter.WriteInt64("Ticks", dateTimeOffset.UtcTicks); bsonWriter.WriteInt32("Offset", (int)dateTimeOffset.Offset.TotalMinutes); bsonWriter.WriteEndDocument(); break; default: var message = string.Format("'{0}' is not a valid DateTimeOffset representation.", representationSerializationOptions.Representation); throw new BsonSerializationException(message); } }
public void TestDateTimeTenGen() { var utcNow = DateTime.UtcNow; var utcNowTruncated = utcNow.AddTicks(-(utcNow.Ticks % 10000)); var ms = BsonUtils.ToMillisecondsSinceEpoch(utcNowTruncated); var tenGenDate = string.Format("new Date({0})", ms); var tests = new TestData <BsonDateTime>[] { new TestData <BsonDateTime>(new BsonDateTime(long.MinValue), "new Date(-9223372036854775808)"), new TestData <BsonDateTime>(new BsonDateTime(0), "new Date(0)"), new TestData <BsonDateTime>(new BsonDateTime(long.MaxValue), "new Date(9223372036854775807)"), new TestData <BsonDateTime>(new BsonDateTime(DateTime.MinValue), "new Date(-62135596800000)"), new TestData <BsonDateTime>(new BsonDateTime(BsonConstants.UnixEpoch), "new Date(0)"), new TestData <BsonDateTime>(new BsonDateTime(utcNowTruncated), tenGenDate), new TestData <BsonDateTime>(new BsonDateTime(DateTime.MaxValue), "new Date(253402300799999)"), }; var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.TenGen }; foreach (var test in tests) { var json = test.Value.ToJson(jsonSettings); Assert.AreEqual(test.Expected, json); Assert.AreEqual(test.Value, BsonSerializer.Deserialize <BsonDateTime>(json)); } }
/// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTimeOffset value) { var bsonWriter = context.Writer; switch (_representation) { case BsonType.Array: bsonWriter.WriteStartArray(); bsonWriter.WriteInt64(value.Ticks); bsonWriter.WriteInt32((int)value.Offset.TotalMinutes); bsonWriter.WriteEndArray(); break; case BsonType.DateTime: var millisecondsSinceEpoch = value.ToUnixTimeMilliseconds(); bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", BsonUtils.ToMillisecondsSinceEpoch(value.UtcDateTime)); bsonWriter.WriteInt64("Ticks", value.Ticks); bsonWriter.WriteInt32("Offset", (int)value.Offset.TotalMinutes); bsonWriter.WriteEndDocument(); break; case BsonType.String: bsonWriter.WriteString(JsonConvert.ToString(value)); break; default: var message = string.Format("'{0}' is not a valid DateTimeOffset representation.", _representation); throw new BsonSerializationException(message); } }
// public methods /// <inheritdoc/> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var adapter = reader as BsonReaderAdapter; if (adapter != null && adapter.BsonValue != null && adapter.BsonValue.BsonType == BsonType.DateTime) { return((BsonDateTime)adapter.BsonValue); } switch (reader.TokenType) { case Newtonsoft.Json.JsonToken.Date: var dateTime = (DateTime)reader.Value; var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(dateTime); return(new BsonDateTime(millisecondsSinceEpoch)); case Newtonsoft.Json.JsonToken.Null: return(null); case Newtonsoft.Json.JsonToken.StartObject: return(ReadExtendedJson(reader)); default: var message = string.Format("Error reading BsonDateTime. Unexpected token: {0}.", reader.TokenType); throw new Newtonsoft.Json.JsonReaderException(message); } }
public void TestDateTimeStrict() { var utcNow = DateTime.UtcNow; var utcNowTruncated = utcNow.AddTicks(-(utcNow.Ticks % 10000)); var ms = BsonUtils.ToMillisecondsSinceEpoch(utcNowTruncated); var strictDate = string.Format("{{ \"$date\" : {0} }}", ms); var tests = new TestData <BsonDateTime>[] { new TestData <BsonDateTime>(new BsonDateTime(long.MinValue), "{ \"$date\" : -9223372036854775808 }"), new TestData <BsonDateTime>(new BsonDateTime(0), "{ \"$date\" : 0 }"), new TestData <BsonDateTime>(new BsonDateTime(long.MaxValue), "{ \"$date\" : 9223372036854775807 }"), new TestData <BsonDateTime>(new BsonDateTime(DateTime.MinValue), "{ \"$date\" : -62135596800000 }"), new TestData <BsonDateTime>(new BsonDateTime(BsonConstants.UnixEpoch), "{ \"$date\" : 0 }"), new TestData <BsonDateTime>(new BsonDateTime(utcNowTruncated), strictDate), new TestData <BsonDateTime>(new BsonDateTime(DateTime.MaxValue), "{ \"$date\" : 253402300799999 }"), }; var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; foreach (var test in tests) { var json = test.Value.ToJson(jsonSettings); Assert.Equal(test.Expected, json); Assert.Equal(test.Value, BsonSerializer.Deserialize <BsonDateTime>(json)); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var dateTime = (DateTimeOffset)value; var dateTimeSerializationOptions = EnsureSerializationOptions <DateTimeSerializationOptions>(options); DateTime utcDateTime; utcDateTime = BsonUtils.ToUniversalTime(dateTime.UtcDateTime); var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); switch (dateTimeSerializationOptions.Representation) { case BsonType.DateTime: bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTimeUTC", millisecondsSinceEpoch); bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks); bsonWriter.WriteEndDocument(); break; case BsonType.Int64: bsonWriter.WriteInt64(utcDateTime.Ticks); break; case BsonType.String: if (dateTimeSerializationOptions.DateOnly) { bsonWriter.WriteString(dateTime.ToString("yyyy-MM-dd")); } else { // we're not using XmlConvert.ToString because of bugs in Mono if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) { // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset dateTime = DateTime.SpecifyKind(dateTime.UtcDateTime, DateTimeKind.Unspecified); } else if (dateTime.UtcDateTime.Kind == DateTimeKind.Unspecified) { // serialize Unspecified as Local se we get the time zone offset dateTime = DateTime.SpecifyKind(dateTime.UtcDateTime, DateTimeKind.Local); } bsonWriter.WriteString(dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK")); } break; default: var message = string.Format("'{0}' is not a valid DateTimeOffset representation.", dateTimeSerializationOptions.Representation); throw new BsonSerializationException(message); } }
public void TestNewDateMillisecondsSinceEpoch() { var utcNow = DateTime.UtcNow; var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcNow); var json = string.Format("{{ date : new Date({0}) }}", millisecondsSinceEpoch); var document = BsonDocument.Parse(json); Assert.AreEqual(BsonType.DateTime, document["date"].BsonType); Assert.AreEqual(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(millisecondsSinceEpoch), document["date"].ToUniversalTime()); }
/// <summary> /// 安全地写入<c>DateTime</c>类型的字段 /// </summary> /// <param name="bsonWriter">Bson读取器</param> /// <param name="name">字段名</param> /// <param name="value">字段值</param> /// <param name="force">是否强制写入<c>null</c>值</param> public static void Write(this IBsonWriter bsonWriter, string name, DateTime?value, bool force = false) { if (value.HasValue) { bsonWriter.WriteDateTime(name, BsonUtils.ToMillisecondsSinceEpoch(value.Value)); } else if (force) { bsonWriter.WriteNull(name); } }
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTimeOffset value) { BsonWriter bsonWriter = (BsonWriter)context.Writer; var dateTime = (DateTimeOffset)value; DateTime utcDateTime; utcDateTime = BsonUtils.ToUniversalTime(dateTime.UtcDateTime); var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); bsonWriter.WriteDateTime(millisecondsSinceEpoch); }
/// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value) { var bsonWriter = context.Writer; var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(value.ToLocalTime()); bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch); bsonWriter.WriteInt32("Day", value.Day); bsonWriter.WriteInt32("Month", value.Month); bsonWriter.WriteInt32("Year", value.Year); bsonWriter.WriteEndDocument(); }
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { EvaluationResult er = (EvaluationResult)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteObjectId("_id", er.Id); bsonWriter.WriteDouble("Duration", er.DurationInSeconds); bsonWriter.WriteDateTime("Start", BsonUtils.ToMillisecondsSinceEpoch(er.startTime)); bsonWriter.WriteDateTime("End", BsonUtils.ToMillisecondsSinceEpoch(er.endTime)); bsonWriter.WriteString("Result", er.Result.ValueAsString); bsonWriter.WriteString("JSON", er.JSON); bsonWriter.WriteEndDocument(); }
public override void Serialize(BsonSerializationContext ctx, BsonSerializationArgs args, Date date) { if (date == null) { ctx.Writer.WriteNull(); } else { var dtUTC = BsonUtils.ToUniversalTime(date.DateTime); ctx.Writer.WriteStartDocument(); ctx.Writer.WriteDateTime("DateTime", BsonUtils.ToMillisecondsSinceEpoch(dtUTC)); ctx.Writer.WriteInt64("Ticks", dtUTC.Ticks); ctx.Writer.WriteEndDocument(); } }
public void Deserialize_should_return_expected_result(string json, string expectedResult) { var x = DateTimeOffset.Parse(expectedResult); var m = BsonUtils.ToMillisecondsSinceEpoch(x.UtcDateTime); var subject = new DateTimeOffsetSerializer(); DateTimeOffset result; using (var reader = new JsonReader(json)) { reader.ReadStartDocument(); reader.ReadName("x"); var context = BsonDeserializationContext.CreateRoot(reader); result = subject.Deserialize(context); reader.ReadEndDocument(); } result.Should().Be(DateTimeOffset.Parse(expectedResult)); }
// private methods private BsonDateTime ReadExtendedJson(Newtonsoft.Json.JsonReader reader) { long millisecondsSinceEpoch; ReadExpectedPropertyName(reader, "$date"); ReadToken(reader); switch (reader.TokenType) { case Newtonsoft.Json.JsonToken.Date: { var dateTime = (DateTime)reader.Value; millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(dateTime); } break; case Newtonsoft.Json.JsonToken.StartObject: { ReadExpectedPropertyName(reader, "$numberLong"); var formattedString = ReadStringValue(reader); ReadEndObject(reader); millisecondsSinceEpoch = long.Parse(formattedString, NumberFormatInfo.InvariantInfo); } break; case Newtonsoft.Json.JsonToken.String: { var formattedString = (string)reader.Value; var dateTime = DateTime.Parse(formattedString, DateTimeFormatInfo.InvariantInfo); millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(dateTime); } break; default: var message = string.Format("Error reading BsonDateTime. Unexpected token: {0}.", reader.TokenType); throw new Newtonsoft.Json.JsonReaderException(message); } ReadEndObject(reader); return(new BsonDateTime(millisecondsSinceEpoch)); }
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTimeOffset value) { context.Writer.WriteDateTime(BsonUtils.ToMillisecondsSinceEpoch(value.UtcDateTime)); }
/// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, DateTime value) { var bsonWriter = context.Writer; DateTime utcDateTime; if (_dateOnly) { if (value.TimeOfDay != TimeSpan.Zero) { throw new BsonSerializationException("TimeOfDay component is not zero."); } utcDateTime = DateTime.SpecifyKind(value, DateTimeKind.Utc); // not ToLocalTime } else { utcDateTime = BsonUtils.ToUniversalTime(value); } var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); switch (_representation) { case BsonType.DateTime: bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch); bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks); bsonWriter.WriteEndDocument(); break; case BsonType.Int64: bsonWriter.WriteInt64(utcDateTime.Ticks); break; case BsonType.String: if (_dateOnly) { bsonWriter.WriteString(value.ToString("yyyy-MM-dd")); } else { // we're not using XmlConvert.ToString because of bugs in Mono if (value == DateTime.MinValue || value == DateTime.MaxValue) { // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset value = DateTime.SpecifyKind(value, DateTimeKind.Unspecified); } else if (value.Kind == DateTimeKind.Unspecified) { // serialize Unspecified as Local se we get the time zone offset value = DateTime.SpecifyKind(value, DateTimeKind.Local); } bsonWriter.WriteString(value.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK")); } break; default: var message = string.Format("'{0}' is not a valid DateTime representation.", _representation); throw new BsonSerializationException(message); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var bsonDateTime = (BsonDateTime)value; var dateTimeSerializationOptions = EnsureSerializationOptions <DateTimeSerializationOptions>(options); DateTime utcDateTime = DateTime.MinValue; long millisecondsSinceEpoch; if (dateTimeSerializationOptions.DateOnly) { if (bsonDateTime.Value.TimeOfDay != TimeSpan.Zero) { throw new BsonSerializationException("TimeOfDay component is not zero."); } utcDateTime = DateTime.SpecifyKind(bsonDateTime.Value, DateTimeKind.Utc); // not ToLocalTime millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); } else { if (bsonDateTime.IsValidDateTime) { utcDateTime = BsonUtils.ToUniversalTime(bsonDateTime.Value); } millisecondsSinceEpoch = bsonDateTime.MillisecondsSinceEpoch; } switch (dateTimeSerializationOptions.Representation) { case BsonType.DateTime: bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch); if (bsonDateTime.IsValidDateTime) { bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks); } else { bsonWriter.WriteUndefined("Ticks"); } bsonWriter.WriteEndDocument(); break; case BsonType.Int64: if (bsonDateTime.IsValidDateTime) { bsonWriter.WriteInt64(utcDateTime.Ticks); } else { throw new BsonSerializationException("BsonDateTime is not a valid DateTime."); } break; case BsonType.String: if (dateTimeSerializationOptions.DateOnly) { bsonWriter.WriteString(bsonDateTime.Value.ToString("yyyy-MM-dd")); } else { // we're not using XmlConvert.ToString because of bugs in Mono var dateTime = bsonDateTime.Value; if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) { // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); } else if (dateTime.Kind == DateTimeKind.Unspecified) { // serialize Unspecified as Local se we get the time zone offset dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local); } bsonWriter.WriteString(dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK")); } break; default: var message = string.Format("'{0}' is not a valid DateTime representation.", dateTimeSerializationOptions.Representation); throw new BsonSerializationException(message); } } }
public void TestMinToMillisConversion() { var actual = BsonUtils.ToMillisecondsSinceEpoch(DateTime.MinValue); Assert.AreEqual(BsonConstants.DateTimeMinValueMillisecondsSinceEpoch, actual); }
private static void WriteDateTime(DateTime value, TextWriter output) { output.Write("{{ \"$date\" : {0} }}", BsonUtils.ToMillisecondsSinceEpoch(value.AddHours(8))); }
private static void WriteOffset(DateTimeOffset value, TextWriter output) { //output.Write("{{ \"$date\" : {0} }}", BsonUtils.ToMillisecondsSinceEpoch(value.UtcDateTime)); output.Write("{{ \"$date\" : {0} }}", BsonUtils.ToMillisecondsSinceEpoch(value.LocalDateTime.AddHours(8))); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var profileInfo = (SystemProfileInfo)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("ts", BsonUtils.ToMillisecondsSinceEpoch(profileInfo.Timestamp)); if (profileInfo.Info != null) { bsonWriter.WriteString("info", profileInfo.Info); } if (profileInfo.Op != null) { bsonWriter.WriteString("op", profileInfo.Op); } if (profileInfo.Namespace != null) { bsonWriter.WriteString("ns", profileInfo.Namespace); } if (profileInfo.Command != null) { bsonWriter.WriteName("command"); profileInfo.Command.WriteTo(bsonWriter); } if (profileInfo.Query != null) { bsonWriter.WriteName("query"); profileInfo.Query.WriteTo(bsonWriter); } if (profileInfo.UpdateObject != null) { bsonWriter.WriteName("updateobj"); profileInfo.UpdateObject.WriteTo(bsonWriter); } if (profileInfo.CursorId != 0) { bsonWriter.WriteInt64("cursorid", profileInfo.CursorId); } if (profileInfo.NumberToReturn != 0) { bsonWriter.WriteInt32("ntoreturn", profileInfo.NumberToReturn); } if (profileInfo.NumberToSkip != 0) { bsonWriter.WriteInt32("ntoskip", profileInfo.NumberToSkip); } if (profileInfo.Exhaust) { bsonWriter.WriteBoolean("exhaust", profileInfo.Exhaust); } if (profileInfo.NumberScanned != 0) { bsonWriter.WriteInt32("nscanned", profileInfo.NumberScanned); } if (profileInfo.IdHack) { bsonWriter.WriteBoolean("idhack", profileInfo.IdHack); } if (profileInfo.ScanAndOrder) { bsonWriter.WriteBoolean("scanAndOrder", profileInfo.ScanAndOrder); } if (profileInfo.Moved) { bsonWriter.WriteBoolean("moved", profileInfo.Moved); } if (profileInfo.FastMod) { bsonWriter.WriteBoolean("fastmod", profileInfo.FastMod); } if (profileInfo.FastModInsert) { bsonWriter.WriteBoolean("fastmodinsert", profileInfo.FastModInsert); } if (profileInfo.Upsert) { bsonWriter.WriteBoolean("upsert", profileInfo.Upsert); } if (profileInfo.KeyUpdates != 0) { bsonWriter.WriteInt32("keyUpdates", profileInfo.KeyUpdates); } if (profileInfo.Exception != null) { bsonWriter.WriteString("exception", profileInfo.Exception); } if (profileInfo.ExceptionCode != 0) { bsonWriter.WriteInt32("exceptionCode", profileInfo.ExceptionCode); } if (profileInfo.NumberReturned != 0) { bsonWriter.WriteInt32("nreturned", profileInfo.NumberReturned); } if (profileInfo.ResponseLength != 0) { bsonWriter.WriteInt32("responseLength", profileInfo.ResponseLength); } bsonWriter.WriteDouble("millis", profileInfo.Duration.TotalMilliseconds); if (profileInfo.Client != null) { bsonWriter.WriteString("client", profileInfo.Client); } if (profileInfo.User != null) { bsonWriter.WriteString("user", profileInfo.User); } if (profileInfo.Error != null) { bsonWriter.WriteString("err", profileInfo.Error); } if (profileInfo.Abbreviated != null) { bsonWriter.WriteString("abbreviated", profileInfo.Abbreviated); } bsonWriter.WriteEndDocument(); } }
void IBsonSerializable.Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("ts", BsonUtils.ToMillisecondsSinceEpoch(_timestamp)); if (_info != null) { bsonWriter.WriteString("info", _info); } if (_op != null) { bsonWriter.WriteString("op", _op); } if (_namespace != null) { bsonWriter.WriteString("ns", _namespace); } if (_command != null) { bsonWriter.WriteName("command"); _command.WriteTo(bsonWriter); } if (_query != null) { bsonWriter.WriteName("query"); _query.WriteTo(bsonWriter); } if (_updateObject != null) { bsonWriter.WriteName("updateobj"); _updateObject.WriteTo(bsonWriter); } if (_cursorId != 0) { bsonWriter.WriteInt64("cursorid", _cursorId); } if (_numberToReturn != 0) { bsonWriter.WriteInt32("ntoreturn", _numberToReturn); } if (_numberToSkip != 0) { bsonWriter.WriteInt32("ntoskip", _numberToSkip); } if (_exhaust) { bsonWriter.WriteBoolean("exhaust", _exhaust); } if (_numberScanned != 0) { bsonWriter.WriteInt32("nscanned", _numberScanned); } if (_idHack) { bsonWriter.WriteBoolean("idhack", _idHack); } if (_scanAndOrder) { bsonWriter.WriteBoolean("scanAndOrder", _scanAndOrder); } if (_moved) { bsonWriter.WriteBoolean("moved", _moved); } if (_fastMod) { bsonWriter.WriteBoolean("fastmod", _fastMod); } if (_fastModInsert) { bsonWriter.WriteBoolean("fastmodinsert", _fastModInsert); } if (_upsert) { bsonWriter.WriteBoolean("upsert", _upsert); } if (_keyUpdates != 0) { bsonWriter.WriteInt32("keyUpdates", _keyUpdates); } if (_exception != null) { bsonWriter.WriteString("exception", _exception); } if (_exceptionCode != 0) { bsonWriter.WriteInt32("exceptionCode", _exceptionCode); } if (_numberReturned != 0) { bsonWriter.WriteInt32("nreturned", _numberReturned); } if (_responseLength != 0) { bsonWriter.WriteInt32("responseLength", _responseLength); } bsonWriter.WriteDouble("millis", _duration.TotalMilliseconds); if (_client != null) { bsonWriter.WriteString("client", _client); } if (_user != null) { bsonWriter.WriteString("user", _user); } if (_error != null) { bsonWriter.WriteString("err", _error); } if (_abbreviated != null) { bsonWriter.WriteString("abbreviated", _abbreviated); } bsonWriter.WriteEndDocument(); }
void IBsonSerializable.Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("ts", BsonUtils.ToMillisecondsSinceEpoch(timestamp)); if (info != null) { bsonWriter.WriteString("info", info); } if (op != null) { bsonWriter.WriteString("op", op); } if (@namespace != null) { bsonWriter.WriteString("ns", @namespace); } if (command != null) { bsonWriter.WriteName("command"); command.WriteTo(bsonWriter); } if (query != null) { bsonWriter.WriteName("query"); query.WriteTo(bsonWriter); } if (updateObject != null) { bsonWriter.WriteName("updateobj"); updateObject.WriteTo(bsonWriter); } if (cursorId != 0) { bsonWriter.WriteInt64("cursorid", cursorId); } if (numberToReturn != 0) { bsonWriter.WriteInt32("ntoreturn", numberToReturn); } if (numberToSkip != 0) { bsonWriter.WriteInt32("ntoskip", numberToSkip); } if (exhaust) { bsonWriter.WriteBoolean("exhaust", exhaust); } if (numberScanned != 0) { bsonWriter.WriteInt32("nscanned", numberScanned); } if (idHack) { bsonWriter.WriteBoolean("idhack", idHack); } if (scanAndOrder) { bsonWriter.WriteBoolean("scanAndOrder", scanAndOrder); } if (moved) { bsonWriter.WriteBoolean("moved", moved); } if (fastMod) { bsonWriter.WriteBoolean("fastmod", fastMod); } if (fastModInsert) { bsonWriter.WriteBoolean("fastmodinsert", fastModInsert); } if (upsert) { bsonWriter.WriteBoolean("upsert", upsert); } if (keyUpdates != 0) { bsonWriter.WriteInt32("keyUpdates", keyUpdates); } if (exception != null) { bsonWriter.WriteString("exception", exception); } if (exceptionCode != 0) { bsonWriter.WriteInt32("exceptionCode", exceptionCode); } if (numberReturned != 0) { bsonWriter.WriteInt32("nreturned", numberReturned); } if (responseLength != 0) { bsonWriter.WriteInt32("responseLength", responseLength); } bsonWriter.WriteDouble("millis", duration.TotalMilliseconds); if (client != null) { bsonWriter.WriteString("client", client); } if (user != null) { bsonWriter.WriteString("user", user); } if (error != null) { bsonWriter.WriteString("err", error); } if (abbreviated != null) { bsonWriter.WriteString("abbreviated", abbreviated); } bsonWriter.WriteEndDocument(); }
public static void zWrite <T>(this BsonWriter bsonWriter, T value) { // implementation for the GetTypeCode method : protected virtual TypeCode GetTypeCodeImpl() // enum TypeCode : Empty = 0, Object = 1, DBNull = 2, Boolean = 3, Char = 4, SByte = 5, Byte = 6, Int16 = 7, UInt16 = 8, Int32 = 9, UInt32 = 10, Int64 = 11, UInt64 = 12, Single = 13, Double = 14, Decimal = 15, DateTime = 16, String = 18 // (bool)value : error cannot convert T to bool // value as bool : error the as operator must be used with a reference type or nullable type // bool b = __refvalue(__makeref(value), bool); // Generic Parse Method without Boxing http://stackoverflow.com/questions/390286/generic-parse-method-without-boxing // UnCommon C# keywords - A Look http://www.codeproject.com/Articles/38695/UnCommon-C-keywords-A-Look#refv if (bsonWriter == null) { return; } Type type = typeof(T); if (value == null) { bsonWriter.WriteNull(); } // nullable type int?, long?, ... else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { type = Nullable.GetUnderlyingType(type); switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: bsonWriter.WriteBoolean((bool)__refvalue(__makeref(value), bool?)); break; case TypeCode.DateTime: bsonWriter.WriteDateTime(BsonUtils.ToMillisecondsSinceEpoch((DateTime)__refvalue(__makeref(value), DateTime?))); break; case TypeCode.Double: bsonWriter.WriteDouble((double)__refvalue(__makeref(value), double?)); break; case TypeCode.Int32: bsonWriter.WriteInt32((int)__refvalue(__makeref(value), int?)); break; case TypeCode.Int64: bsonWriter.WriteInt64((long)__refvalue(__makeref(value), long?)); break; default: if (type == typeof(Date)) { bsonWriter.WriteDateTime(BsonUtils.ToMillisecondsSinceEpoch(((Date)__refvalue(__makeref(value), Date?)).DateTime)); } else { throw new PBException("unable to write type {0} with BsonWriter", type.zGetTypeName()); } break; } } else { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: bsonWriter.WriteBoolean(__refvalue(__makeref(value), bool)); break; case TypeCode.DateTime: bsonWriter.WriteDateTime(BsonUtils.ToMillisecondsSinceEpoch(__refvalue(__makeref(value), DateTime))); break; case TypeCode.Double: bsonWriter.WriteDouble(__refvalue(__makeref(value), double)); break; case TypeCode.Int32: bsonWriter.WriteInt32(__refvalue(__makeref(value), int)); break; case TypeCode.Int64: bsonWriter.WriteInt64(__refvalue(__makeref(value), long)); break; case TypeCode.String: bsonWriter.WriteString(value as string); break; default: if (type == typeof(byte[])) { bsonWriter.WriteBytes(value as byte[]); } else if (type == typeof(Date)) { bsonWriter.WriteDateTime(BsonUtils.ToMillisecondsSinceEpoch(__refvalue(__makeref(value), Date).DateTime)); } else { throw new PBException("unable to write type {0} with BsonWriter", type.zGetTypeName()); } break; } } }
/// <inheritdoc/> public override void WriteValue(DateTimeOffset value) { base.WriteValue(value); _wrappedWriter.WriteDateTime(BsonUtils.ToMillisecondsSinceEpoch(value.UtcDateTime)); }
private static void WriteDateTime(DateTime value, TextWriter output) { output.Write($"{{ \"$date\" : {BsonUtils.ToMillisecondsSinceEpoch(value)} }}"); }