public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            object value = null;
            if (bsonReader.CurrentBsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
            }
            else
            {
                bsonReader.ReadStartArray();
                var idList = new List<ObjectId>();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var id = (ObjectId)BsonSerializer.Deserialize(bsonReader, typeof(ObjectId));
                    idList.Add(id);
                }
                bsonReader.ReadEndArray();

                if (idList.Count > 0)
                {
                    var cursor = MongoDbProvider.Database.GetCollection(DocumentType, DocumentType.Name)
                        .FindAs(DocumentType, Query.In("_id", BsonArray.Create(idList)));

                    var documents = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(DocumentType));
                    foreach (var document in cursor)
                    {
                        documents.Add(document);
                    }
                    value = documents;
                }
            }
            return value;
        }
		private static bool IsRelationalAssociation(BsonReader bsonReader, Type nominalType)
		{
			if (bsonReader.State != BsonReaderState.Value || bsonReader.CurrentBsonType != BsonType.ObjectId)
				return false;

			return IsRelationalType(nominalType);
		}
 // 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, // ignored
     IBsonSerializationOptions options)
 {
     var bsonType = bsonReader.GetCurrentBsonType();
     switch (bsonType)
     {
         case BsonType.Array: return (BsonValue)BsonArraySerializer.Instance.Deserialize(bsonReader, typeof(BsonArray), options);
         case BsonType.Binary: return (BsonValue)BsonBinaryDataSerializer.Instance.Deserialize(bsonReader, typeof(BsonBinaryData), options);
         case BsonType.Boolean: return (BsonValue)BsonBooleanSerializer.Instance.Deserialize(bsonReader, typeof(BsonBoolean), options);
         case BsonType.DateTime: return (BsonValue)BsonDateTimeSerializer.Instance.Deserialize(bsonReader, typeof(BsonDateTime), options);
         case BsonType.Document: return (BsonValue)BsonDocumentSerializer.Instance.Deserialize(bsonReader, typeof(BsonDocument), options);
         case BsonType.Double: return (BsonValue)BsonDoubleSerializer.Instance.Deserialize(bsonReader, typeof(BsonDouble), options);
         case BsonType.Int32: return (BsonValue)BsonInt32Serializer.Instance.Deserialize(bsonReader, typeof(BsonInt32), options);
         case BsonType.Int64: return (BsonValue)BsonInt64Serializer.Instance.Deserialize(bsonReader, typeof(BsonInt64), options);
         case BsonType.JavaScript: return (BsonValue)BsonJavaScriptSerializer.Instance.Deserialize(bsonReader, typeof(BsonJavaScript), options);
         case BsonType.JavaScriptWithScope: return (BsonValue)BsonJavaScriptWithScopeSerializer.Instance.Deserialize(bsonReader, typeof(BsonJavaScriptWithScope), options);
         case BsonType.MaxKey: return (BsonValue)BsonMaxKeySerializer.Instance.Deserialize(bsonReader, typeof(BsonMaxKey), options);
         case BsonType.MinKey: return (BsonValue)BsonMinKeySerializer.Instance.Deserialize(bsonReader, typeof(BsonMinKey), options);
         case BsonType.Null: return (BsonValue)BsonNullSerializer.Instance.Deserialize(bsonReader, typeof(BsonNull), options);
         case BsonType.ObjectId: return (BsonValue)BsonObjectIdSerializer.Instance.Deserialize(bsonReader, typeof(BsonObjectId), options);
         case BsonType.RegularExpression: return (BsonValue)BsonRegularExpressionSerializer.Instance.Deserialize(bsonReader, typeof(BsonRegularExpression), options);
         case BsonType.String: return (BsonValue)BsonStringSerializer.Instance.Deserialize(bsonReader, typeof(BsonString), options);
         case BsonType.Symbol: return (BsonValue)BsonSymbolSerializer.Instance.Deserialize(bsonReader, typeof(BsonSymbol), options);
         case BsonType.Timestamp: return (BsonValue)BsonTimestampSerializer.Instance.Deserialize(bsonReader, typeof(BsonTimestamp), options);
         case BsonType.Undefined: return (BsonValue)BsonUndefinedSerializer.Instance.Deserialize(bsonReader, typeof(BsonUndefined), options);
         default:
             var message = string.Format("Invalid BsonType {0}.", bsonType);
             throw new BsonInternalException(message);
     }
 }
 public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
 {
     int timestamp, machine, increment;
     short pid;
     bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment);
     return new ObjectId(timestamp, machine, pid, increment).ToString();
 }
