public void SerializeOpQueryMessage()
        {
            const Int32 requestId = 1;
            const Int32 responseTo = 0;
            const OpQueryMessage.OpQueryFlags flags = OpQueryMessage.OpQueryFlags.AwaitData;
            const String fullCollectionName = "reactive.coll";
            const Int32 numberToSkip = 0;
            const Int32 numberToReturn = 1;

            var serializer = new BsonSerializer(ReflectionCache.None);
            var rawQuery = serializer.Serialize(new Query {id = 3});

            var expected = new Byte[]
                {
                    55, 0, 0, 0,
                    1, 0, 0, 0,
                    0, 0, 0, 0,
                    212, 7, 0, 0,
                    32, 0, 0, 0,
                    114, 101, 97, 99,
                    116, 105, 118, 101,
                    46, 99, 111, 108,
                    108, 0, 0, 0,
                    0, 0, 1, 0,
                    0, 0, 13, 0,
                    0, 0, 16, 105,
                    100, 0, 3, 0,
                    0, 0, 0
                };
            var buffer = new byte[expected.Length];
            var message = new OpQueryMessage(flags,
                                             fullCollectionName,
                                             numberToSkip,
                                             numberToReturn,
                                             rawQuery);
            message.Write(ref buffer, requestId, responseTo);

            Assert.Equal(expected, buffer);
        }
Beispiel #2
0
 /// <summary>
 /// Internally saves chunk entities to file.
 /// </summary>
 /// <param name="ents">The entity data.</param>
 void SaveToFileE(BsonDocument ents)
 {
     try
     {
         ChunkDetails det = new ChunkDetails()
         {
             Version = 2, X = WorldPosition.X, Y = WorldPosition.Y, Z = WorldPosition.Z, Blocks = BsonSerializer.Serialize(ents)
         };
         lock (GetLocker())
         {
             OwningRegion.ChunkManager.WriteChunkEntities(det);
         }
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "Saving entities for chunk " + WorldPosition.ToString() + " to file: " + ex.ToString());
     }
 }
