Beispiel #1
0
        public void TestZeroToDateTimeConversion()
        {
            var actual = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(0);

            Assert.AreEqual(DateTimeKind.Utc, actual.Kind);
            Assert.AreEqual(BsonConstants.UnixEpoch, actual);
        }
 /// <summary>
 ///     安全地读入<c>DateTime</c>类型的字段
 /// </summary>
 /// <param name="bsonReader">Bson读取器</param>
 /// <param name="expected">字段名</param>
 /// <param name="read">字段名缓存</param>
 /// <returns>读取结果</returns>
 public static DateTime?ReadDateTime(this IBsonReader bsonReader, string expected, ref string read)
 => ReadStruct(
     bsonReader,
     expected,
     ref read,
     () =>
     BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()).ToUniversalTime());
Beispiel #3
0
        /// <summary>
        /// Writes a BSON DateTime to the writer.
        /// </summary>
        /// <param name="value">The number of milliseconds since the Unix epoch.</param>
        public override void WriteDateTime(long value)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteDateTime", BsonWriterState.Value, BsonWriterState.Initial);
            }

            WriteNameHelper(Name);
            var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);

            if (this.isIsoDateTime)
            {
                _textWriter.Write(string.Format("\"{0}\"", utcDateTime.ToLocalTime().ToString(ISODateTimeFormat)));
            }
            else
            {
                _textWriter.Write(string.Format("\"{0}\"", utcDateTime.ToLocalTime().ToString(LocalDateTimeFormat)));
            }

            State = GetNextState();
        }
Beispiel #4
0
        static object ReadObject(BsonReader bsonReader)         //_120509_173140 keep consistent
        {
            switch (bsonReader.GetCurrentBsonType())
            {
            case BsonType.Array: return(ReadArray(bsonReader));                                                                                               // replacement

            case BsonType.Binary: var binary = BsonSerializer.Deserialize <BsonValue>(bsonReader); return(BsonTypeMapper.MapToDotNetValue(binary) ?? binary); // byte[] or Guid else self

            case BsonType.Boolean: return(bsonReader.ReadBoolean());

            case BsonType.DateTime: return(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()));

            case BsonType.Document: return(ReadCustomObject(bsonReader));                    // replacement

            case BsonType.Double: return(bsonReader.ReadDouble());

            case BsonType.Int32: return(bsonReader.ReadInt32());

            case BsonType.Int64: return(bsonReader.ReadInt64());

            case BsonType.Null: bsonReader.ReadNull(); return(null);

            case BsonType.ObjectId: return(bsonReader.ReadObjectId());

            case BsonType.String: return(bsonReader.ReadString());

            default: return(BsonSerializer.Deserialize <BsonValue>(bsonReader));
            }
        }
Beispiel #5
0
        public void TestMinToDateTimeConversion()
        {
            var actual = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(
                BsonConstants.DateTimeMinValueMillisecondsSinceEpoch);

            Assert.AreEqual(DateTimeKind.Utc, actual.Kind);
            Assert.AreEqual(DateTime.MinValue, actual);
        }