Example #5
0
        public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            if (_trace)
                pb.Trace.WriteLine("ZStringArraySerializer.Deserialize()");

            VerifyTypes(nominalType, actualType, typeof(ZStringArray));

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Array:
                    bsonReader.ReadStartArray();
                    //return new ZString(bsonReader.ReadString());
                    var array = new List<string>();
                    bsonType = bsonReader.ReadBsonType();
                    while (bsonType != BsonType.EndOfDocument)
                    {
                        if (bsonType != BsonType.String)
                            throw new PBException("error ZStringArray cannot contain value of type {0}", bsonType);
                        var value = bsonReader.ReadString();
                        array.Add(value);
                        bsonType = bsonReader.ReadBsonType();
                    }
                    bsonReader.ReadEndArray();
                    return new ZStringArray(array.ToArray());
                default:
                    throw new PBException("error cannot deserialize ZStringArray from BsonType {0}.", bsonType);
            }
        }
 public OXmlSimpleFieldElement _Deserialize(BsonReader bsonReader, IBsonSerializationOptions options)
 {
     OXmlSimpleFieldElement element = new OXmlSimpleFieldElement();
     while (true)
     {
         BsonType bsonType = bsonReader.ReadBsonType();
         if (bsonType == BsonType.EndOfDocument)
             break;
         string name = bsonReader.ReadName();
         switch (name.ToLower())
         {
             case "type":
                 if (bsonType != BsonType.String)
                     throw new PBException($"wrong type value {bsonType}");
                 string type = bsonReader.ReadString();
                 if (type.ToLower() != "simplefield")
                     throw new PBException($"invalid Type {type} when deserialize OXmlSimpleFieldElement");
                 break;
             case "instruction":
                 if (bsonType == BsonType.Null)
                     break;
                 if (bsonType != BsonType.String)
                     throw new PBException($"wrong Instruction value {bsonType}");
                 element.Instruction = bsonReader.ReadString();
                 break;
             default:
                 throw new PBException($"unknow SimpleField value \"{name}\"");
         }
     }
     return element;
 }
        public override object Deserialize(
			BsonReader bsonReader,
			Type nominalType,
			IBsonSerializationOptions options
			)
        {
            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return null;
            }

            var nvc = new NameValueCollection();

            bsonReader.ReadStartArray();
            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                bsonReader.ReadStartArray();
                var key = (string)StringSerializer.Instance.Deserialize(bsonReader, typeof(string), options);
                var val = (string)StringSerializer.Instance.Deserialize(bsonReader, typeof(string), options);
                bsonReader.ReadEndArray();
                nvc.Add(key, val);
            }
            bsonReader.ReadEndArray();

            return nvc;
        }
        // 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(decimal));
            var representationSerializationOptions = EnsureSerializationOptions<RepresentationSerializationOptions>(options);

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Array:
                    var array = (BsonArray)BsonArraySerializer.Instance.Deserialize(bsonReader, typeof(BsonArray), null);
                    var bits = new int[4];
                    bits[0] = array[0].AsInt32;
                    bits[1] = array[1].AsInt32;
                    bits[2] = array[2].AsInt32;
                    bits[3] = array[3].AsInt32;
                    return new decimal(bits);
                case BsonType.Double:
                    return representationSerializationOptions.ToDecimal(bsonReader.ReadDouble());
                case BsonType.Int32:
                    return representationSerializationOptions.ToDecimal(bsonReader.ReadInt32());
                case BsonType.Int64:
                    return representationSerializationOptions.ToDecimal(bsonReader.ReadInt64());
                case BsonType.String:
                    return XmlConvert.ToDecimal(bsonReader.ReadString());
                default:
                    var message = string.Format("Cannot deserialize Decimal from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
        // 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(DateTimeOffset));

            BsonType bsonType = bsonReader.GetCurrentBsonType();
            long ticks;
            TimeSpan offset;
            switch (bsonType)
            {
                case BsonType.Array:
                    bsonReader.ReadStartArray();
                    ticks = bsonReader.ReadInt64();
                    offset = TimeSpan.FromMinutes(bsonReader.ReadInt32());
                    bsonReader.ReadEndArray();
                    return new DateTimeOffset(ticks, offset);
                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadDateTime("DateTime"); // ignore value
                    ticks = bsonReader.ReadInt64("Ticks");
                    offset = TimeSpan.FromMinutes(bsonReader.ReadInt32("Offset"));
                    bsonReader.ReadEndDocument();
                    return new DateTimeOffset(ticks, offset);
                case BsonType.String:
                    return XmlConvert.ToDateTimeOffset(bsonReader.ReadString());
                default:
                    var message = string.Format("Cannot deserialize DateTimeOffset from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
        // 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(bool));

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Boolean:
                    return bsonReader.ReadBoolean();
                case BsonType.Double:
                    return bsonReader.ReadDouble() != 0.0;
                case BsonType.Int32:
                    return bsonReader.ReadInt32() != 0;
                case BsonType.Int64:
                    return bsonReader.ReadInt64() != 0;
                case BsonType.Null:
                    bsonReader.ReadNull();
                    return false;
                case BsonType.String:
                    return XmlConvert.ToBoolean(bsonReader.ReadString().ToLower());
                default:
                    var message = string.Format("Cannot deserialize Boolean from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
        // 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)
        {
            if (bsonReader.GetCurrentBsonType() == BsonType.Null)
            {
                bsonReader.ReadNull();
                return null;
            }
            else
            {
                bsonReader.ReadStartDocument();
                DeserializeType(bsonReader, "link");
                bsonReader.ReadName("properties");
                bsonReader.ReadStartDocument();
                var href = bsonReader.ReadString("href");
                string hrefType = null;
                if (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    hrefType = bsonReader.ReadString("type");
                }
                bsonReader.ReadEndDocument();
                bsonReader.ReadEndDocument();

                return new GeoJsonLinkedCoordinateReferenceSystem(href, hrefType);
            }
        }
Example #12
0
        public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            object value = null;
            var valueType = actualType.GetConceptValueType();
			if (valueType == typeof(Guid)) {
				var guidBytes = new byte[16];
				BsonBinarySubType subType;
				bsonReader.ReadBinaryData (out guidBytes, out subType);
				value = new Guid (guidBytes);
			} else if (valueType == typeof(double))
				value = bsonReader.ReadDouble ();
			else if (valueType == typeof(float))
				value = (float)bsonReader.ReadDouble ();
			else if (valueType == typeof(Int32))
				value = bsonReader.ReadInt32 ();
			else if (valueType == typeof(Int64))
				value = bsonReader.ReadInt64 ();
			else if (valueType == typeof(bool))
				value = bsonReader.ReadBoolean ();
			else if (valueType == typeof(string))
				value = bsonReader.ReadString ();
			else if (valueType == typeof(decimal))
				value = decimal.Parse (bsonReader.ReadString ());
            
            var concept = ConceptFactory.CreateConceptInstance(actualType, value);
            return concept;
        }
Example #13
0
 object IBsonSerializable.Deserialize(
     BsonReader bsonReader,
     Type nominalType,
     IBsonSerializationOptions options
 ) {
     throw new InvalidOperationException();
 }
        // 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(double));
            var representationSerializationOptions = EnsureSerializationOptions<RepresentationSerializationOptions>(options);

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Double:
                    return bsonReader.ReadDouble();
                case BsonType.Int32:
                    return representationSerializationOptions.ToDouble(bsonReader.ReadInt32());
                case BsonType.Int64:
                    return representationSerializationOptions.ToDouble(bsonReader.ReadInt64());
                case BsonType.String:
                    return XmlConvert.ToDouble(bsonReader.ReadString());
                default:
                    var message = string.Format("Cannot deserialize Double from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
 private static OXmlPageSize ReadPageSize(BsonReader bsonReader)
 {
     bsonReader.ReadStartDocument();
     OXmlPageSize value = new OXmlPageSize();
     while (true)
     {
         BsonType bsonType = bsonReader.ReadBsonType();
         if (bsonType == BsonType.EndOfDocument)
             break;
         string name = bsonReader.ReadName();
         switch (name.ToLower())
         {
             case "width":
                 if (bsonType == BsonType.Null)
                     break;
                 if (bsonType != BsonType.Int32)
                     throw new PBException($"wrong PageSize width value {bsonType}");
                 value.Width = bsonReader.ReadInt32();
                 break;
             case "height":
                 if (bsonType == BsonType.Null)
                     break;
                 if (bsonType != BsonType.Int32)
                     throw new PBException($"wrong PageSize height value {bsonType}");
                 value.Height = bsonReader.ReadInt32();
                 break;
             default:
                 throw new PBException($"unknow PageSize value \"{name}\"");
         }
     }
     bsonReader.ReadEndDocument();
     return value;
 }
        // 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(CultureInfo));

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Null:
                    bsonReader.ReadNull();
                    return null;
                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    var name = bsonReader.ReadString("Name");
                    var useUserOverride = bsonReader.ReadBoolean("UseUserOverride");
                    bsonReader.ReadEndDocument();
                    return new CultureInfo(name, useUserOverride);
                case BsonType.String:
                    return new CultureInfo(bsonReader.ReadString());
                default:
                    var message = string.Format("Cannot deserialize CultureInfo from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
        public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            if (bsonReader.CurrentBsonType == BsonType.Int32)
                return bsonReader.ReadInt32().ToString();

            throw new InvalidOperationException();
        }
 public OXmlOpenHeaderElement _Deserialize(BsonReader bsonReader, IBsonSerializationOptions options)
 {
     OXmlOpenHeaderElement element = new OXmlOpenHeaderElement();
     while (true)
     {
         BsonType bsonType = bsonReader.ReadBsonType();
         if (bsonType == BsonType.EndOfDocument)
             break;
         string name = bsonReader.ReadName();
         switch (name.ToLower())
         {
             case "type":
                 if (bsonType != BsonType.String)
                     throw new PBException($"wrong type value {bsonType}");
                 string type = bsonReader.ReadString();
                 //"openfooter"
                 if (type.ToLower() != "openheader")
                     throw new PBException($"invalid Type {type} when deserialize OXmlOpenHeader");
                 break;
             case "headertype":
                 if (bsonType == BsonType.Null)
                     break;
                 if (bsonType != BsonType.String)
                     throw new PBException($"wrong HeaderType value {bsonType}");
                 element.HeaderType = bsonReader.ReadString().zParseEnum<HeaderFooterValues>();
                 break;
             default:
                 //OpenHeaderFooter
                 throw new PBException($"unknow OpenHeader value \"{name}\"");
         }
     }
     return element;
 }
 public object Deserialize(
     BsonReader bsonReader,
     Type nominalType
 )
 {
     throw new InvalidOperationException("Deserialize not valid for BsonDocumentWrapper");
 }
 public OXmlParagraphElement _Deserialize(BsonReader bsonReader, IBsonSerializationOptions options)
 {
     OXmlParagraphElement paragraph = new OXmlParagraphElement();
     while (true)
     {
         BsonType bsonType = bsonReader.ReadBsonType();
         if (bsonType == BsonType.EndOfDocument)
             break;
         //if (bsonType != BsonType.String)
         //    throw new PBException("error ZStringArray cannot contain value of type {0}", bsonType);
         //var value = bsonReader.ReadString();
         string name = bsonReader.ReadName();
         switch (name.ToLower())
         {
             case "type":
                 if (bsonType != BsonType.String)
                     throw new PBException($"wrong type value {bsonType}");
                 string type = bsonReader.ReadString();
                 if (type.ToLower() != "paragraph")
                     throw new PBException($"invalid Type {type} when deserialize OXmlParagraphElement");
                 break;
             case "style":
                 if (bsonType == BsonType.Null)
                     break;
                 if (bsonType != BsonType.String)
                     throw new PBException($"wrong style value {bsonType}");
                 paragraph.Style = bsonReader.ReadString();
                 break;
             default:
                 throw new PBException($"unknow Paragraph value \"{name}\"");
         }
     }
     return paragraph;
 }
 public override object Deserialize(
     BsonReader bsonReader,
     Type nominalType,
     IBsonSerializationOptions options
 ) {
     return XmlConvert.ToDateTime(bsonReader.ReadString(), XmlDateTimeSerializationMode.RoundtripKind);
 }
        public void TestBookmark() {
            var json = "{ \"x\" : 1, \"y\" : 2 }";
            using (bsonReader = BsonReader.Create(json)) {
                // do everything twice returning to bookmark in between
                var bookmark = bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType());

                bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();
                bsonReader.ReturnToBookmark(bookmark);
                bsonReader.ReadStartDocument();

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType());

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual("x", bsonReader.ReadName());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("x", bsonReader.ReadName());

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual(1, bsonReader.ReadInt32());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(1, bsonReader.ReadInt32());

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType());

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual("y", bsonReader.ReadName());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("y", bsonReader.ReadName());

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual(2, bsonReader.ReadInt32());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(2, bsonReader.ReadInt32());

                bookmark = bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.EndOfDocument, bsonReader.ReadBsonType());
                bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.EndOfDocument, bsonReader.ReadBsonType());

                bookmark = bsonReader.GetBookmark();
                bsonReader.ReadEndDocument();
                bsonReader.ReturnToBookmark(bookmark);
                bsonReader.ReadEndDocument();

                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);

            }
            Assert.AreEqual(json, BsonSerializer.Deserialize<BsonDocument>(new StringReader(json)).ToJson());
        }
 public override object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
 {
   // read an ObjectId from the database but convert it to a string before returning it
   int timestamp, machine, increment;
   short pid;
   bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment);
   return new ObjectId(timestamp, machine, pid, increment).ToString();
 }