Beispiel #3
0
        protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, ReadonlyList <T> value)
        {
            var inner = new List <T>(value);

            BsonSerializer.Serialize(context.Writer, innerType, inner);
        }
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
            }
            else
            {
                if (nominalType == typeof(object))
                {
                    var actualType = value.GetType();
                    bsonWriter.WriteStartDocument();
                    bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType));
                    bsonWriter.WriteName("_v");
                    Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
                    bsonWriter.WriteEndDocument();
                    return;
                }

                var dictionary = (IDictionary <TKey, TValue>)value;
                var dictionarySerializationOptions   = EnsureSerializationOptions(options);
                var dictionaryRepresentation         = dictionarySerializationOptions.Representation;
                var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions;

                if (dictionaryRepresentation == DictionaryRepresentation.Dynamic)
                {
                    if (typeof(TKey) == typeof(string) || typeof(TKey) == typeof(object))
                    {
                        dictionaryRepresentation = DictionaryRepresentation.Document;
                        foreach (object key in dictionary.Keys)
                        {
                            var name = key as string; // key might not be a string
                            if (string.IsNullOrEmpty(name) || name[0] == '$' || name.IndexOf('.') != -1 || name.IndexOf('\0') != -1)
                            {
                                dictionaryRepresentation = DictionaryRepresentation.ArrayOfArrays;
                                break;
                            }
                        }
                    }
                    else
                    {
                        dictionaryRepresentation = DictionaryRepresentation.ArrayOfArrays;
                    }
                }

                switch (dictionaryRepresentation)
                {
                case DictionaryRepresentation.Document:
                    bsonWriter.WriteStartDocument();
                    foreach (var keyValuePair in dictionary)
                    {
                        bsonWriter.WriteName((string)(object)keyValuePair.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), keyValuePair.Value, keyValuePairSerializationOptions.ValueSerializationOptions);
                    }
                    bsonWriter.WriteEndDocument();
                    break;

                case DictionaryRepresentation.ArrayOfArrays:
                case DictionaryRepresentation.ArrayOfDocuments:
                    // override KeyValuePair representation if necessary
                    var keyValuePairRepresentation = (dictionaryRepresentation == DictionaryRepresentation.ArrayOfArrays) ? BsonType.Array : BsonType.Document;
                    if (keyValuePairSerializationOptions.Representation != keyValuePairRepresentation)
                    {
                        keyValuePairSerializationOptions = new KeyValuePairSerializationOptions(
                            keyValuePairRepresentation,
                            keyValuePairSerializationOptions.KeySerializationOptions,
                            keyValuePairSerializationOptions.ValueSerializationOptions);
                    }

                    bsonWriter.WriteStartArray();
                    foreach (var keyValuePair in dictionary)
                    {
                        _keyValuePairSerializer.Serialize(
                            bsonWriter,
                            typeof(KeyValuePair <TKey, TValue>),
                            keyValuePair,
                            keyValuePairSerializationOptions);
                    }
                    bsonWriter.WriteEndArray();
                    break;

                default:
                    var message = string.Format("'{0}' is not a valid IDictionary<{1}, {2}> representation.",
                                                dictionaryRepresentation,
                                                BsonUtils.GetFriendlyTypeName(typeof(TKey)),
                                                BsonUtils.GetFriendlyTypeName(typeof(TValue)));
                    throw new BsonSerializationException(message);
                }
            }
        }
        /// <summary>
        /// Adds a new acc
        /// </summary>
        /// <param name="registerBindingModel"></param>
        /// <returns></returns>
        public Account Add(RegisterBindingModel registerBindingModel)
        {
            var collection = _client.GetServer().GetDatabase("tabletop").GetCollection(Util.Mongo.MongoUtilities.GetCollectionFromType(typeof(Account)));

            if (collection == null)
            {
                throw new Exception("No account collection in database.");
            }

            var hashDict = HashPassword(registerBindingModel.Password);

            if (!hashDict.ContainsKey("hash") || !hashDict.ContainsKey("salt"))
            {
                throw new Exception("Could not hash password properly.");
            }

            var id = ObjectId.GenerateNewId(DateTime.Now).ToString();

            var account = new Account()
            {
                _id   = id,
                name  = registerBindingModel.Name,
                email = registerBindingModel.Email,
                salt  = hashDict["salt"],
                hash  = hashDict["hash"]
            };

            var bsonDoc = new BsonDocument();
            var bsonDocumentWriterSettings = new BsonDocumentWriterSettings();

            bsonDocumentWriterSettings.GuidRepresentation = GuidRepresentation.Standard;
            var bsonDocumentWriter = new BsonDocumentWriter(bsonDoc, bsonDocumentWriterSettings);

            BsonSerializer.Serialize(bsonDocumentWriter, account);
            var saveOptions = new MongoInsertOptions();

            saveOptions.WriteConcern = WriteConcern.Acknowledged;
            var succeeded = collection.Save(bsonDoc, saveOptions);

            if (!succeeded.Ok)
            {
                throw new Exception(succeeded.LastErrorMessage);
            }

            var playerId = ObjectId.GenerateNewId(DateTime.Now).ToString();

            var player = new Player()
            {
                _id         = playerId,
                AccountName = account.name,
                Email       = account.email,
                JoinDate    = DateTime.Now
            };

            var playerCollection = _client.GetServer().GetDatabase("tabletop").GetCollection(Util.Mongo.MongoUtilities.GetCollectionFromType(player.GetType()));

            bsonDoc            = new BsonDocument();
            bsonDocumentWriter = new BsonDocumentWriter(bsonDoc, bsonDocumentWriterSettings);
            BsonSerializer.Serialize(bsonDocumentWriter, player);
            succeeded = playerCollection.Save(bsonDoc, saveOptions);
            if (!succeeded.Ok)
            {
                throw new Exception(succeeded.LastErrorMessage);
            }

            return(account);
        }