Beispiel #6
0
        /// <summary>
        /// Writes a BSON DateTime to the writer.
        /// </summary>
        /// <param name="value">The number of milliseconds since the Unix epoch.</param>
        public override void WriteDateTime(
            long value
            )
        {
            if (disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (state != BsonWriterState.Value && state != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteDateTime", BsonWriterState.Value, BsonWriterState.Initial);
            }

            switch (settings.OutputMode)
            {
            case JsonOutputMode.Strict:
                WriteStartDocument();
                WriteInt64("$date", value);
                WriteEndDocument();
                break;

            case JsonOutputMode.JavaScript:
            case JsonOutputMode.TenGen:
                WriteNameHelper(name);
                textWriter.Write("new Date({0})", value);
                break;

            case JsonOutputMode.Shell:
                WriteNameHelper(name);
                if (settings.ShellVersion >= new Version(1, 8, 0))
                {
                    // use ISODate for values that fall within .NET's DateTime range, and "new Date" for all others
                    if (
                        value >= BsonConstants.DateTimeMinValueMillisecondsSinceEpoch &&
                        value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch
                        )
                    {
                        var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                        textWriter.Write("ISODate(\"{0}\")", utcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"));
                    }
                    else
                    {
                        textWriter.Write("new Date({0})", value);
                    }
                }
                else
                {
                    textWriter.Write("new Date({0})", value);
                }
                break;

            default:
                throw new BsonInternalException("Unexpected JsonOutputMode.");
            }

            state = GetNextState();
        }
        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>
        /// Writes a BSON DateTime to the writer.
        /// </summary>
        /// <param name="value">The number of milliseconds since the Unix epoch.</param>
        public override void WriteDateTime(long value)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteDateTime", BsonWriterState.Value, BsonWriterState.Initial);
            }

            WriteNameHelper(Name);
            switch (Settings.OutputMode)
            {
#pragma warning disable 618
            case JsonOutputMode.Strict:
#pragma warning restore 618
                _textWriter.Write("{{ \"$date\" : {0} }}", value);
                break;

            case JsonOutputMode.RelaxedExtendedJson:
                if (value >= 0 && value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                {
                    var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                    _textWriter.Write("{{ \"$date\" : \"{0}\" }}", utcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"));
                }
                else
                {
                    _textWriter.Write("{{ \"$date\" : {{ \"$numberLong\" : \"{0}\" }} }}", value);
                }
                break;

            case JsonOutputMode.CanonicalExtendedJson:
                _textWriter.Write("{{ \"$date\" : {{ \"$numberLong\" : \"{0}\" }} }}", value);
                break;

            case JsonOutputMode.Shell:
            default:
                // use ISODate for values that fall within .NET's DateTime range, and "new Date" for all others
                if (value >= BsonConstants.DateTimeMinValueMillisecondsSinceEpoch &&
                    value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                {
                    var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                    _textWriter.Write("ISODate(\"{0}\")", utcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"));
                }
                else
                {
                    _textWriter.Write("new Date({0})", value);
                }
                break;
            }

            State = GetNextState();
        }
        private ServerDescription BuildServerDescription(BsonDocument serverDescription, TimeSpan heartbeatInterval)
        {
            JsonDrivenHelper.EnsureAllFieldsAreValid(serverDescription, "address", "avg_rtt_ms", "tags", "type", "lastUpdateTime", "lastWrite", "maxWireVersion");

            var    endPoint             = EndPointHelper.Parse(serverDescription["address"].ToString());
            var    averageRoundTripTime = TimeSpan.FromMilliseconds(serverDescription.GetValue("avg_rtt_ms", 0.0).ToDouble());
            var    type   = GetServerType(serverDescription["type"].ToString());
            TagSet tagSet = null;

            if (serverDescription.Contains("tags"))
            {
                tagSet = BuildTagSet((BsonDocument)serverDescription["tags"]);
            }
            DateTime lastWriteTimestamp;

            if (serverDescription.Contains("lastWrite"))
            {
                lastWriteTimestamp = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(serverDescription["lastWrite"]["lastWriteDate"].ToInt64());
            }
            else
            {
                lastWriteTimestamp = _utcNow;
            }
            var      maxWireVersion   = serverDescription.GetValue("maxWireVersion", 5).ToInt32();
            var      wireVersionRange = new Range <int>(0, maxWireVersion);
            var      serverVersion    = maxWireVersion == 5 ? new SemanticVersion(3, 4, 0) : new SemanticVersion(3, 2, 0);
            DateTime lastUpdateTimestamp;

            if (serverDescription.Contains("lastUpdateTime"))
            {
                lastUpdateTimestamp = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(serverDescription.GetValue("lastUpdateTime", 0).ToInt64());
            }
            else
            {
                lastUpdateTimestamp = _utcNow;
            }

            var serverId = new ServerId(_clusterId, endPoint);

            return(new ServerDescription(
                       serverId,
                       endPoint,
                       averageRoundTripTime: averageRoundTripTime,
                       type: type,
                       lastUpdateTimestamp: lastUpdateTimestamp,
                       lastWriteTimestamp: lastWriteTimestamp,
                       heartbeatInterval: heartbeatInterval,
                       wireVersionRange: wireVersionRange,
                       version: serverVersion,
                       tags: tagSet,
                       state: ServerState.Connected));
        }
Beispiel #10
0
    public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
    {
        EvaluationResult er = new EvaluationResult();

        bsonReader.ReadStartDocument();
        er.Id = bsonReader.ReadObjectId();
        er.DurationInSeconds = bsonReader.ReadDouble();
        er.startTime         = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime());
        er.endTime           = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime());
        er.Result            = EvaluationStatus.Parse(bsonReader.ReadString());
        er.JSON = bsonReader.ReadString();
        bsonReader.ReadEndDocument();
        return(er);
    }
Beispiel #11
0
        /// <summary>
        /// Writes a BSON DateTime to the writer.
        /// </summary>
        /// <param name="value">The number of milliseconds since the Unix epoch.</param>
        public override void WriteDateTime(long value)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteDateTime", BsonWriterState.Value, BsonWriterState.Initial);
            }

            WriteNameHelper(Name);
            switch (_jsonWriterSettings.OutputMode)
            {
            case JsonOutputMode.Strict:
                _textWriter.Write("{{ \"$date\" : {0} }}", value);
                break;

            case JsonOutputMode.Shell:
            default:
                // use ISODate for values that fall within .NET's DateTime range, and "new Date" for all others
                if (value >= BsonConstants.DateTimeMinValueMillisecondsSinceEpoch &&
                    value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                {
                    if (_jsonWriterSettings.UseLocalTime)
                    {
                        var localDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value).ToLocalTime();
                        _textWriter.Write("ISODate(\"{0}\")", localDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFzzz"));
                    }
                    else
                    {
                        var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                        _textWriter.Write("ISODate(\"{0}\")", utcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"));
                    }
                }
                else
                {
                    _textWriter.Write("new Date({0})", value);
                }
                break;
            }

            State = GetNextState();
        }
Beispiel #12
0
        static object ReadObject(IBsonReader bsonReader)         //_120509_173140 sync, test
        {
            switch (bsonReader.GetCurrentBsonType())
            {
            case BsonType.Array: return(ReadArray(bsonReader));                    // replacement

            case BsonType.Boolean: return(bsonReader.ReadBoolean());

            case BsonType.DateTime: return(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()));

            case BsonType.Decimal128: return(Decimal128.ToDecimal(bsonReader.ReadDecimal128()));

            case BsonType.Document: return(ReadCustomObject(bsonReader));                    // replacement

            case BsonType.Double: return(bsonReader.ReadDouble());

            case BsonType.Int32: return(bsonReader.ReadInt32());

            case BsonType.Int64: return(bsonReader.ReadInt64());

            case BsonType.Null: bsonReader.ReadNull(); return(null);

            case BsonType.ObjectId: return(bsonReader.ReadObjectId());

            case BsonType.String: return(bsonReader.ReadString());

            case BsonType.Binary:
                var data = bsonReader.ReadBinaryData();
                switch (data.SubType)
                {
                case BsonBinarySubType.UuidLegacy:
                case BsonBinarySubType.UuidStandard:
                    return(data.ToGuid());

                default:
                    return(data);
                }

            default: return(BsonSerializer.Deserialize <BsonValue>(bsonReader));
            }
        }
Beispiel #13
0
        /// <summary>
        /// Writes a BSON timestamp to the writer.
        /// </summary>
        /// <param name="value">The combined timestamp/increment value.</param>
        public override void WriteTimestamp(long value)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteTimestamp", BsonWriterState.Value, BsonWriterState.Initial);
            }

            WriteStartDocument();
            if (!BsonDefaults.JsCompatibility)
            {
                WriteInt64("$timestamp", value);
            }
            else
            {
                var minLetfBound  = (BsonConstants.DateTimeMinValueMillisecondsSinceEpoch + BsonConstants.DateTimeValueMillisecondsForOneDate) / 1000;
                var maxRightBound = (BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch - BsonConstants.DateTimeValueMillisecondsForOneDate) / 1000;
                int sec           = (int)(value >> 32);
                int inc           = (int)value;
                if (sec >= minLetfBound && sec <= maxRightBound)
                {
                    DateTime utcDateTime;
                    DateTime localTime;
                    utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(sec * 1000L);
                    localTime   = utcDateTime.ToLocalTime();
                    _textWriter.Write(" \"$timestamp\" : \"{0}.{1}\"", localTime.ToString("yyyy-MM-dd-HH.mm.ss"), inc);
                }
                else
                {
                    // should nerver come here, if so, let't display by digits
                    WriteInt64("$timestamp", value);
                }
            }
            WriteEndDocument();
            State = GetNextState();
        }
        // explicit interface implementation
        object IBsonSerializable.Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
        {
            if (bsonReader.CurrentBsonType == Bson.BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            else
            {
                bsonReader.ReadStartDocument();
                BsonType bsonType;
                while ((bsonType = bsonReader.ReadBsonType()) != BsonType.EndOfDocument)
                {
                    var name = bsonReader.ReadName();
                    switch (name)
                    {
                    case "abbreviated":
                        abbreviated = bsonReader.ReadString();
                        break;

                    case "client":
                        client = bsonReader.ReadString();
                        break;

                    case "command":
                        command = BsonDocument.ReadFrom(bsonReader);
                        break;

                    case "cursorid":
                        cursorId = BsonValue.ReadFrom(bsonReader).ToInt64();
                        break;

                    case "err":
                        error = bsonReader.ReadString();
                        break;

                    case "exception":
                        exception = bsonReader.ReadString();
                        break;

                    case "exceptionCode":
                        exceptionCode = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "exhaust":
                        exhaust = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "fastmod":
                        fastMod = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "fastmodinsert":
                        fastModInsert = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "idhack":
                        idHack = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "info":
                        info = bsonReader.ReadString();
                        break;

                    case "keyUpdates":
                        keyUpdates = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "millis":
                        duration = TimeSpan.FromMilliseconds(BsonValue.ReadFrom(bsonReader).ToDouble());
                        break;

                    case "moved":
                        moved = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "nreturned":
                        numberReturned = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "ns":
                        @namespace = bsonReader.ReadString();
                        break;

                    case "nscanned":
                        numberScanned = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "ntoreturn":
                        numberToReturn = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "ntoskip":
                        numberToSkip = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "op":
                        op = bsonReader.ReadString();
                        break;

                    case "query":
                        query = BsonDocument.ReadFrom(bsonReader);
                        break;

                    case "responseLength":
                        responseLength = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "scanAndOrder":
                        scanAndOrder = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "ts":
                        timestamp = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime());
                        break;

                    case "updateobj":
                        updateObject = BsonDocument.ReadFrom(bsonReader);
                        break;

                    case "upsert":
                        upsert = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "user":
                        user = bsonReader.ReadString();
                        break;

                    default:
                        break;     // ignore unknown elements
                    }
                }
                bsonReader.ReadEndDocument();
                return(this);
            }
        }
