Esempio n. 1
0
        public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var      bsonReader      = context.Reader;
            var      currentBsonType = bsonReader.GetCurrentBsonType();
            DateTime value;

            switch (currentBsonType)
            {
            case BsonType.Document:
                value = new DateTime();
                _helper.DeserializeMembers(context,
                                           (elementName, flag) =>
                {
                    if (flag != DATE_TIME_FLAG)
                    {
                        if (flag != TICKS_FLAG)
                        {
                            return;
                        }

                        value = new DateTime(_int64Serializer.Deserialize(context), DateTimeKind.Utc);
                    }
                    else
                    {
                        bsonReader.SkipValue();
                    }
                });
                break;

            default:
                throw CreateCannotDeserializeFromBsonTypeException(currentBsonType);
            }

            switch (Kind)
            {
            case DateTimeKind.Local:
                value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), DateTimeKind.Local);
                break;

            case DateTimeKind.Unspecified:
                value = DateTime.SpecifyKind(value, DateTimeKind.Unspecified);
                break;

            case DateTimeKind.Utc:
                value = BsonUtils.ToUniversalTime(value);
                break;

            default:
                throw CreateCannotDeserializeFromBsonTypeException(currentBsonType);
            }

            return(value);
        }
Esempio n. 2
0
        /// <summary>
        /// 将任意类型的对象转成BsonDocument类型的对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static BsonDocument ConvertBsonDocument(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            Dictionary <string, object> dict = new Dictionary <string, object>();

            PropertyInfo[] propertyInfos = obj.GetType().GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (!propertyInfo.CanRead)
                {
                    continue;
                }
                object value = propertyInfo.GetValue(obj, null);
                if (value != null && value != DBNull.Value)
                {
                    if (value.GetType().FullName == DECIMAL_TYPE_FULLNAME)
                    {
                        dict[propertyInfo.Name] = Convert.ToDouble(value);
                    }
                    else if (value.GetType().FullName == DATETIME_TYPE_FULLNAME)
                    {// [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
                        dict[propertyInfo.Name] = BsonUtils.ToLocalTime(Convert.ToDateTime(value));
                    }
                    //else if (value.GetType().BaseType.FullName == typeof(Enum).FullName)
                    //{
                    //    dict[propertyInfo.Name] = (int)value;
                    //}
                    else
                    {
                        dict[propertyInfo.Name] = value;
                    }
                }
            }
            BsonDocument document = new BsonDocument(dict);

            return(document);
        }
Esempio n. 3
0
        /// <summary>
        /// 将更新的对象,变成UpdateDocument类型之后,可以直接调用带有IMongoUpdate类型的Update方法了.
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static UpdateDocument ConvertUpdateDocument(object entity)
        {
            if (entity == null)
            {
                return(null);
            }
            PropertyInfo[] propertyInfos     = entity.GetType().GetProperties();
            Dictionary <string, object> dict = new Dictionary <string, object>();

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                object value = propertyInfo.GetValue(entity, null);
                if (value != null)
                {
                    if (value.GetType().FullName == DECIMAL_TYPE_FULLNAME)
                    {
                        dict[propertyInfo.Name] = Convert.ToDouble(value);
                    }
                    else if (value.GetType().FullName == DATETIME_TYPE_FULLNAME)
                    {// [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
                        dict[propertyInfo.Name] = BsonUtils.ToLocalTime(Convert.ToDateTime(value));
                    }
                    //else if (value.GetType().BaseType.FullName == typeof(Enum).FullName)
                    //{
                    //    dict[propertyInfo.Name] = (int)value;
                    //}
                    else
                    {
                        dict[propertyInfo.Name] = value;
                    }
                }
            }
            //UpdateDocument updateDocument = new UpdateDocument(dict);
            QueryDocument  queryDocument  = new QueryDocument(dict);//wangyunpeng 2015-7-14 修改Mongodb支持批量更新
            UpdateDocument updateDocument = new UpdateDocument {
                { "$set", queryDocument }
            };

            return(updateDocument);
        }
        // public methods
        /// <summary>
        /// Deserializes a value.
        /// </summary>
        /// <param name="context">The deserialization context.</param>
        /// <returns>An object.</returns>
        public override DateTime Deserialize(BsonDeserializationContext context)
        {
            var      bsonReader = context.Reader;
            DateTime value;

            var bsonType = bsonReader.GetCurrentBsonType();

            switch (bsonType)
            {
            case BsonType.DateTime:
                // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly
                value = new BsonDateTime(bsonReader.ReadDateTime()).ToUniversalTime();
                break;

            case BsonType.Document:
                value = default(DateTime);
                _helper.DeserializeMembers(context, (elementName, flag) =>
                {
                    switch (flag)
                    {
                    case Flags.DateTime: bsonReader.SkipValue(); break;         // ignore value (use Ticks instead)

                    case Flags.Ticks: value = new DateTime(context.DeserializeWithChildContext(_int64Serializer), DateTimeKind.Utc); break;
                    }
                });
                break;

            case BsonType.Int64:
                value = DateTime.SpecifyKind(new DateTime(bsonReader.ReadInt64()), DateTimeKind.Utc);
                break;

            case BsonType.String:
                // note: we're not using XmlConvert because of bugs in Mono
                if (_dateOnly)
                {
                    value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc);
                }
                else
                {
                    var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" };
                    value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
                }
                break;

            default:
                throw CreateCannotDeserializeFromBsonTypeException(bsonType);
            }

            if (_dateOnly)
            {
                if (value.TimeOfDay != TimeSpan.Zero)
                {
                    throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero.");
                }
                value = DateTime.SpecifyKind(value, _kind); // not ToLocalTime or ToUniversalTime!
            }
            else
            {
                switch (_kind)
                {
                case DateTimeKind.Local:
                case DateTimeKind.Unspecified:
                    value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), _kind);
                    break;

                case DateTimeKind.Utc:
                    value = BsonUtils.ToUniversalTime(value);
                    break;
                }
            }

            return(value);
        }