Example #24
0
 public bool Read()
 {
     Index++;
     if (Index >= Cursor.Count())   
         return false;
     m_reader = BsonReader.Create(Cursor.ElementAt(Index));
     return true;
 }
 // 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)
 {
     throw new NotSupportedException();
 }
 public object Deserialize(
     BsonReader bsonReader,
     Type nominalType
 )
 {
     var message = string.Format("Deserialize method cannot be called on a {0}", this.GetType().Name);
     throw new InvalidOperationException(message);
 }
 /// <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 object Deserialize(
     BsonReader bsonReader,
     Type nominalType,
     Type actualType,
     IBsonSerializationOptions options)
 {
     var value = (IBsonSerializable)Activator.CreateInstance(actualType, true); // private default constructor OK
     return value.Deserialize(bsonReader, nominalType, options);
 }
 // protected methods
 protected void DeserializeType(BsonReader bsonReader, string expectedType)
 {
     var type = bsonReader.ReadString("type");
     if (type != expectedType)
     {
         var message = string.Format("Expected type to be '{0}'.", expectedType);
         throw new FormatException(message);
     }
 }
        // 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)
        {
            var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options);
            var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions;

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Null:
                    bsonReader.ReadNull();
                    return null;

                case BsonType.Array:
                    var instance = CreateInstance(actualType);
                    var itemDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
                    Type lastItemType = null;
                    IBsonSerializer lastItemSerializer = null;

                    bsonReader.ReadStartArray();
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        var itemType = itemDiscriminatorConvention.GetActualType(bsonReader, typeof(object));
                        IBsonSerializer itemSerializer;
                        if (itemType == lastItemType)
                        {
                            itemSerializer = lastItemSerializer;
                        }
                        else
                        {
                            itemSerializer = BsonSerializer.LookupSerializer(itemType);
                            lastItemType = itemType;
                            lastItemSerializer = itemSerializer;
                        }
                        var item = itemSerializer.Deserialize(bsonReader, typeof(object), itemType, itemSerializationOptions);
                        AddItem(instance, item);
                    }
                    bsonReader.ReadEndArray();

                    return FinalizeResult(instance, actualType);

                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadString("_t"); // skip over discriminator
                    bsonReader.ReadName("_v");
                    var value = Deserialize(bsonReader, actualType, actualType, options);
                    bsonReader.ReadEndDocument();
                    return value;

                default:
                    var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType);
                    throw new FileFormatException(message);
            }
        }
 public void TestArrayEmpty() {
     var json = "[]";
     using (bsonReader = BsonReader.Create(json)) {
         Assert.AreEqual(BsonType.Array, bsonReader.ReadBsonType());
         bsonReader.ReadStartArray();
         Assert.AreEqual(BsonType.EndOfDocument, bsonReader.ReadBsonType());
         bsonReader.ReadEndArray();
         Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
     }
     Assert.AreEqual(json, BsonSerializer.Deserialize<BsonArray>(new StringReader(json)).ToJson());
 }
        /// <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(T[, , ]));

            var    bsonType = bsonReader.CurrentBsonType;
            string message;

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

            case BsonType.Array:
                bsonReader.ReadStartArray();
                var outerList = new List <List <List <T> > >();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.ReadStartArray();
                    var middleList = new List <List <T> >();
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        bsonReader.ReadStartArray();
                        var innerList = new List <T>();
                        while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                        {
                            var element = BsonSerializer.Deserialize <T>(bsonReader);
                            innerList.Add(element);
                        }
                        bsonReader.ReadEndArray();
                        middleList.Add(innerList);
                    }
                    bsonReader.ReadEndArray();
                    outerList.Add(middleList);
                }
                bsonReader.ReadEndArray();

                var length1 = outerList.Count;
                var length2 = (length1 == 0) ? 0 : outerList[0].Count;
                var length3 = (length2 == 0) ? 0 : outerList[0][0].Count;
                var array   = new T[length1, length2, length3];
                for (int i = 0; i < length1; i++)
                {
                    var middleList = outerList[i];
                    if (middleList.Count != length2)
                    {
                        message = string.Format("Middle list {0} is of length {1} but should be of length {2}.", i, middleList.Count, length2);
                        throw new FileFormatException(message);
                    }
                    for (int j = 0; j < length2; j++)
                    {
                        var innerList = middleList[j];
                        if (innerList.Count != length3)
                        {
                            message = string.Format("Inner list {0} is of length {1} but should be of length {2}.", j, innerList.Count, length3);
                            throw new FileFormatException(message);
                        }
                        for (int k = 0; k < length3; k++)
                        {
                            array[i, j, k] = innerList[k];
                        }
                    }
                }

                return(array);

            case BsonType.Document:
                bsonReader.ReadStartDocument();
                bsonReader.ReadString("_t");     // skip over discriminator
                bsonReader.ReadName("_v");
                var value = Deserialize(bsonReader, actualType, actualType, options);
                bsonReader.ReadEndDocument();
                return(value);

            default:
                message = string.Format("Can't deserialize a {0} from BsonType {1}.", actualType.FullName, bsonType);
                throw new FileFormatException(message);
            }
        }