Beispiel #6
0
 /// <summary>
 /// Serializes a wrapped object to a BsonWriter.
 /// </summary>
 /// <param name="bsonWriter">The writer.</param>
 /// <param name="nominalType">The nominal type (ignored).</param>
 /// <param name="options">The serialization options.</param>
 public void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
 {
     BsonSerializer.Serialize(bsonWriter, _nominalType, _obj, options); // use wrapped nominalType
 }
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options
            )
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
            }
            else
            {
                var dictionary = (IDictionary)value;

                var      representationOptions = options as RepresentationSerializationOptions;
                BsonType representation;
                if (representationOptions == null)
                {
                    representation = BsonType.Document;
                    foreach (object key in dictionary.Keys)
                    {
                        var name = key as string; // check for null and type string at the same time
                        if (name == null || name.StartsWith("$") || name.Contains("."))
                        {
                            representation = BsonType.Array;
                            break;
                        }
                    }
                }
                else
                {
                    representation = representationOptions.Representation;
                }

                switch (representation)
                {
                case BsonType.Document:
                    bsonWriter.WriteStartDocument();
                    foreach (DictionaryEntry entry in dictionary)
                    {
                        bsonWriter.WriteName((string)entry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value);
                    }
                    bsonWriter.WriteEndDocument();
                    break;

                case BsonType.Array:
                    bsonWriter.WriteStartArray();
                    foreach (DictionaryEntry entry in dictionary)
                    {
                        bsonWriter.WriteStartArray();
                        BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value);
                        bsonWriter.WriteEndArray();
                    }
                    bsonWriter.WriteEndArray();
                    break;

                default:
                    var message = string.Format("'{0}' is not a valid representation for type IDictionary.", representation);
                    throw new BsonSerializationException(message);
                }
            }
        }
Beispiel #8
0
        /*******************************************/
        /**** Public Methods                    ****/
        /*******************************************/

        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Type value)
        {
            var bsonWriter = context.Writer;

            bsonWriter.WriteStartDocument();

            var discriminator = m_DiscriminatorConvention.GetDiscriminator(typeof(object), typeof(Type));

            bsonWriter.WriteName(m_DiscriminatorConvention.ElementName);
            BsonValueSerializer.Instance.Serialize(context, discriminator);

            if (value == null)
            {
                //Using context.Writer.WriteNull() leads to problem in the deserialisation.
                //We think that BSON think that the types will always be types to be deserialised rather than properties of objects.
                //If that type is null bson throws an exception believing that it wont be able to deserialise an object of type null, while for this case it is ment to be used as a property.
                bsonWriter.WriteName("Name");
                bsonWriter.WriteString("");
            }
            else
            {
                // Handle the case of generic types
                Type[] generics = new Type[] { };
                if (value.IsGenericType)
                {
                    generics = value.GetGenericArguments();
                    value    = value.GetGenericTypeDefinition();
                }

                // Write the name of the type
                bsonWriter.WriteName("Name");
                if (value.IsGenericParameter)
                {
                    bsonWriter.WriteString("T");

                    Type[] constraints = value.GetGenericParameterConstraints();
                    if (constraints.Length > 0)
                    {
                        bsonWriter.WriteName("Constraints");
                        bsonWriter.WriteStartArray();
                        foreach (Type constraint in constraints)
                        {
                            // T : IComparable<T> creates an infinite loop. Thankfully, that's the only case where a type constrained by itself even makes sense
                            if (constraint.Name == "IComparable`1" && constraint.GenericTypeArguments.FirstOrDefault() == value)
                            {
                                BsonSerializer.Serialize(bsonWriter, typeof(IEnumerable));
                            }
                            else
                            {
                                BsonSerializer.Serialize(bsonWriter, constraint);
                            }
                        }

                        bsonWriter.WriteEndArray();
                    }
                }
                else if (value.Namespace.StartsWith("BH.oM"))
                {
                    bsonWriter.WriteString(value.FullName);
                }
                else if (value.AssemblyQualifiedName != null)
                {
                    bsonWriter.WriteString(value.AssemblyQualifiedName);
                }
                else
                {
                    bsonWriter.WriteString(""); //TODO: is that even possible?
                }
                // Add additional information for generic types
                if (generics.Length > 0)
                {
                    bsonWriter.WriteName("GenericArguments");
                    bsonWriter.WriteStartArray();
                    foreach (Type arg in generics)
                    {
                        BsonSerializer.Serialize(bsonWriter, arg);
                    }
                    bsonWriter.WriteEndArray();
                }

                // Add the BHoM verion
                bsonWriter.AddVersion();
            }

            bsonWriter.WriteEndDocument();
        }