Esempio n. 5
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(BsonDateTime));
            var dateTimeSerializationOptions = EnsureSerializationOptions <DateTimeSerializationOptions>(options);

            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            else
            {
                long?millisecondsSinceEpoch = null;
                long?ticks = null;
                switch (bsonType)
                {
                case BsonType.DateTime:
                    millisecondsSinceEpoch = bsonReader.ReadDateTime();
                    break;

                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    millisecondsSinceEpoch = bsonReader.ReadDateTime("DateTime");
                    bsonReader.ReadName("Ticks");
                    var ticksValue = BsonValue.ReadFrom(bsonReader);
                    if (!ticksValue.IsBsonUndefined)
                    {
                        ticks = ticksValue.ToInt64();
                    }
                    bsonReader.ReadEndDocument();
                    break;

                case BsonType.Int64:
                    ticks = bsonReader.ReadInt64();
                    break;

                case BsonType.String:
                    // note: we're not using XmlConvert because of bugs in Mono
                    DateTime dateTime;
                    if (dateTimeSerializationOptions.DateOnly)
                    {
                        dateTime = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc);
                    }
                    else
                    {
                        var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", };
                        dateTime = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
                    }
                    ticks = dateTime.Ticks;
                    break;

                default:
                    var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
                }

                BsonDateTime bsonDateTime;
                if (ticks.HasValue)
                {
                    bsonDateTime = BsonDateTime.Create(new DateTime(ticks.Value, DateTimeKind.Utc));
                }
                else
                {
                    bsonDateTime = BsonDateTime.Create(millisecondsSinceEpoch.Value);
                }

                if (dateTimeSerializationOptions.DateOnly)
                {
                    var dateTime = bsonDateTime.Value;
                    if (dateTime.TimeOfDay != TimeSpan.Zero)
                    {
                        throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero.");
                    }
                    bsonDateTime = BsonDateTime.Create(DateTime.SpecifyKind(dateTime, dateTimeSerializationOptions.Kind)); // not ToLocalTime or ToUniversalTime!
                }
                else
                {
                    if (bsonDateTime.IsValidDateTime)
                    {
                        var dateTime = bsonDateTime.Value;
                        switch (dateTimeSerializationOptions.Kind)
                        {
                        case DateTimeKind.Local:
                        case DateTimeKind.Unspecified:
                            dateTime = DateTime.SpecifyKind(BsonUtils.ToLocalTime(dateTime), dateTimeSerializationOptions.Kind);
                            break;

                        case DateTimeKind.Utc:
                            dateTime = BsonUtils.ToUniversalTime(dateTime);
                            break;
                        }
                        bsonDateTime = BsonDateTime.Create(dateTime);
                    }
                    else
                    {
                        if (dateTimeSerializationOptions.Kind != DateTimeKind.Utc)
                        {
                            throw new FileFormatException("BsonDateTime is outside the range of .NET DateTime.");
                        }
                    }
                }

                return(bsonDateTime);
            }
        }
Esempio n. 6
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(DateTime));

            var      dateTimeOptions = (options == null) ? DateTimeSerializationOptions.Defaults : (DateTimeSerializationOptions)options;
            DateTime value;

            var bsonType = bsonReader.CurrentBsonType;

            switch (bsonType)
            {
            case BsonType.DateTime:
                // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly
                value = BsonDateTime.Create(bsonReader.ReadDateTime()).Value;
                break;

            case BsonType.Document:
                bsonReader.ReadStartDocument();
                bsonReader.ReadDateTime("DateTime");     // ignore value (use Ticks instead)
                value = new DateTime(bsonReader.ReadInt64("Ticks"), DateTimeKind.Utc);
                bsonReader.ReadEndDocument();
                break;

            case BsonType.Int64:
                value = DateTime.SpecifyKind(new DateTime(bsonReader.ReadInt64()), DateTimeKind.Utc);
                break;

            case BsonType.String:
                // note: we're not using XmlConvert because of bugs in Mono
                if (dateTimeOptions.DateOnly)
                {
                    value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc);
                }
                else
                {
                    var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" };
                    value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
                }
                break;

            default:
                var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType);
                throw new FileFormatException(message);
            }

            if (dateTimeOptions.DateOnly)
            {
                if (value.TimeOfDay != TimeSpan.Zero)
                {
                    throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero.");
                }
                value = DateTime.SpecifyKind(value, dateTimeOptions.Kind); // not ToLocalTime or ToUniversalTime!
            }
            else
            {
                switch (dateTimeOptions.Kind)
                {
                case DateTimeKind.Local:
                case DateTimeKind.Unspecified:
                    value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), dateTimeOptions.Kind);
                    break;

                case DateTimeKind.Utc:
                    value = BsonUtils.ToUniversalTime(value);
                    break;
                }
            }

            return(value);
        }
Esempio n. 7
0
 /// <summary>
 /// 将当前时间转换为Unix时间
 /// </summary>
 /// <param name="currentDateTime"></param>
 /// <returns></returns>
 public static DateTime ChangeLocalDateTime(DateTime currentDateTime)
 {
     return(BsonUtils.ToLocalTime(currentDateTime));
 }