Example #32
0
        //public static WebHeaderSerializer Instance { get { return __instance; } }

        public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            if (_trace)
            {
                pb.Trace.WriteLine("WebHeaderSerializer.Deserialize()");
            }

            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            else if (bsonType == BsonType.Document)
            {
                if (nominalType == typeof(object))
                {
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadString("_t");                              // skip over discriminator
                    bsonReader.ReadName("_v");
                    var value = Deserialize(bsonReader, actualType, options); // recursive call replacing nominalType with actualType
                    bsonReader.ReadEndDocument();
                    return(value);
                }

                var headers = new WebHeaderCollection();

                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    string key = bsonReader.ReadName();

                    bsonType = bsonReader.GetCurrentBsonType();
                    if (bsonType == BsonType.String)
                    {
                        string value = bsonReader.ReadString();
                        headers.Add(key, value);
                    }
                    else if (bsonType == BsonType.Array)
                    {
                        bsonReader.ReadStartArray();
                        bsonType = bsonReader.ReadBsonType();
                        while (bsonType != BsonType.EndOfDocument)
                        {
                            if (bsonType != BsonType.String)
                            {
                                throw new PBException("invalid BsonType {0} for header array \"{1}\" value deserialize WebHeaderCollection.", bsonType, key);
                            }
                            string value = bsonReader.ReadString();
                            headers.Add(key, value);
                            bsonType = bsonReader.ReadBsonType();
                        }
                        bsonReader.ReadEndArray();
                    }
                    else
                    {
                        throw new PBException("error deserialize WebHeaderCollection, invalid BsonType {0} for \"{1}\".", bsonType, key);
                    }
                }
                bsonReader.ReadEndDocument();

                return(headers);
            }
            else
            {
                throw new PBException("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType);
            }
        }