Beispiel #9
0
        public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
                return;
            }
            object document;
            Type   type;

            var json = Uri.UnescapeDataString(value.ToString());              //viene con el JSON.stringify.encode...

            if (json.StarstAndEnds("{", "}"))
            {
                document = BsonDocument.Parse(json);
                type     = typeof(BsonDocument);
            }
            else if (json.StarstAndEnds("[", "]"))
            {
                document = BsonSerializer.Deserialize <BsonArray> (json);
                type     = typeof(BsonArray);
            }
            else if (json.IsBsonISODate())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> (json);
                type     = typeof(BsonDateTime);
            }
            else if (json.IsISOString())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> ("ISODate(\"" + json + "\")");
                type     = typeof(BsonDateTime);
            }
            else if (json.IsMsFormat())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> ("new " + json.Replace("/", ""));
                type     = typeof(BsonDateTime);
            }
            else if (json.IsBool())
            {
                document = BsonSerializer.Deserialize <BsonBoolean> (json);
                type     = typeof(BsonBoolean);
            }
            else if (json.IsInt())
            {
                document = BsonSerializer.Deserialize <BsonInt32> (json);
                type     = typeof(BsonInt32);
            }
            else if (json.IsBsonNumberLong())
            {
                document = BsonSerializer.Deserialize <BsonInt64> (json);
                type     = typeof(BsonInt64);
            }
            else if (json.IsLong())
            {
                document = BsonSerializer.Deserialize <BsonInt64> ("NumberLong(\"" + json + "\")");
                type     = typeof(BsonInt64);
            }
            else if (json.IsDouble())
            {
                document = BsonSerializer.Deserialize <BsonDouble> (json);
                type     = typeof(BsonDouble);
            }
            else
            {
                document = BsonSerializer.Deserialize <BsonString> (json.StarstAndEnds("\"", "\"")
                                        ?json
                                        :"\"" + json + "\"");
                type = typeof(BsonString);
            }            /* else {
                          *     Console.WriteLine("Obect ....{0}", json);
                          *     document = value.ToJson (value.GetType ());
                          *     type = typeof(object); // value.GetType();
                          * }*/

            BsonSerializer.Serialize(bsonWriter, type, document, options);
        }
Beispiel #10
0
 protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, T value)
 {
     BsonSerializer.Serialize(context.Writer, JObject.FromObject(value, serializer).ToBson());
 }
Beispiel #11
0
        static void Main(string[] args)
        {
            FileInfo assemblyFileInfo = new FileInfo(args[0]);
            string   savePath         = args[1];

            DirectoryInfo fireMLDirInfo  = assemblyFileInfo.Directory;
            DirectoryInfo contentDirInfo = fireMLDirInfo.Parent;

            List <string> plotFileList  = new List <string>();
            List <string> assetFileList = new List <string>();

            foreach (FileInfo fileInfo in fireMLDirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                string ext = fileInfo.Extension;
                if (ext == ".fmlplot")
                {
                    plotFileList.Add(fileInfo.FullName);
                }
                else if (ext == ".fmlasset")
                {
                    assetFileList.Add(fileInfo.FullName);
                }
            }

            string xsdDirPath = fireMLDirInfo.FullName + "\\" + "XSD";

            //FireEngine.XNAContent.ContentManager contentManager = new FireEngine.XNAContent.ContentManager(contentDirInfo.FullName);
            CompilerKernel kernel = new CompilerKernel(plotFileList.ToArray(), assetFileList.ToArray(), xsdDirPath, null /*contentManager*/);
            FireMLRoot     result = kernel.CompileFireML();

            Error[] errors = kernel.CheckPoint();

            foreach (Error e in errors)
            {
                Console.WriteLine("{0}\n{1},{2}\n{3}", e.Location.FileName, e.Location.Line, e.Location.Column, e.Message);
                Console.WriteLine();
            }

            if (errors.Length > 0)
            {
                Environment.Exit(-1);
                return;
            }

            Stream     bsonStream = new FileStream(savePath, FileMode.Create);
            BsonBuffer bsonBuffer = new BsonBuffer();
            BsonBinaryWriterSettings bsonSettings = new BsonBinaryWriterSettings();
            BsonBinaryWriter         bsonWriter   = new BsonBinaryWriter(bsonStream, bsonBuffer, bsonSettings);

            BsonSerializer.Serialize <FireMLRoot>(bsonWriter, result);
            bsonWriter.Close();

            JsonWriterSettings jsonSettings = new JsonWriterSettings();

            jsonSettings.NewLineChars = "\r\n";
            jsonSettings.OutputMode   = JsonOutputMode.JavaScript;
            jsonSettings.Indent       = true;
            jsonSettings.IndentChars  = "  ";
            StreamWriter streamWriter = new StreamWriter(new FileStream(savePath + ".json", FileMode.Create));
            JsonWriter   jsonWriter   = new JsonWriter(streamWriter, jsonSettings);

            BsonSerializer.Serialize <FireMLRoot>(jsonWriter, result);
            jsonWriter.Close();
        }