Beispiel #15
0
 public override DateTimeOffset Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
 {
     return(new DateTimeOffset(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(context.Reader.ReadDateTime())).ToLocalTime());
 }
Beispiel #16
0
 public void TestGreaterThanMaxToDateTimeConversion()
 {
     var actual = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(
         BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch + 1);
 }
Beispiel #17
0
 public void TestLessThanMinToDateTimeConversion()
 {
     var actual = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(
         BsonConstants.DateTimeMinValueMillisecondsSinceEpoch - 1);
 }
Beispiel #18
0
 public void TestLessThanMinToDateTimeConversion()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                 BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(
                                                     BsonConstants.DateTimeMinValueMillisecondsSinceEpoch - 1));
 }
Beispiel #19
0
        /// <summary>
        /// Writes a BSON DateTime to the writer.
        /// </summary>
        /// <param name="value">The number of milliseconds since the Unix epoch.</param>
        public override void WriteDateTime(long value)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("JsonWriter");
            }
            if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
            {
                ThrowInvalidState("WriteDateTime", BsonWriterState.Value, BsonWriterState.Initial);
            }

            switch (_jsonWriterSettings.OutputMode)
            {
            case JsonOutputMode.Strict:
                WriteStartDocument();
                if (!BsonDefaults.JsCompatibility)
                {
                    WriteInt64("$date", value);
                }
                else
                {
                    // i am going to convert utc time to local time,
                    // for DateTime can only represent time in the range [0001-01-01 00:00:00, 9999-12-31 23:31:59],
                    // so i need to ensure the result of local time is in the bound of this range.

                    var minLetfBound   = BsonConstants.DateTimeMinValueMillisecondsSinceEpoch + BsonConstants.DateTimeValueMillisecondsForOneDate;
                    var maxRightBound  = BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch + BsonConstants.DateTimeValueMillisecondsForHalfDate;
                    var safeRightBound = BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch - BsonConstants.DateTimeValueMillisecondsForHalfDate;
                    if (value >= minLetfBound && value <= maxRightBound)
                    {
                        DateTime utcDateTime;
                        DateTime localTime;
                        if (value <= safeRightBound)
                        {
                            // when value is less or equal than safeRightBound
                            // the date of it's localtime must less or equal than "9999-12-31"
                            utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                            localTime   = utcDateTime.ToLocalTime();
                            if (localTime.Date.Year >= 1900 && localTime.Date.Year <= 9999)
                            {
                                // when the localtime is in the range of [1900-01-01 00:00:00, 9999-12-31 23:59:59]
                                // we show it in the format "xxxx-xx-xx"
                                _textWriter.Write(" \"$date\" : \"{0}\"", localTime.ToString("yyyy-MM-dd"));
                            }
                            else
                            {
                                WriteInt64("$date", value);
                            }
                        }
                        else if (value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                        {
                            // get the time zone
                            long spanMs = (long)TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds * 1000;
                            if (value + spanMs <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                            {
                                // when span is negative, should come here to show by format
                                utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                                localTime   = utcDateTime.ToLocalTime();
                                _textWriter.Write(" \"$date\" : \"{0}\"", localTime.ToString("yyyy-MM-dd"));
                            }
                            else
                            {
                                // when span is positive, may be come here to show by digits
                                WriteInt64("$date", value);
                            }
                        }
                        else
                        {
                            // get the time zone
                            long spanMs = (long)TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds * 1000;
                            if (spanMs >= 0)
                            {
                                // in [max_utc, max_utc+12], localtime must be greater than "9999-12-31",
                                // so, output the digits directly
                                WriteInt64("$date", value);
                            }
                            else
                            {
                                if (value + spanMs <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                                {
                                    // in [max_utc-12, max_utc) whose localtime is "9999-12-31"
                                    _textWriter.Write(" \"$date\" : \"9999-12-31\"");
                                }
                                else
                                {
                                    // in [max_utc-12, max_utc) whose localtime is greater than "9999-12-31"
                                    WriteInt64("$date", value);
                                }
                            }
                        }
                    }
                    else
                    {
                        WriteInt64("$date", value);
                    }
                }
                WriteEndDocument();
                break;

            case JsonOutputMode.JavaScript:
            case JsonOutputMode.TenGen:
                WriteNameHelper(Name);
                _textWriter.Write("new Date({0})", value);
                break;

            case JsonOutputMode.Shell:
                WriteNameHelper(Name);
                if (_jsonWriterSettings.ShellVersion >= new Version(1, 8, 0))
                {
                    // use ISODate for values that fall within .NET's DateTime range, and "new Date" for all others
                    if (value >= BsonConstants.DateTimeMinValueMillisecondsSinceEpoch &&
                        value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
                    {
                        var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
                        _textWriter.Write("ISODate(\"{0}\")", utcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"));
                    }
                    else
                    {
                        _textWriter.Write("new Date({0})", value);
                    }
                }
                else
                {
                    _textWriter.Write("new Date({0})", value);
                }
                break;

            default:
                throw new BsonInternalException("Unexpected JsonOutputMode.");
            }

            State = GetNextState();
        }
Beispiel #20
0
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyTypes(nominalType, actualType, typeof(SystemProfileInfo));

            if (bsonReader.GetCurrentBsonType() == Bson.BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            else
            {
                var profileInfo = new SystemProfileInfo();

                bsonReader.ReadStartDocument();
                BsonType bsonType;
                while ((bsonType = bsonReader.ReadBsonType()) != BsonType.EndOfDocument)
                {
                    var name = bsonReader.ReadName();
                    switch (name)
                    {
                    case "abbreviated":
                        profileInfo.Abbreviated = bsonReader.ReadString();
                        break;

                    case "client":
                        profileInfo.Client = bsonReader.ReadString();
                        break;

                    case "command":
                        profileInfo.Command = BsonDocument.ReadFrom(bsonReader);
                        break;

                    case "cursorid":
                        profileInfo.CursorId = BsonValue.ReadFrom(bsonReader).ToInt64();
                        break;

                    case "err":
                        profileInfo.Error = bsonReader.ReadString();
                        break;

                    case "exception":
                        profileInfo.Exception = bsonReader.ReadString();
                        break;

                    case "exceptionCode":
                        profileInfo.ExceptionCode = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "exhaust":
                        profileInfo.Exhaust = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "fastmod":
                        profileInfo.FastMod = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "fastmodinsert":
                        profileInfo.FastModInsert = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "idhack":
                        profileInfo.IdHack = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "info":
                        profileInfo.Info = bsonReader.ReadString();
                        break;

                    case "keyUpdates":
                        profileInfo.KeyUpdates = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "millis":
                        profileInfo.Duration = TimeSpan.FromMilliseconds(BsonValue.ReadFrom(bsonReader).ToDouble());
                        break;

                    case "moved":
                        profileInfo.Moved = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "nreturned":
                        profileInfo.NumberReturned = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "ns":
                        profileInfo.Namespace = bsonReader.ReadString();
                        break;

                    case "nscanned":
                        profileInfo.NumberScanned = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "ntoreturn":
                        profileInfo.NumberToReturn = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "ntoskip":
                        profileInfo.NumberToSkip = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "op":
                        profileInfo.Op = bsonReader.ReadString();
                        break;

                    case "query":
                        profileInfo.Query = BsonDocument.ReadFrom(bsonReader);
                        break;

                    case "responseLength":
                        profileInfo.ResponseLength = BsonValue.ReadFrom(bsonReader).ToInt32();
                        break;

                    case "scanAndOrder":
                        profileInfo.ScanAndOrder = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "ts":
                        profileInfo.Timestamp = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime());
                        break;

                    case "updateobj":
                        profileInfo.UpdateObject = BsonDocument.ReadFrom(bsonReader);
                        break;

                    case "upsert":
                        profileInfo.Upsert = BsonValue.ReadFrom(bsonReader).ToBoolean();
                        break;

                    case "user":
                        profileInfo.User = bsonReader.ReadString();
                        break;

                    default:
                        break;     // ignore unknown elements
                    }
                }
                bsonReader.ReadEndDocument();

                return(profileInfo);
            }
        }