Example #33
0
        public static int b2j(string bfile, string jfile)
        {
            try
            {
                Stream textReader = File.OpenRead(bfile);

                bool need_root = false;

                if (!arguments.ContainsKey("noroot"))
                {
                    using (BsonReader reader = new BsonReader(textReader))
                    {
                        while (reader.Read())
                        {
                            if (reader.TokenType != JsonToken.PropertyName && reader.TokenType == JsonToken.StartObject)
                            {
                                continue;
                            }
                            if ((string)reader.Value != "root")
                            {
                                need_root = true;
                            }
                            break;
                        }
                    }
                }
                textReader.Close();
                textReader = File.OpenRead(bfile);


                using (BsonReader reader = new BsonReader(textReader))
                {
                    var outFile = jfile;
                    reader.Encoding = Encoding.GetEncoding(1251);
                    if (jfile == null)
                    {
                        outFile = bfile.Replace(".bson", ".json");
                    }
                    TextWriter stm = new StreamWriter(outFile, false, Encoding.GetEncoding(1251));

                    using (JsonTextWriter jsonWriter = new JsonTextWriter(stm))
                    {
                        jsonWriter.Formatting = Formatting.Indented;

                        if (need_root)
                        {
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName("root");
                        }

                        while (reader.Read())
                        {
                            jsonWriter.WriteToken(reader);
                        }
                        if (need_root)
                        {
                            jsonWriter.WriteEndObject();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return(2);
            }
            return(0);
        }
Example #34
0
 public override IXPloitSocketMsg Deserialize(Type type, Encoding codec, byte[] data, int index, int length)
 {
     using (MemoryStream ms = new MemoryStream(data, index, length))
         using (BsonReader read = new BsonReader(ms))
             return((IXPloitSocketMsg)Serializer.Deserialize(read, type));
 }
Example #35
0
        public void WriteValues()
        {
            byte[]       data   = MiscellaneousUtils.HexToBytes("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");
            MemoryStream ms     = new MemoryStream(data);
            BsonReader   reader = new BsonReader(ms);

            reader.ReadRootValueAsArray = true;
            reader.DateTimeKindHandling = DateTimeKind.Utc;

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(long.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(long.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(int.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(int.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(byte.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(sbyte.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.String, reader.TokenType);
            Assert.AreEqual("a", reader.Value);
            Assert.AreEqual(typeof(string), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);
            Assert.AreEqual(decimal.MaxValue, reader.Value);
            Assert.AreEqual(typeof(double), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);
            Assert.AreEqual(double.MaxValue, reader.Value);
            Assert.AreEqual(typeof(double), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);
            Assert.AreEqual(float.MaxValue, reader.Value);
            Assert.AreEqual(typeof(double), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
            Assert.AreEqual(true, reader.Value);
            Assert.AreEqual(typeof(bool), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
            Assert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, reader.Value);
            Assert.AreEqual(typeof(byte[]), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Date, reader.TokenType);
            Assert.AreEqual(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Date, reader.TokenType);
            Assert.AreEqual(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

            Assert.IsFalse(reader.Read());
        }
Example #36
0
 /// <summary>
 /// Deserializes an object from a BsonReader.
 /// </summary>
 /// <typeparam name="TNominalType">The nominal type of the object.</typeparam>
 /// <param name="bsonReader">The BsonReader.</param>
 /// <returns>A TNominalType.</returns>
 public static TNominalType Deserialize <TNominalType>(BsonReader bsonReader)
 {
     return((TNominalType)Deserialize(bsonReader, typeof(TNominalType)));
 }
Example #37
0
        public static Response Decode(int code, byte[] arr)
        {
            MemoryStream   ms         = new MemoryStream(arr);
            BsonReader     reader     = new BsonReader(ms);
            JsonSerializer serializer = new JsonSerializer();

            Response response = null;

            switch (code)
            {
            case SignupResponse.MESSAGE_CODE:
                response = serializer.Deserialize <SignupResponse>(reader);
                break;

            case LoginResponse.MESSAGE_CODE:
                response = serializer.Deserialize <LoginResponse>(reader);
                break;

            case GetStatisticsResponse.MESSAGE_CODE:
                response = serializer.Deserialize <GetStatisticsResponse>(reader);
                break;

            case BestScoresResponse.MESSAGE_CODE:
                response = serializer.Deserialize <BestScoresResponse>(reader);
                break;

            case LogoutResponse.MESSAGE_CODE:
                response = serializer.Deserialize <LogoutResponse>(reader);
                break;

            case CreateRoomResponse.MESSAGE_CODE:
                response = serializer.Deserialize <CreateRoomResponse>(reader);
                break;

            case GetRoomsResponse.MESSAGE_CODE:
                response = serializer.Deserialize <GetRoomsResponse>(reader);
                break;

            case JoinRoomResponse.MESSAGE_CODE:
                response = serializer.Deserialize <JoinRoomResponse>(reader);
                break;

            case GetRoomStateResponse.MESSAGE_CODE:
                response = serializer.Deserialize <GetRoomStateResponse>(reader);
                break;

            case CloseRoomResponse.MESSAGE_CODE:
                response = serializer.Deserialize <CloseRoomResponse>(reader);
                break;

            case LeaveRoomResponse.MESSAGE_CODE:
                response = serializer.Deserialize <LeaveRoomResponse>(reader);
                break;

            case StartGameResponse.MESSAGE_CODE:
                response = serializer.Deserialize <StartGameResponse>(reader);
                break;

            case GetQuestionResponse.MESSAGE_CODE:
                response = serializer.Deserialize <GetQuestionResponse>(reader);
                break;

            case SubmitAnswerResponse.MESSAGE_CODE:
                response = serializer.Deserialize <SubmitAnswerResponse>(reader);
                break;

            case GetGameResultResponse.MESSAGE_CODE:
                response = serializer.Deserialize <GetGameResultResponse>(reader);
                break;

            case LeaveGameResponse.MESSAGE_CODE:
                response = serializer.Deserialize <LeaveGameResponse>(reader);
                break;

            default:
                break;
            }

            return(response);
        }
Example #38
0
 public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
 {
     return(Deserialize(bsonReader));
 }
        // 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(KeyValuePair <TKey, TValue>));
            var keyValuePairSerializationOptions = EnsureSerializationOptions <KeyValuePairSerializationOptions>(options);

            var    keyDiscriminatorConvention   = GetKeyDiscriminatorConvention();
            var    valueDiscriminatorConvention = GetValueDiscriminatorConvention();
            TKey   key;
            TValue value;

            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Array)
            {
                bsonReader.ReadStartArray();
                bsonReader.ReadBsonType();
                var keyType       = keyDiscriminatorConvention.GetActualType(bsonReader, typeof(TKey));
                var keySerializer = GetKeySerializer(keyType);
                key = (TKey)keySerializer.Deserialize(bsonReader, typeof(TKey), keyType, keyValuePairSerializationOptions.KeySerializationOptions);
                bsonReader.ReadBsonType();
                var valueType       = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(TValue));
                var valueSerializer = GetValueSerializer(valueType);
                value = (TValue)valueSerializer.Deserialize(bsonReader, typeof(TValue), valueType, keyValuePairSerializationOptions.ValueSerializationOptions);
                bsonReader.ReadEndArray();
            }
            else if (bsonType == BsonType.Document)
            {
                bsonReader.ReadStartDocument();
                key   = default(TKey);
                value = default(TValue);
                bool keyFound = false, valueFound = false;
                bool elementFound;
                bool elementIsKey;
                while (bsonReader.ReadBsonType(__bsonTrie, out elementFound, out elementIsKey) != BsonType.EndOfDocument)
                {
                    var name = bsonReader.ReadName();
                    if (elementFound)
                    {
                        if (elementIsKey)
                        {
                            var keyType       = keyDiscriminatorConvention.GetActualType(bsonReader, typeof(TKey));
                            var keySerializer = GetValueSerializer(keyType);
                            key      = (TKey)keySerializer.Deserialize(bsonReader, typeof(TKey), keyType, keyValuePairSerializationOptions.KeySerializationOptions);
                            keyFound = true;
                        }
                        else
                        {
                            var valueType       = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(TValue));
                            var valueSerializer = GetValueSerializer(valueType);
                            value      = (TValue)valueSerializer.Deserialize(bsonReader, typeof(TValue), valueType, keyValuePairSerializationOptions.ValueSerializationOptions);
                            valueFound = true;
                        }
                    }
                    else
                    {
                        var message = string.Format("Element '{0}' is not valid for KeyValuePairs (expecting 'k' or 'v').", name);
                        throw new BsonSerializationException(message);
                    }
                }
                bsonReader.ReadEndDocument();

                if (!keyFound)
                {
                    throw new FileFormatException("KeyValuePair item was missing the 'k' element.");
                }
                if (!valueFound)
                {
                    throw new FileFormatException("KeyValuePair item was missing the 'v' element.");
                }
            }
            else
            {
                var message = string.Format(
                    "Cannot deserialize '{0}' from BsonType {1}.",
                    BsonUtils.GetFriendlyTypeName(typeof(KeyValuePair <TKey, TValue>)),
                    bsonType);
                throw new FileFormatException(message);
            }

            return(new KeyValuePair <TKey, TValue>(key, value));
        }
Example #40
0
        public async Task Attachments()
        {
            var destination = new DatabaseDestination(Database);
            var options     = new DatabaseSmugglerOptionsServerSide
            {
                OperateOnTypes       = DatabaseItemType.Attachments,
                SkipRevisionCreation = true
            };

            destination.Initialize(options, null, buildVersion: default);

            using (var documentActions = destination.Documents())
                using (var buffered = new BufferedStream(RequestBodyStream()))
                                                                            #pragma warning disable CS0618 // Type or member is obsolete
                    using (var reader = new BsonReader(buffered))
#pragma warning restore CS0618                                                                             // Type or member is obsolete
                    {
                        var result = LegacyAttachmentUtils.GetObject(reader);

                        const string idProperty       = "@id";
                        const string etagProperty     = "@etag";
                        const string metadataProperty = "@metadata";
                        const string dataProperty     = "data";

                        string lastAttachmentEtag = null;
                        var    progress           = new SmugglerProgressBase.CountsWithLastEtagAndAttachments();
                        foreach (var attachmentObject in result.Values)
                        {
                            if (!(attachmentObject is Dictionary <string, object> attachmentDictionary))
                            {
                                throw new InvalidDataException("attachmentObject isn't a Dictionary<string, object>");
                            }

                            if (attachmentDictionary.TryGetValue(idProperty, out var attachmentKeyObject) == false)
                            {
                                throw new InvalidDataException($"{idProperty} doesn't exist");
                            }

                            if (!(attachmentKeyObject is string attachmentKey))
                            {
                                throw new InvalidDataException($"{idProperty} isn't of type string");
                            }

                            if (attachmentDictionary.TryGetValue(etagProperty, out var lastAttachmentEtagObject) == false)
                            {
                                throw new InvalidDataException($"{etagProperty} doesn't exist");
                            }

                            if (!(lastAttachmentEtagObject is byte[] lastAttachmentEtagByteArray))
                            {
                                throw new InvalidDataException($"{etagProperty} isn't of type byte[]");
                            }

                            lastAttachmentEtag = LegacyAttachmentUtils.ByteArrayToEtagString(lastAttachmentEtagByteArray);

                            if (attachmentDictionary.TryGetValue(metadataProperty, out object metadataObject) == false)
                            {
                                throw new InvalidDataException($"{metadataProperty} doesn't exist");
                            }

                            if (!(metadataObject is Dictionary <string, object> metadata))
                            {
                                throw new InvalidDataException($"{idProperty} isn't of type string");
                            }

                            if (metadata.TryGetValue("Raven-Delete-Marker", out var deletedObject) && deletedObject is bool deletedObjectAsBool && deletedObjectAsBool)
                            {
                                var id = StreamSource.GetLegacyAttachmentId(attachmentKey);
                                documentActions.DeleteDocument(id);
                                continue;
                            }

                            var djv = new DynamicJsonValue();
                            foreach (var keyValue in metadata)
                            {
                                var key = keyValue.Key;
                                if (key.Equals("Raven-Replication-Source") ||
                                    key.Equals("Raven-Replication-Version") ||
                                    key.Equals("Raven-Replication-History"))
                                {
                                    continue;
                                }

                                djv[key] = keyValue.Value;
                            }

                            var contextToUse      = documentActions.GetContextForNewDocument();
                            var metadataBlittable = contextToUse.ReadObject(djv, "metadata");

                            if (attachmentDictionary.TryGetValue(dataProperty, out object dataObject) == false)
                            {
                                throw new InvalidDataException($"{dataProperty} doesn't exist");
                            }

                            if (!(dataObject is byte[] data))
                            {
                                throw new InvalidDataException($"{dataProperty} isn't of type byte[]");
                            }

                            using (var dataStream = new MemoryStream(data))
                            {
                                var attachment = new DocumentItem.AttachmentStream
                                {
                                    Stream = documentActions.GetTempStream()
                                };

                                var attachmentDetails = StreamSource.GenerateLegacyAttachmentDetails(contextToUse, dataStream, attachmentKey, metadataBlittable, ref attachment);

                                var documentItem = new DocumentItem
                                {
                                    Document = new Document
                                    {
                                        Data         = StreamSource.WriteDummyDocumentForAttachment(contextToUse, attachmentDetails),
                                        Id           = attachmentDetails.Id,
                                        ChangeVector = string.Empty,
                                        Flags        = DocumentFlags.HasAttachments,
                                        LastModified = Database.Time.GetUtcNow()
                                    },
                                    Attachments = new List <DocumentItem.AttachmentStream>
                                    {
                                        attachment
                                    }
                                };

                                documentActions.WriteDocument(documentItem, progress);
                            }
                        }

                        using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                        {
                            var replicationSource = GetSourceReplicationInformation(context, GetRemoteServerInstanceId(), out var documentId);
                            replicationSource.LastAttachmentEtag = lastAttachmentEtag;
                            replicationSource.Source             = GetFromServer();
                            replicationSource.LastModified       = DateTime.UtcNow;

                            await SaveSourceReplicationInformation(replicationSource, context, documentId);
                        }
                    }
        }
Example #41
0
        /// <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 object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options
            )
        {
            VerifyNominalType(nominalType);
            if (bsonReader.CurrentBsonType == Bson.BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            else
            {
                if (actualType.IsValueType)
                {
                    var message = string.Format("Value class {0} cannot be deserialized.", actualType.FullName);
                    throw new BsonSerializationException(message);
                }

                var classMap = BsonClassMap.LookupClassMap(actualType);
                if (classMap.IsAnonymous)
                {
                    throw new InvalidOperationException("Anonymous class cannot be deserialized.");
                }
                var obj = classMap.CreateInstance();

                bsonReader.ReadStartDocument();
                var missingElementMemberMaps = new HashSet <BsonMemberMap>(classMap.MemberMaps); // make a copy!
                var discriminatorConvention  = BsonDefaultSerializer.LookupDiscriminatorConvention(nominalType);
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var elementName = bsonReader.ReadName();
                    if (elementName == discriminatorConvention.ElementName)
                    {
                        bsonReader.SkipValue(); // skip over discriminator
                        continue;
                    }

                    var memberMap = classMap.GetMemberMapForElement(elementName);
                    if (memberMap != null && memberMap != classMap.ExtraElementsMemberMap)
                    {
                        DeserializeMember(bsonReader, obj, memberMap);
                        missingElementMemberMaps.Remove(memberMap);
                    }
                    else
                    {
                        if (classMap.ExtraElementsMemberMap != null)
                        {
                            DeserializeExtraElement(bsonReader, obj, elementName, classMap.ExtraElementsMemberMap);
                        }
                        else if (classMap.IgnoreExtraElements)
                        {
                            bsonReader.SkipValue();
                        }
                        else
                        {
                            string message = string.Format("Unexpected element '{0}'.", elementName);
                            throw new FileFormatException(message);
                        }
                    }
                }
                bsonReader.ReadEndDocument();

                foreach (var memberMap in missingElementMemberMaps)
                {
                    if (memberMap.IsRequired)
                    {
                        var message = string.Format("Required element '{0}' is missing.", memberMap.ElementName);
                        throw new FileFormatException(message);
                    }

                    if (memberMap.HasDefaultValue)
                    {
                        memberMap.ApplyDefaultValue(obj);
                    }
                }

                return(obj);
            }
        }
        /// <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 = BsonUtils.ToLocalTime(value, dateTimeOptions.Kind);
                    break;

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

            return(value);
        }
        // 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(T[, ]));
            var arraySerializationOptions = EnsureSerializationOptions <ArraySerializationOptions>(options);
            var itemSerializationOptions  = arraySerializationOptions.ItemSerializationOptions;

            var    bsonType = bsonReader.GetCurrentBsonType();
            string message;

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

            case BsonType.Array:
                var             itemNominalType             = typeof(T);
                var             itemNominalTypeIsValueType  = itemNominalType.IsValueType;
                var             itemNominalTypeSerializer   = BsonSerializer.LookupSerializer(itemNominalType);
                var             itemDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(itemNominalType);
                Type            lastItemType       = null;
                IBsonSerializer lastItemSerializer = null;

                // if itemNominalType is a value type then these assignments are final
                var itemActualType           = itemNominalType;
                var itemActualTypeSerializer = itemNominalTypeSerializer;

                bsonReader.ReadStartArray();
                var outerList = new List <List <T> >();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.ReadStartArray();
                    var innerList = new List <T>();
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        if (!itemNominalTypeIsValueType)
                        {
                            itemActualType = itemDiscriminatorConvention.GetActualType(bsonReader, itemNominalType);
                            if (itemActualType == itemNominalType)
                            {
                                itemActualTypeSerializer = itemNominalTypeSerializer;
                            }
                            else if (itemActualType == lastItemType)
                            {
                                itemActualTypeSerializer = lastItemSerializer;
                            }
                            else
                            {
                                itemActualTypeSerializer = BsonSerializer.LookupSerializer(itemActualType);
                                lastItemType             = itemActualType;
                                lastItemSerializer       = itemActualTypeSerializer;
                            }
                        }
                        var item = (T)itemActualTypeSerializer.Deserialize(bsonReader, itemNominalType, itemActualType, itemSerializationOptions);
                        innerList.Add(item);
                    }
                    bsonReader.ReadEndArray();
                    outerList.Add(innerList);
                }
                bsonReader.ReadEndArray();

                var length1 = outerList.Count;
                var length2 = (length1 == 0) ? 0 : outerList[0].Count;
                var array   = new T[length1, length2];
                for (int i = 0; i < length1; i++)
                {
                    var innerList = outerList[i];
                    if (innerList.Count != length2)
                    {
                        message = string.Format("Inner list {0} is of length {1} but should be of length {2}.", i, innerList.Count, length2);
                        throw new Exception(message);
                    }
                    for (int j = 0; j < length2; j++)
                    {
                        array[i, j] = innerList[j];
                    }
                }

                return(array);

            case BsonType.Document:
                bsonReader.ReadStartDocument();
                bsonReader.ReadString("_t");     // skip over discriminator
                bsonReader.ReadName("_v");
                var value = Deserialize(bsonReader, actualType, actualType, options);
                bsonReader.ReadEndDocument();
                return(value);

            default:
                message = string.Format("Can't deserialize a {0} from BsonType {1}.", actualType.FullName, bsonType);
                throw new Exception(message);
            }
        }