Beispiel #12
0
 public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
 {
     BsonSerializer.Serialize(context.Writer, typeof(Triplet), value);
 }
Beispiel #13
0
 public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Triplet value)
 {
     BsonSerializer.Serialize(context.Writer, value);
 }
Beispiel #14
0
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
            }
            else
            {
                if (nominalType == typeof(object))
                {
                    var actualType = value.GetType();
                    bsonWriter.WriteStartDocument();
                    bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType));
                    bsonWriter.WriteName("_v");
                    Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
                    bsonWriter.WriteEndDocument();
                    return;
                }

                var dictionary = (IDictionary)value;
                var dictionarySerializationOptions   = EnsureSerializationOptions(options);
                var dictionaryRepresentation         = dictionarySerializationOptions.Representation;
                var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions;

                if (dictionaryRepresentation == DictionaryRepresentation.Dynamic)
                {
                    dictionaryRepresentation = DictionaryRepresentation.Document;
                    foreach (object key in dictionary.Keys)
                    {
                        var name = key as string; // check for null and type string at the same time
                        if (name == null || name[0] == '$' || name.IndexOf('.') != -1)
                        {
                            dictionaryRepresentation = DictionaryRepresentation.ArrayOfArrays;
                            break;
                        }
                    }
                }

                switch (dictionaryRepresentation)
                {
                case DictionaryRepresentation.Document:
                    bsonWriter.WriteStartDocument();
                    foreach (DictionaryEntry dictionaryEntry in dictionary)
                    {
                        bsonWriter.WriteName((string)dictionaryEntry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(object), dictionaryEntry.Value, keyValuePairSerializationOptions.ValueSerializationOptions);
                    }
                    bsonWriter.WriteEndDocument();
                    break;

                case DictionaryRepresentation.ArrayOfArrays:
                case DictionaryRepresentation.ArrayOfDocuments:
                    // override KeyValuePair representation if necessary
                    var keyValuePairRepresentation = (dictionaryRepresentation == DictionaryRepresentation.ArrayOfArrays) ? BsonType.Array : BsonType.Document;
                    if (keyValuePairSerializationOptions.Representation != keyValuePairRepresentation)
                    {
                        keyValuePairSerializationOptions = new KeyValuePairSerializationOptions(
                            keyValuePairRepresentation,
                            keyValuePairSerializationOptions.KeySerializationOptions,
                            keyValuePairSerializationOptions.ValueSerializationOptions);
                    }

                    bsonWriter.WriteStartArray();
                    foreach (DictionaryEntry dictionaryEntry in dictionary)
                    {
                        var keyValuePair = new KeyValuePair <object, object>(dictionaryEntry.Key, dictionaryEntry.Value);
                        _keyValuePairSerializer.Serialize(
                            bsonWriter,
                            typeof(KeyValuePair <object, object>),
                            keyValuePair,
                            keyValuePairSerializationOptions);
                    }
                    bsonWriter.WriteEndArray();
                    break;

                default:
                    var message = string.Format("'{0}' is not a valid IDictionary representation.", dictionaryRepresentation);
                    throw new BsonSerializationException(message);
                }
            }
        }
Beispiel #15
0
        public void Document_Create()
        {
            var now = DateTime.Now;
            var cid = Guid.NewGuid();

            // create a typed object
            var orderObject = new Order
            {
                OrderKey   = 123,
                CustomerId = cid,
                Date       = now,
                Items      = new List <OrderItem>()
                {
                    new OrderItem {
                        Qtd = 3, Description = "Package", Unit = 99m
                    }
                }
            };

            // create same object, but using BsonDocument
            var orderDoc = new BsonDocument();

            orderDoc.Id            = 123;
            orderDoc["CustomerId"] = cid;
            orderDoc["Date"]       = now;
            orderDoc["Items"]      = new BsonArray();
            var i = new BsonObject();

            i["Qtd"]         = 3;
            i["Description"] = "Package";
            i["Unit"]        = 99m;
            orderDoc["Items"].AsArray.Add(i);

            // serialize both and get indexKey for each one
            var bytesObject = BsonSerializer.Serialize(orderObject);
            var keyObject   = new IndexKey(BsonSerializer.GetIdValue(orderObject));

            var bytesDoc = BsonSerializer.Serialize(orderDoc);
            var keyDoc   = new IndexKey(BsonSerializer.GetIdValue(orderDoc));

            // lets revert objects (create a object from Document and create a Document from a object)
            var revertObject = BsonSerializer.Deserialize <Order>(keyDoc, bytesDoc);
            var revertDoc    = BsonSerializer.Deserialize <BsonDocument>(keyObject, bytesObject);

            // lets compare properties

            Assert.AreEqual(revertObject.OrderKey, revertDoc.Id);
            Assert.AreEqual(revertObject.CustomerId, revertDoc["CustomerId"].AsGuid);
            Assert.AreEqual(revertObject.Date, revertDoc["Date"].AsDateTime);
            Assert.AreEqual(revertObject.Items[0].Unit, revertDoc["Items"][0]["Unit"].AsDecimal);

            // get some property
            Assert.AreEqual(now, BsonSerializer.GetFieldValue(revertObject, "Date"));
            Assert.AreEqual(now, BsonSerializer.GetFieldValue(revertDoc, "Date"));

            Assert.AreEqual(cid, BsonSerializer.GetFieldValue(revertObject, "CustomerId"));
            Assert.AreEqual(cid, BsonSerializer.GetFieldValue(revertDoc, "CustomerId"));

            Assert.AreEqual(null, BsonSerializer.GetFieldValue(revertObject, "Date2"));
            Assert.AreEqual(null, BsonSerializer.GetFieldValue(revertDoc, "Date2"));
        }
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options
            )
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
            }
            else
            {
                var dictionary = (IDictionary <TKey, TValue>)value;

                if (nominalType == typeof(object))
                {
                    var actualType = value.GetType();
                    bsonWriter.WriteStartDocument();
                    bsonWriter.WriteString("_t", BsonClassMap.GetTypeNameDiscriminator(actualType));
                    bsonWriter.WriteName("_v");
                    Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
                    bsonWriter.WriteEndDocument();
                    return;
                }

                var dictionaryOptions = options as DictionarySerializationOptions;
                if (dictionaryOptions == null)
                {
                    // support RepresentationSerializationOptions for backward compatibility
                    var representationOptions = options as RepresentationSerializationOptions;
                    if (representationOptions != null)
                    {
                        switch (representationOptions.Representation)
                        {
                        case BsonType.Array:
                            dictionaryOptions = DictionarySerializationOptions.ArrayOfArrays;
                            break;

                        case BsonType.Document:
                            dictionaryOptions = DictionarySerializationOptions.Document;
                            break;

                        default:
                            var message = string.Format("BsonType {0} is not a valid representation for a Dictionary.", representationOptions.Representation);
                            throw new BsonSerializationException(message);
                        }
                    }

                    if (dictionaryOptions == null)
                    {
                        dictionaryOptions = DictionarySerializationOptions.Defaults;
                    }
                }

                var representation = dictionaryOptions.Representation;
                if (representation == DictionaryRepresentation.Dynamic)
                {
                    if (typeof(TKey) == typeof(string) || typeof(TKey) == typeof(object))
                    {
                        representation = DictionaryRepresentation.Document;
                        foreach (object key in dictionary.Keys)
                        {
                            var name = key as string; // check for null and type string at the same time
                            if (name == null || name.StartsWith("$") || name.Contains("."))
                            {
                                representation = DictionaryRepresentation.ArrayOfArrays;
                                break;
                            }
                        }
                    }
                    else
                    {
                        representation = DictionaryRepresentation.ArrayOfArrays;
                    }
                }

                switch (representation)
                {
                case DictionaryRepresentation.Document:
                    bsonWriter.WriteStartDocument();
                    foreach (KeyValuePair <TKey, TValue> entry in dictionary)
                    {
                        bsonWriter.WriteName((string)(object)entry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), entry.Value);
                    }
                    bsonWriter.WriteEndDocument();
                    break;

                case DictionaryRepresentation.ArrayOfArrays:
                    bsonWriter.WriteStartArray();
                    foreach (KeyValuePair <TKey, TValue> entry in dictionary)
                    {
                        bsonWriter.WriteStartArray();
                        BsonSerializer.Serialize(bsonWriter, typeof(TKey), entry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), entry.Value);
                        bsonWriter.WriteEndArray();
                    }
                    bsonWriter.WriteEndArray();
                    break;

                case DictionaryRepresentation.ArrayOfDocuments:
                    bsonWriter.WriteStartArray();
                    foreach (KeyValuePair <TKey, TValue> entry in dictionary)
                    {
                        bsonWriter.WriteStartDocument();
                        bsonWriter.WriteName("k");
                        BsonSerializer.Serialize(bsonWriter, typeof(TKey), entry.Key);
                        bsonWriter.WriteName("v");
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), entry.Value);
                        bsonWriter.WriteEndDocument();
                    }
                    bsonWriter.WriteEndArray();
                    break;

                default:
                    var message = string.Format("'{0}' is not a valid representation for type IDictionary<{1}, {2}>.", representation, typeof(TKey).Name, typeof(TValue).Name);
                    throw new BsonSerializationException(message);
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
            }
            else
            {
                if (nominalType == typeof(object))
                {
                    var actualType = value.GetType();
                    bsonWriter.WriteStartDocument();
                    bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType));
                    bsonWriter.WriteName("_v");
                    Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
                    bsonWriter.WriteEndDocument();
                    return;
                }

                // support RepresentationSerializationOptions for backward compatibility
                var representationSerializationOptions = options as RepresentationSerializationOptions;
                if (representationSerializationOptions != null)
                {
                    switch (representationSerializationOptions.Representation)
                    {
                    case BsonType.Array:
                        options = DictionarySerializationOptions.ArrayOfArrays;
                        break;

                    case BsonType.Document:
                        options = DictionarySerializationOptions.Document;
                        break;

                    default:
                        var message = string.Format("BsonType {0} is not a valid representation for a Dictionary.", representationSerializationOptions.Representation);
                        throw new BsonSerializationException(message);
                    }
                }

                var dictionary = (IDictionary <TKey, TValue>)value;
                var dictionarySerializationOptions = EnsureSerializationOptions <DictionarySerializationOptions>(options);
                var representation           = dictionarySerializationOptions.Representation;
                var itemSerializationOptions = dictionarySerializationOptions.ItemSerializationOptions;

                if (representation == DictionaryRepresentation.Dynamic)
                {
                    if (typeof(TKey) == typeof(string) || typeof(TKey) == typeof(object))
                    {
                        representation = DictionaryRepresentation.Document;
                        foreach (object key in dictionary.Keys)
                        {
                            var name = key as string; // check for null and type string at the same time
                            if (name == null || name[0] == '$' || name.IndexOf('.') != -1)
                            {
                                representation = DictionaryRepresentation.ArrayOfArrays;
                                break;
                            }
                        }
                    }
                    else
                    {
                        representation = DictionaryRepresentation.ArrayOfArrays;
                    }
                }

                switch (representation)
                {
                case DictionaryRepresentation.Document:
                    bsonWriter.WriteStartDocument();
                    foreach (KeyValuePair <TKey, TValue> entry in dictionary)
                    {
                        bsonWriter.WriteName((string)(object)entry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), entry.Value, itemSerializationOptions);
                    }
                    bsonWriter.WriteEndDocument();
                    break;

                case DictionaryRepresentation.ArrayOfArrays:
                    bsonWriter.WriteStartArray();
                    foreach (KeyValuePair <TKey, TValue> entry in dictionary)
                    {
                        bsonWriter.WriteStartArray();
                        BsonSerializer.Serialize(bsonWriter, typeof(TKey), entry.Key);
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), entry.Value, itemSerializationOptions);
                        bsonWriter.WriteEndArray();
                    }
                    bsonWriter.WriteEndArray();
                    break;

                case DictionaryRepresentation.ArrayOfDocuments:
                    bsonWriter.WriteStartArray();
                    foreach (KeyValuePair <TKey, TValue> entry in dictionary)
                    {
                        bsonWriter.WriteStartDocument();
                        bsonWriter.WriteName("k");
                        BsonSerializer.Serialize(bsonWriter, typeof(TKey), entry.Key);
                        bsonWriter.WriteName("v");
                        BsonSerializer.Serialize(bsonWriter, typeof(TValue), entry.Value, itemSerializationOptions);
                        bsonWriter.WriteEndDocument();
                    }
                    bsonWriter.WriteEndArray();
                    break;

                default:
                    var message = string.Format(
                        "'{0}' is not a valid {1} representation.",
                        representation,
                        BsonUtils.GetFriendlyTypeName(typeof(IDictionary <TKey, TValue>)));
                    throw new BsonSerializationException(message);
                }
            }
        }