Example #44
0
 public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
 {
     throw new NotImplementedException();
 }
        public bool selectAllInto(JArray results, string query)
        {
            if (_connection != null)
            {
                try
                {
                    var cmd  = _connection.CreateCommand(query);
                    var stmt = SQLite3.Prepare2(_connection.Handle, cmd.CommandText);

                    try
                    {
                        while (SQLite3.Step(stmt) == SQLite3.Result.Row)
                        {
                            int colCount = SQLite3.ColumnCount(stmt);
                            if (colCount <= 0)
                            {
                                return(false);
                            }

                            JObject jsonObj = new JObject();

                            for (int i = 0; i < colCount; i++)
                            {
                                string columnName = SQLite3.ColumnName16(stmt, i);

                                if (columnName.Equals(FIELD_JSON))
                                {
                                    MemoryStream ms = new MemoryStream(SQLite3.ColumnByteArray(stmt, i));
                                    using (BsonReader reader = new BsonReader(ms))
                                    {
                                        jsonObj.Add(FIELD_JSON, JToken.ReadFrom(reader));
                                    }
                                }
                                else if (columnName.Equals(FIELD_ID))
                                {
                                    jsonObj.Add(FIELD_ID, Int32.Parse(SQLite3.ColumnString(stmt, i)));
                                }
                                else
                                {
                                    if (isJSONCreatedColumn(columnName))
                                    {
                                        jsonObj.Add(columnName, SQLite3.ColumnString(stmt, i));
                                    }
                                    else
                                    {
                                        jsonObj.Add(columnName.Replace('_', '.'), SQLite3.ColumnString(stmt, i));
                                    }
                                }
                            }
                            results.Add(jsonObj);
                        }
                    }
                    finally
                    {
                        SQLite3.Finalize(stmt);
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    lastErrorMsg = e.ToString();
                }
            }
            return(false);
        }
Example #46
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)
        {
            var dictionarySerializationOptions   = EnsureSerializationOptions(options);
            var dictionaryRepresentation         = dictionarySerializationOptions.Representation;
            var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions;

            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            else if (bsonType == BsonType.Document)
            {
                if (nominalType == typeof(object))
                {
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadString("_t");                              // skip over discriminator
                    bsonReader.ReadName("_v");
                    var value = Deserialize(bsonReader, actualType, options); // recursive call replacing nominalType with actualType
                    bsonReader.ReadEndDocument();
                    return(value);
                }

                var dictionary = CreateInstance(actualType);
                var valueDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));

                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var key             = bsonReader.ReadName();
                    var valueType       = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(object));
                    var valueSerializer = BsonSerializer.LookupSerializer(valueType);
                    var value           = valueSerializer.Deserialize(bsonReader, typeof(object), valueType, keyValuePairSerializationOptions.ValueSerializationOptions);
                    dictionary.Add(key, value);
                }
                bsonReader.ReadEndDocument();

                return(dictionary);
            }
            else if (bsonType == BsonType.Array)
            {
                var dictionary = CreateInstance(actualType);

                bsonReader.ReadStartArray();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var keyValuePair = (KeyValuePair <object, object>)_keyValuePairSerializer.Deserialize(
                        bsonReader,
                        typeof(KeyValuePair <object, object>),
                        keyValuePairSerializationOptions);
                    dictionary.Add(keyValuePair.Key, keyValuePair.Value);
                }
                bsonReader.ReadEndArray();

                return(dictionary);
            }
            else
            {
                var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType);
                throw new FileFormatException(message);
            }
        }
Example #47
0
 /// <summary>
 /// Deserializes an object from a BsonReader.
 /// </summary>
 /// <param name="bsonReader">The BsonReader.</param>
 /// <param name="nominalType">The nominal type of the object.</param>
 /// <returns>An object.</returns>
 public static object Deserialize(BsonReader bsonReader, Type nominalType)
 {
     return(Deserialize(bsonReader, nominalType, null));
 }
        // public methods
        /// <summary>
        /// Gets the actual type of an object by reading the discriminator from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The reader.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <returns>The actual type.</returns>
        public Type GetActualType(BsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonReader.State == BsonReaderState.Value)
            {
                Type primitiveType = null;
                switch (bsonType)
                {
                case BsonType.Boolean: primitiveType = typeof(bool); break;

                case BsonType.Binary:
                    var               bookmark = bsonReader.GetBookmark();
                    byte[]            bytes;
                    BsonBinarySubType subType;
                    bsonReader.ReadBinaryData(out bytes, out subType);
                    if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
                    {
                        primitiveType = typeof(Guid);
                    }
                    bsonReader.ReturnToBookmark(bookmark);
                    break;

                case BsonType.DateTime: primitiveType = typeof(DateTime); break;

                case BsonType.Double: primitiveType = typeof(double); break;

                case BsonType.Int32: primitiveType = typeof(int); break;

                case BsonType.Int64: primitiveType = typeof(long); break;

                case BsonType.ObjectId: primitiveType = typeof(ObjectId); break;

                case BsonType.String: primitiveType = typeof(string); break;
                }

                if (primitiveType != null && nominalType.IsAssignableFrom(primitiveType))
                {
                    return(primitiveType);
                }
            }

            if (bsonType == BsonType.Document)
            {
                // ensure KnownTypes of nominalType are registered (so IsTypeDiscriminated returns correct answer)
                BsonDefaultSerializer.EnsureKnownTypesAreRegistered(nominalType);

                // we can skip looking for a discriminator if nominalType has no discriminated sub types
                if (BsonDefaultSerializer.IsTypeDiscriminated(nominalType))
                {
                    var bookmark = bsonReader.GetBookmark();
                    bsonReader.ReadStartDocument();
                    var actualType = nominalType;
                    if (bsonReader.FindElement(_elementName))
                    {
                        var discriminator = BsonValue.ReadFrom(bsonReader);
                        if (discriminator.IsBsonArray)
                        {
                            discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                        }
                        actualType = BsonDefaultSerializer.LookupActualType(nominalType, discriminator);
                    }
                    bsonReader.ReturnToBookmark(bookmark);
                    return(actualType);
                }
            }

            return(nominalType);
        }
Example #49
0
 public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
 {
     return(Deserialize(bsonReader, nominalType, options));
 }
 public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
 {
     serializer.Deserialize(bsonReader, typeof(object), options);
     return((Func <object, T>)Get);
 }
Example #51
0
        private object Deserialize(BsonReader bsonReader, IBsonSerializationOptions options)
        {
            var enumerable = (IEnumerable <T>)_enumerableSerializer.Deserialize(bsonReader, typeof(ISet <T>), typeof(HashSet <T>), options);

            return(new Collection.HashSet <T>(enumerable));
        }
Example #52
0
        public void SerializeGoogleGeoCode()
        {
            string json = @"{
  ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
  ""Status"": {
    ""code"": 200,
    ""request"": ""geocode""
  },
  ""Placemark"": [
    {
      ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
      ""AddressDetails"": {
        ""Country"": {
          ""CountryNameCode"": ""US"",
          ""AdministrativeArea"": {
            ""AdministrativeAreaName"": ""CA"",
            ""SubAdministrativeArea"": {
              ""SubAdministrativeAreaName"": ""Santa Clara"",
              ""Locality"": {
                ""LocalityName"": ""Mountain View"",
                ""Thoroughfare"": {
                  ""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
                },
                ""PostalCode"": {
                  ""PostalCodeNumber"": ""94043""
                }
              }
            }
          }
        },
        ""Accuracy"": 8
      },
      ""Point"": {
        ""coordinates"": [-122.083739, 37.423021, 0]
      }
    }
  ]
}";

            GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject <GoogleMapGeocoderStructure>(json);

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

            JsonSerializer serializer = new JsonSerializer();

            serializer.Serialize(writer, jsonGoogleMapGeocoder);

            ms.Seek(0, SeekOrigin.Begin);
            BsonReader reader = new BsonReader(ms);
            GoogleMapGeocoderStructure bsonGoogleMapGeocoder = (GoogleMapGeocoderStructure)serializer.Deserialize(reader, typeof(GoogleMapGeocoderStructure));

            Assert.IsNotNull(bsonGoogleMapGeocoder);
            Assert.AreEqual("1600 Amphitheatre Parkway, Mountain View, CA, USA", bsonGoogleMapGeocoder.Name);
            Assert.AreEqual("200", bsonGoogleMapGeocoder.Status.Code);
            Assert.AreEqual("geocode", bsonGoogleMapGeocoder.Status.Request);

            IList <Placemark> placemarks = bsonGoogleMapGeocoder.Placemark;

            Assert.IsNotNull(placemarks);
            Assert.AreEqual(1, placemarks.Count);

            Placemark placemark = placemarks[0];

            Assert.AreEqual("1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", placemark.Address);
            Assert.AreEqual(8, placemark.AddressDetails.Accuracy);
            Assert.AreEqual("US", placemark.AddressDetails.Country.CountryNameCode);
            Assert.AreEqual("CA", placemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
            Assert.AreEqual("Santa Clara", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName);
            Assert.AreEqual("Mountain View", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);
            Assert.AreEqual("1600 Amphitheatre Pkwy", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName);
            Assert.AreEqual("94043", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber);
            Assert.AreEqual(-122.083739m, placemark.Point.Coordinates[0]);
            Assert.AreEqual(37.423021m, placemark.Point.Coordinates[1]);
            Assert.AreEqual(0m, placemark.Point.Coordinates[2]);
        }
        // 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="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
        {
            var value = (IBsonSerializable)Activator.CreateInstance(nominalType, true); // private default constructor OK

            return(value.Deserialize(bsonReader, nominalType, options));
        }