Beispiel #18
0
 public new void WriteTo(BsonWriter bsonWriter)
 {
     BsonSerializer.Serialize(bsonWriter, this);
 }
Beispiel #19
0
        public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
                return;
            }
            object document;
            Type   type;

            var json = value.ToString();

            Console.WriteLine("serialize");
            Console.WriteLine(json);

            if (json.StarstAndEnds("{", "}"))
            {
                document = BsonDocument.Parse(json);
                type     = typeof(BsonDocument);
            }
            else if (json.StarstAndEnds("[", "]"))
            {
                document = BsonSerializer.Deserialize <BsonArray> (json);
                type     = typeof(BsonArray);
            }
            else if (json.IsBsonISODate())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> (json);
                type     = typeof(BsonDateTime);
            }
            else if (json.IsISOString())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> ("ISODate(\"" + json + "\")");
                type     = typeof(BsonDateTime);
            }
            else if (json.IsMsFormat())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> ("new " + json.Replace("/", ""));
                type     = typeof(BsonDateTime);
            }
            else if (json.IsBool())
            {
                document = BsonSerializer.Deserialize <BsonBoolean> (json);
                type     = typeof(BsonBoolean);
            }
            else if (json.IsInt())
            {
                document = BsonSerializer.Deserialize <BsonInt32> (json);
                type     = typeof(BsonInt32);
            }
            else if (json.IsBsonNumberLong())
            {
                document = BsonSerializer.Deserialize <BsonInt64> (json);
                type     = typeof(BsonInt64);
            }
            else if (json.IsLong())
            {
                document = BsonSerializer.Deserialize <BsonInt64> ("NumberLong(\"" + json + "\")");
                type     = typeof(BsonInt64);
            }
            else if (json.IsDouble())
            {
                document = BsonSerializer.Deserialize <BsonDouble> (json);
                type     = typeof(BsonDouble);
            }
            else
            {
                document = BsonSerializer.Deserialize <BsonString> (json.StarstAndEnds("\"", "\"")
                                        ?json
                                        :"\"" + json + "\"");
                type = typeof(BsonString);
            }

            BsonSerializer.Serialize(bsonWriter, type, document, options);
        }