Example #54
0
        // -----------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        // -----------------------------------------------------------------
        public static RequestBase DeserializeFromBinaryStream(Stream bstream)
        {
            BsonReader bson = new BsonReader(bstream);

            return(DeserializeFromReader(bson));
        }
Example #55
0
        public void ReadEndOfStream()
        {
            BsonReader reader = new BsonReader(new MemoryStream());

            Assert.IsFalse(reader.Read());
        }
Example #56
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="options">The serialization options.</param>
 /// <returns>An object.</returns>
 public virtual object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
 {
     // override this method to determine actualType if your serializer handles polymorphic data types
     return(Deserialize(bsonReader, nominalType, nominalType, options));
 }
        public override T Deserialize <T>(Stream input)
        {
            var reader = new BsonReader(input, IsArray(typeof(T)), DateTimeKind.Utc);

            return(Deserialize <T>(reader));
        }
        /// <inheritdoc />
        public virtual IDictionary <string, object> LoadTempData([NotNull] HttpContext context)
        {
            if (!IsSessionEnabled(context))
            {
                // Session middleware is not enabled. No-op
                return(null);
            }

            var tempDataDictionary = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            var session            = context.Session;

            byte[] value;

            if (session != null && session.TryGetValue(TempDataSessionStateKey, out value))
            {
                using (var memoryStream = new MemoryStream(value))
                    using (var writer = new BsonReader(memoryStream))
                    {
                        tempDataDictionary = _jsonSerializer.Deserialize <Dictionary <string, object> >(writer);
                    }

                var convertedDictionary = new Dictionary <string, object>(tempDataDictionary, StringComparer.OrdinalIgnoreCase);
                foreach (var item in tempDataDictionary)
                {
                    var jArrayValue = item.Value as JArray;
                    if (jArrayValue != null && jArrayValue.Count > 0)
                    {
                        var  arrayType = jArrayValue[0].Type;
                        Type returnType;
                        if (_tokenTypeLookup.TryGetValue(arrayType, out returnType))
                        {
                            var arrayConverter = _arrayConverters.GetOrAdd(returnType, type =>
                            {
                                return((Func <JArray, object>)_convertArrayMethodInfo.MakeGenericMethod(type).CreateDelegate(typeof(Func <JArray, object>)));
                            });
                            var result = arrayConverter(jArrayValue);

                            convertedDictionary[item.Key] = result;
                        }
                        else
                        {
                            var message = Resources.FormatTempData_CannotDeserializeToken(nameof(JToken), arrayType);
                            throw new InvalidOperationException(message);
                        }
                    }
                    else
                    {
                        var jObjectValue = item.Value as JObject;
                        if (jObjectValue == null)
                        {
                            continue;
                        }
                        else if (!jObjectValue.HasValues)
                        {
                            convertedDictionary[item.Key] = null;
                            continue;
                        }

                        var  jTokenType = jObjectValue.Properties().First().Value.Type;
                        Type valueType;
                        if (_tokenTypeLookup.TryGetValue(jTokenType, out valueType))
                        {
                            var dictionaryConverter = _dictionaryConverters.GetOrAdd(valueType, type =>
                            {
                                return((Func <JObject, object>)_convertDictMethodInfo.MakeGenericMethod(type).CreateDelegate(typeof(Func <JObject, object>)));
                            });
                            var result = dictionaryConverter(jObjectValue);

                            convertedDictionary[item.Key] = result;
                        }
                        else
                        {
                            var message = Resources.FormatTempData_CannotDeserializeToken(nameof(JToken), jTokenType);
                            throw new InvalidOperationException(message);
                        }
                    }
                }

                tempDataDictionary = convertedDictionary;

                // If we got it from Session, remove it so that no other request gets it
                session.Remove(TempDataSessionStateKey);
            }
            else
            {
                // Since we call Save() after the response has been sent, we need to initialize an empty session
                // so that it is established before the headers are sent.
                session[TempDataSessionStateKey] = new byte[] { };
            }

            return(tempDataDictionary);
        }
Example #59
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(Version));

            BsonType bsonType = bsonReader.GetCurrentBsonType();
            string   message;

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

            case BsonType.Document:
                bsonReader.ReadStartDocument();
                int major = -1, minor = -1, build = -1, revision = -1;
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var name = bsonReader.ReadName();
                    switch (name)
                    {
                    case "Major": major = bsonReader.ReadInt32(); break;

                    case "Minor": minor = bsonReader.ReadInt32(); break;

                    case "Build": build = bsonReader.ReadInt32(); break;

                    case "Revision": revision = bsonReader.ReadInt32(); break;

                    default:
                        message = string.Format("Unrecognized element '{0}' while deserializing a Version value.", name);
                        throw new FileFormatException(message);
                    }
                }
                bsonReader.ReadEndDocument();
                if (major == -1)
                {
                    message = string.Format("Version missing Major element.");
                    throw new FileFormatException(message);
                }
                else if (minor == -1)
                {
                    message = string.Format("Version missing Minor element.");
                    throw new FileFormatException(message);
                }
                else if (build == -1)
                {
                    return(new Version(major, minor));
                }
                else if (revision == -1)
                {
                    return(new Version(major, minor, build));
                }
                else
                {
                    return(new Version(major, minor, build, revision));
                }

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

            default:
                message = string.Format("Cannot deserialize Version from BsonType {0}.", bsonType);
                throw new FileFormatException(message);
            }
        }
        public void TestBookmark()
        {
            var json = "{ \"x\" : 1, \"y\" : 2 }";

            using (_bsonReader = BsonReader.Create(json))
            {
                // do everything twice returning to bookmark in between
                var bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                _bsonReader.ReadStartDocument();
                _bsonReader.ReturnToBookmark(bookmark);
                _bsonReader.ReadStartDocument();

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual("x", _bsonReader.ReadName());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("x", _bsonReader.ReadName());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(1, _bsonReader.ReadInt32());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual("y", _bsonReader.ReadName());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("y", _bsonReader.ReadName());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(2, _bsonReader.ReadInt32());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                _bsonReader.ReadEndDocument();
                _bsonReader.ReturnToBookmark(bookmark);
                _bsonReader.ReadEndDocument();

                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson());
        }