Ejemplo n.º 1
0
        public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
        {
            var settingsPropertyValueCollection = new SettingsPropertyValueCollection();

            if (collection.Count < 1)
            {
                return(settingsPropertyValueCollection);
            }

            var username = (string)context["UserName"];

            if (string.IsNullOrWhiteSpace(username))
            {
                return(settingsPropertyValueCollection);
            }

            var query        = Query.And(Query.EQ("ApplicationName", ApplicationName), Query.EQ("Username", username));
            var bsonDocument = mongoCollection.FindOneAs <BsonDocument>(query);

            if (bsonDocument == null)
            {
                return(settingsPropertyValueCollection);
            }

            foreach (SettingsProperty settingsProperty in collection)
            {
                var settingsPropertyValue = new SettingsPropertyValue(settingsProperty);
                settingsPropertyValueCollection.Add(settingsPropertyValue);

                if (!bsonDocument.Contains(settingsPropertyValue.Name))
                {
                    continue;
                }

                var value = BsonTypeMapper.MapToDotNetValue(bsonDocument[settingsPropertyValue.Name]);
                if (value == null)
                {
                    continue;
                }
                settingsPropertyValue.PropertyValue = value;
                settingsPropertyValue.IsDirty       = false;
                settingsPropertyValue.Deserialized  = true;
            }

            var update = Update.Set("LastActivityDate", DateTime.Now);

            mongoCollection.Update(query, update);

            return(settingsPropertyValueCollection);
        }
Ejemplo n.º 2
0
        public void TestMapBsonJavaScript()
        {
            var value     = new BsonJavaScript("code");
            var bsonValue = (BsonJavaScript)BsonTypeMapper.MapToBsonValue(value);

            Assert.Same(value, bsonValue);
            var bsonJavaScript = (BsonJavaScript)BsonTypeMapper.MapToBsonValue(value, BsonType.JavaScript);

            Assert.Same(value, bsonJavaScript);
            var bsonJavaScriptWithScope = (BsonJavaScriptWithScope)BsonTypeMapper.MapToBsonValue(value, BsonType.JavaScriptWithScope);

            Assert.Equal(value.Code, bsonJavaScriptWithScope.Code);
            Assert.Equal(new BsonDocument(), bsonJavaScriptWithScope.Scope);
        }
Ejemplo n.º 3
0
        public static void Register(Type type)
        {
            if (_registrations.Contains(type))
            {
                return;
            }

            BsonTypeMapper.RegisterCustomTypeMapper(
                type,
                new StringValueCustomBsonTypeMapper()
                );

            _registrations.Add(type);
        }
Ejemplo n.º 4
0
        public static T getObjValue <T>(object sessionObj)
        {
            if (sessionObj == null)
            {
                return(default(T));
            }

            if (sessionObj is T)
            {
                return((T)sessionObj);
            }

            if (sessionObj is BsonDocument)
            {
                return((T)BsonSerializer.Deserialize <T>(sessionObj as BsonDocument));
            }

            if (sessionObj is BsonValue)
            {
                return((T)BsonTypeMapper.MapToDotNetValue(sessionObj as BsonValue));
            }

            if (sessionObj is Newtonsoft.Json.Linq.JObject)
            {
                return(((JObject)sessionObj).ToObject <T>());
            }

            if (sessionObj is JArray)
            {
                var jarr = sessionObj as JArray;
                if (typeof(T) == typeof(BsonDocument))
                {
                    var doc = new BsonDocument();

                    foreach (var item in jarr)
                    {
                        doc.Add((string)item["Name"], BsonValue.Create(((JValue)item["Value"]).Value));
                    }

                    return((T)(object)doc);
                }
                else
                {
                    return(jarr.ToObject <T>());
                }
            }


            return(default(T));
        }
Ejemplo n.º 5
0
        public object GetCollection(string constring, string db, string collection)
        {
            MongoClient dbClient       = new MongoClient(constring);
            var         dbase          = dbClient.GetDatabase(db);
            var         coll           = dbase.GetCollection <BsonDocument>("Todo");
            var         returnDocument = coll.Find(new BsonDocument()).FirstOrDefault();

            var dotNetObj = BsonTypeMapper.MapToDotNetValue(returnDocument);

            //var dotNetObj = returnDocument.ConvertAll(BsonTypeMapper.MapToDotNetValue);
            JsonConvert.SerializeObject(dotNetObj);

            return(dotNetObj);
        }
Ejemplo n.º 6
0
        public void TestBsonTypeMapperTryMapToBsonValue()
        {
            BsonValue document1, document2, document3, document4;

            Assert.IsTrue(BsonTypeMapper.TryMapToBsonValue(_dictionary, out document1));
            Assert.IsTrue(BsonTypeMapper.TryMapToBsonValue(_hashtable, out document2));
            Assert.IsTrue(BsonTypeMapper.TryMapToBsonValue(_idictionaryNonGeneric, out document3));
            Assert.IsTrue(BsonTypeMapper.TryMapToBsonValue(_idictionary, out document4));

            Assert.AreEqual("Dictionary<string, object>", ((BsonDocument)document1)["type"].AsString);
            Assert.AreEqual("Hashtable", ((BsonDocument)document2)["type"].AsString);
            Assert.AreEqual("IDictionary", ((BsonDocument)document3)["type"].AsString);
            Assert.AreEqual("IDictionary<string, object>", ((BsonDocument)document4)["type"].AsString);
        }
Ejemplo n.º 7
0
        private void DeserializeExtraElementValue(
            BsonDeserializationContext context,
            Dictionary <string, object> values,
            string elementName,
            BsonMemberMap extraElementsMemberMap)
        {
            var bsonReader = context.Reader;

            if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
            {
                BsonDocument extraElements;
                object       obj;
                if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj))
                {
                    extraElements = (BsonDocument)obj;
                }
                else
                {
                    extraElements = new BsonDocument();
                    values.Add(extraElementsMemberMap.ElementName, extraElements);
                }

                var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
                extraElements[elementName] = bsonValue;
            }
            else
            {
                IDictionary <string, object> extraElements;
                object obj;
                if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj))
                {
                    extraElements = (IDictionary <string, object>)obj;
                }
                else
                {
                    if (extraElementsMemberMap.MemberType == typeof(IDictionary <string, object>))
                    {
                        extraElements = new Dictionary <string, object>();
                    }
                    else
                    {
                        extraElements = (IDictionary <string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
                    }
                    values.Add(extraElementsMemberMap.ElementName, extraElements);
                }

                var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
                extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
            }
        }
        public static void Register(Type type)
        {
            if (_registrations.Contains(type))
            {
                return;
            }

            BsonTypeMapper.RegisterCustomTypeMapper(
                type,
                new EventStoreIdentityCustomBsonTypeMapper()
                );

            _registrations.Add(type);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Retrieves the content of the collection object with respect to the filters
        /// </summary>
        /// <param name="dal">The MongoDB client object initialized</param>
        /// <param name="collection">Name of the collection to retrieve</param>
        /// <param name="paramss">The filters to be included in a form of key/value pairs</param>
        /// <returns></returns>
        public object GetCollectionWithParams(DALOps dal, string collection, Dictionary <object, object> paramss)
        {
            if (paramss.Count == 1)
            {
                var filter = Builders <BsonDocument> .Filter.Eq(paramss.Keys.First().ToString(), paramss.Values.First().ToString());

                var coll           = dal._database.GetCollection <BsonDocument>(collection);
                var returnDocument = coll.Find(filter).FirstOrDefault();

                if (returnDocument == null)
                {
                    string dd = "No record found";
                    JsonConvert.SerializeObject(dd);
                    return(dd);
                }
                else
                {
                    var dotNetObj = BsonTypeMapper.MapToDotNetValue(returnDocument);
                    JsonConvert.SerializeObject(dotNetObj);
                    return(dotNetObj);
                }
            }
            else
            {
                var filter = Builders <BsonDocument> .Filter.Eq(paramss.Keys.First().ToString(), paramss.Values.First().ToString());

                for (int i = 1; i < paramss.Count; i++)
                {
                    var key   = paramss.Keys.ElementAt(i).ToString();
                    var value = paramss.Values.ElementAt(i).ToString();

                    if ((value.ToString().ToLowerInvariant() == "true") || (value.ToString().ToLowerInvariant() == "false"))
                    {
                        filter = filter & (Builders <BsonDocument> .Filter.Eq(key, Convert.ToBoolean(value)));
                    }
                    else
                    {
                        filter = filter & (Builders <BsonDocument> .Filter.Eq(key, value));
                    }
                }
                var coll           = dal._database.GetCollection <BsonDocument>(collection);
                var returnDocument = coll.Find(filter).FirstOrDefault();
                var dotNetObj      = BsonTypeMapper.MapToDotNetValue(returnDocument);
                //var dotNetObj = returnDocument.ConvertAll(BsonTypeMapper.MapToDotNetValue);
                JsonConvert.SerializeObject(dotNetObj);

                return(dotNetObj);
            }
        }
Ejemplo n.º 10
0
        public void TestMapString()
        {
            var value     = "hello";
            var bsonValue = (BsonString)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue("1", BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDateTime = (BsonDateTime)BsonTypeMapper.MapToBsonValue("2010-01-02", BsonType.DateTime);

            Assert.Equal(new DateTime(2010, 1, 2), bsonDateTime.ToUniversalTime());
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Decimal128);

            Assert.Equal((Decimal128)1.2M, bsonDecimal128.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Double);

            Assert.Equal(1.2, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue("1", BsonType.Int32);

            Assert.Equal(1, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue("1", BsonType.Int64);

            Assert.Equal(1L, bsonInt64.Value);
            var bsonJavaScript = (BsonJavaScript)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScript);

            Assert.Equal("code", bsonJavaScript.Code);
            var bsonJavaScriptWithScope = (BsonJavaScriptWithScope)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScriptWithScope);

            Assert.Equal("code", bsonJavaScriptWithScope.Code);
            Assert.Equal(0, bsonJavaScriptWithScope.Scope.ElementCount);
            var objectId     = ObjectId.GenerateNewId();
            var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(objectId.ToString(), BsonType.ObjectId);

            Assert.Equal(objectId, bsonObjectId.Value);
            var bsonRegularExpression = (BsonRegularExpression)BsonTypeMapper.MapToBsonValue(new Regex("pattern"), BsonType.RegularExpression);

            Assert.Equal("pattern", bsonRegularExpression.Pattern);
            Assert.Equal("", bsonRegularExpression.Options);
            var bsonString = (BsonString)BsonTypeMapper.MapToBsonValue(value, BsonType.String);

            Assert.Equal(value, bsonString.Value);
            var bsonSymbol = (BsonSymbol)BsonTypeMapper.MapToBsonValue("symbol", BsonType.Symbol);

            Assert.Same(BsonSymbolTable.Lookup("symbol"), bsonSymbol);
            var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue("1", BsonType.Timestamp);

            Assert.Equal(1L, bsonTimestamp.Value);
        }
Ejemplo n.º 11
0
 public IActionResult Get(string id)
 {
     try
     {
         System.Console.WriteLine("Product deltails for Product id : " + id);
         ProductDAO   prodDAO = new ProductDAO();
         BsonDocument doc     = prodDAO.GetById(id);
         return(new JsonResult(BsonTypeMapper.MapToDotNetValue(doc)));
     }
     catch (System.Exception e)
     {
         System.Console.WriteLine(e.Message);
         return(NotFound(new { message = "Not Found" }));
     }
 }
Ejemplo n.º 12
0
        public void TestMapByteArray()
        {
            var value     = ObjectId.GenerateNewId().ToByteArray();
            var bsonValue = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreSame(value, bsonValue.Bytes);
            Assert.AreEqual(BsonBinarySubType.Binary, bsonValue.SubType);
            var bsonBinary = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value, BsonType.Binary);

            Assert.AreSame(value, bsonBinary.Bytes);
            Assert.AreEqual(BsonBinarySubType.Binary, bsonBinary.SubType);
            var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(value, BsonType.ObjectId);

            Assert.IsTrue(value.SequenceEqual(bsonObjectId.ToByteArray()));
        }
Ejemplo n.º 13
0
        public object InsertToCollection(string collection, object item)
        {
            var coll = _database.GetCollection <BsonDocument>(collection);

            var returnDocument = new BsonDocument(item.ToBsonDocument());

            returnDocument.Remove("_t");
            coll.InsertOne(returnDocument);

            var dotNetObj = BsonTypeMapper.MapToDotNetValue(returnDocument);

            JsonConvert.SerializeObject(dotNetObj);

            return(dotNetObj);
        }
Ejemplo n.º 14
0
 private static Type ResolveProviderType(BsonValue elementValue, bool isKey)
 {
     if (elementValue.GetType() == typeof(BsonArray) || elementValue.GetType() == typeof(BsonDocument))
     {
         return(elementValue.GetType());
     }
     else if (BsonTypeMapper.MapToDotNetValue(elementValue) != null)
     {
         return(GetRawValueType(elementValue, isKey));
     }
     else
     {
         return(null);
     }
 }
        public WriteConcernResult ModifyAll <TEntity>(
            ICommandRepository commandRepository,
            ISpecificationQueryStrategy <TEntity> specificationStrategy,
            WriteConcern writeConcern,
            params MongoUpdateItem <TEntity>[] updateItems) where TEntity : class
        {
            if (writeConcern == null)
            {
                throw new ArgumentNullException("writeConcern", "writeConcern is null.");
            }

            if (specificationStrategy == null)
            {
                throw new ArgumentNullException("predicate", "predicate is null.");
            }

            if (updateItems == null)
            {
                throw new ArgumentNullException("mongoUpdate", "mongoUpdate is null.");
            }

            var mongoDatabase = commandRepository.ObjectContext as MongoDatabase;

            if (mongoDatabase == null)
            {
                throw new NotSupportedException("Load can only be used with a DbContext");
            }

            var updateBuilder = new UpdateBuilder();

            foreach (var item in updateItems)
            {
                var value = BsonTypeMapper.MapToBsonValue(item.Value);
                updateBuilder.Set(item.Key, value);
            }

            var collection = mongoDatabase.GetCollection <TEntity>(typeof(TEntity).FullName);
            var query      = collection.AsQueryable().AddQueryStrategy(specificationStrategy);
            var mongoQuery = ((MongoQueryable <TEntity>)query).GetMongoQuery();

            var result = collection.Update(mongoQuery, updateBuilder, UpdateFlags.Multi, writeConcern);

            var modifyAllEvent = new MongoDbEntityModifedAllEvent <TEntity>(commandRepository, specificationStrategy, updateBuilder, writeConcern);

            commandRepository.RaiseEvent(modifyAllEvent);

            return(result);
        }
Ejemplo n.º 16
0
        public ChannelItem GetChannelItem(string channelItemId)
        {
            var informationCollection = this.Database.GetCollection <InformationEntry>("information");
            var informationItem       = informationCollection?.Find(item => item.InformationId == channelItemId && item.IsActive).First();

            var propertyDictionary = informationItem?.Properties.ToDictionary(
                item => item.Name,
                item => item.Values.Select(value => BsonTypeMapper.MapToDotNetValue(value))
                );

            return(new ChannelItem
            {
                Id = channelItemId,
                Properties = propertyDictionary
            });
        }
Ejemplo n.º 17
0
        public static BsonDocument ToBsonDoc(SiaqodbDocument cobj)
        {
            var doc = new BsonDocument();

            doc["_id"]  = cobj.Key;
            doc["_rev"] = BsonTypeMapper.MapToBsonValue(cobj.Version);
            doc["doc"]  = cobj.Content;
            if (cobj.Tags != null)
            {
                foreach (string tagName in cobj.Tags.Keys)
                {
                    doc[tagName] = BsonTypeMapper.MapToBsonValue(cobj.Tags[tagName]);
                }
            }
            return(doc);
        }
Ejemplo n.º 18
0
        public static KeyValuePair <string, BsonValue> GetMongoProperty(T entity, string propertyName)
        {
            var value          = typeof(T).GetProperty(propertyName).GetValue(entity);
            var memberMap      = BsonClassMap.LookupClassMap(typeof(T)).GetMemberMap(propertyName);
            var memberBsonType = GetBsonType(value, memberMap);

            // some "non-string types are mapped to string"
            if (memberBsonType == BsonType.String)
            {
                value = value.ToString();
            }

            var bsonPropertyValue = BsonTypeMapper.MapToBsonValue(value, memberBsonType);

            return(new KeyValuePair <string, BsonValue>(propertyName, bsonPropertyValue));
        }
Ejemplo n.º 19
0
        public void TestMapSingle()
        {
            var value     = (float)1.2;
            var bsonValue = (BsonDouble)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue(value, BsonType.Decimal128);

            Assert.Equal((Decimal128)value, bsonDecimal128.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.Equal(value, bsonDouble.Value);
        }
Ejemplo n.º 20
0
        // This method should be called as soon as possible. Multiple calls are allowed.
        public static void Register()
        {
            if (_registered)
            {
                return;
            }

            _registered = true;

            BsonSerializer.RegisterSerializer(typeof(Dictionary), new DictionarySerializer());
            BsonSerializer.RegisterSerializer(typeof(LazyDictionary), new LazyDictionarySerializer());
            BsonSerializer.RegisterSerializer(typeof(RawDictionary), new RawDictionarySerializer());
            BsonSerializer.RegisterSerializer(typeof(PSObject), new PSObjectSerializer());

            BsonTypeMapper.RegisterCustomTypeMapper(typeof(PSObject), new PSObjectTypeMapper());
        }
Ejemplo n.º 21
0
        private BsonValue GetBsonValueWithLayout(LogEventInfo logEvent, string layoutText)
        {
            var layout = Layout.FromString(layoutText);
            var value  = RenderLogEvent(layout, logEvent);

            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }
            BsonValue bsonValue;

            if (!BsonTypeMapper.TryMapToBsonValue(value, out bsonValue))
            {
                bsonValue = bsonValue.ToBsonDocument();
            }
            return(bsonValue);
        }
Ejemplo n.º 22
0
        public static void p5_mongo_aggregate(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning
            using (new Utilities.ArgsRemover(e.Args, true)) {
                // Retrieving table name and running sanity check
                var tableName = e.Args.Get <string> (context);
                if (string.IsNullOrEmpty(tableName))
                {
                    throw new LambdaException("No table name supplied to [p5.mongo.find]", e.Args, context);
                }

                // Retrieving collection
                var collection = Database.Instance.MongoDatabase.GetCollection <BsonDocument> (tableName);

                // Retrieving grouping clauses and creating BsonDocument for Group method
                BsonDocument doc = new BsonDocument();
                doc.Add("_id", BsonValue.Create(e.Args ["_id"].Value));
                foreach (var idxChild in e.Args.Children.Where(ix => ix.Name != "_id" && ix.Name != "where"))
                {
                    doc.Add(idxChild.Name, new BsonDocument(idxChild.Get <string> (context), 1));
                }

                // Retrieving filter criteria
                FilterDefinition <BsonDocument> filter = null;
                if (e.Args ["where"] != null && e.Args ["where"].Children.Count > 0)
                {
                    filter = Filter.CreateFilter(context, e.Args);
                }

                // Running query
                var aggregate = filter == null?
                                collection.Aggregate().Group(doc) :
                                    collection.Aggregate().Match(filter).Group(doc);

                // Looping through each result
                foreach (var idxDoc in aggregate.ToEnumerable())
                {
                    // Making sure we return currently iterated document to caller
                    var id      = BsonTypeMapper.MapToDotNetValue(idxDoc.Elements.First(ix => ix.Name == "_id").Value);
                    var idxNode = e.Args.Add(tableName, id).LastChild;

                    // Parsing document, and stuffing results into idxNode, making sure we skip the "_id" element for main document
                    DocumentParser.ParseDocument(context, idxNode, idxDoc, "_id");
                }
            }
        }
Ejemplo n.º 23
0
 public override object Serialize <T>(T value)
 {
     // if can be converted to bsonvalue, return the value
     try
     {
         BsonValue bsonValue;
         if (BsonTypeMapper.TryMapToBsonValue(value, out bsonValue))
         {
             return(value);
         }
     }
     catch
     {
         // ignored. TryMapToBsonValue can throw exception (i.e. when the type is an array of objects that cannot be mapped to a bsonvalue)
     }
     return(value.ToBsonDocument(typeof(object)));
 }
        protected override T GetQuery(TKey key, IFetchStrategy <T> fetchStrategy)
        {
            var keyBsonType   = ((StringSerializer)BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.GetSerializer()).Representation;
            var keyMemberName = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.MemberName;

            if (IsValidKey(key))
            {
                var keyBsonValue = BsonTypeMapper.MapToBsonValue(key, keyBsonType);
                var filter       = Builders <T> .Filter.Eq(keyMemberName, keyBsonValue);

                return(BaseCollection().Find(filter).FirstOrDefault());
            }
            else
            {
                return(default(T));
            }
        }
Ejemplo n.º 25
0
        public void TestMapUInt64()
        {
            var value     = (ulong)1;
            var bsonValue = (BsonInt64)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.AreEqual(true, bsonBoolean.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.AreEqual(value, bsonDouble.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.AreEqual(value, bsonInt64.Value);
            var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue(value, BsonType.Timestamp);

            Assert.AreEqual(value, bsonTimestamp.Value);
        }
Ejemplo n.º 26
0
        public void TestMapUInt32()
        {
            var value     = (uint)1;
            var bsonValue = (BsonInt64)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.AreEqual(true, bsonBoolean.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.AreEqual(value, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);

            Assert.AreEqual(value, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.AreEqual(value, bsonInt64.Value);
        }
Ejemplo n.º 27
0
        private static Type GetRawValueType(BsonValue elementValue, bool isKey = false)
        {
            Type elementType;

            switch (elementValue.BsonType)
            {
            case BsonType.DateTime:
                elementType = typeof(DateTime);
                break;

            default:
                elementType = BsonTypeMapper.MapToDotNetValue(elementValue).GetType();
                break;
            }
            if (!isKey && elementType.IsValueType)
            {
                elementType = typeof(Nullable <>).MakeGenericType(elementType);
            }
            return(elementType);
        }
Ejemplo n.º 28
0
        private TClass Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            CheckItemMap();
            var reader      = context.Reader;
            var bsonType    = reader.CurrentBsonType;
            var elementType = typeof(MongoDBRef);

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

            case BsonType.Array:
                reader.ReadStartArray();
                var lista_objs = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(itemType));

                //var serializer = BsonSerializer.LookupSerializer(elementType);
                while (reader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var mref = BsonSerializer.Deserialize(reader, elementType) as MongoDBRef;
                    if (mref == null)
                    {
                        lista_objs.Add(null);
                    }
                    else
                    {
                        var obj = ReflectionTools.CreateInstance(itemType);
                        itemIdMap.Setter.Invoke(obj, BsonTypeMapper.MapToDotNetValue(mref.Id));
                        lista_objs.Add(obj);
                    }
                }
                reader.ReadEndArray();
                return((TClass)(object)lista_objs);

            default:

                var message = string.Format("Can't deserialize a {0} from BsonType {1}.", elementType.FullName, bsonType);
                throw new ApplicationException(message);
            }
        }
Ejemplo n.º 29
0
        private static object ConvertRawValue(BsonValue bsonValue)
        {
            if (bsonValue == null)
            {
                return(null);
            }

            if (BsonTypeMapper.MapToDotNetValue(bsonValue) != null)
            {
                if (bsonValue.IsObjectId)
                {
                    return(bsonValue.ToString());
                }
                else if (bsonValue.IsGuid)
                {
                    return(bsonValue.AsGuid);
                }
                else
                {
                    switch (bsonValue.BsonType)
                    {
                    case BsonType.DateTime:
                        return(UnixEpoch + TimeSpan.FromMilliseconds(bsonValue.AsBsonDateTime.MillisecondsSinceEpoch));

                    default:
                        return(BsonTypeMapper.MapToDotNetValue(bsonValue));
                    }
                }
            }
            else
            {
                switch (bsonValue.BsonType)
                {
                case BsonType.Binary:
                    return(bsonValue.AsBsonBinaryData.Bytes);

                default:
                    return(BsonTypeMapper.MapToDotNetValue(bsonValue));
                }
            }
        }
Ejemplo n.º 30
0
        private BsonDocument BuildBsonDocument(LoggingEvent log)
        {
            if (_fields.Count == 0)
            {
                return(BackwardCompatibility.BuildBsonDocument(log));
            }
            var doc = new BsonDocument();

            foreach (MongoAppenderFileld field in _fields)
            {
                object    value = field.Layout.Format(log);
                BsonValue bsonValue;
                // if the object is complex and can't be mapped to a simple object, convert to bson document
                if (!BsonTypeMapper.TryMapToBsonValue(value, out bsonValue))
                {
                    bsonValue = value.ToBsonDocument();
                }
                doc.Add(field.Name, bsonValue);
            }
            return(doc);
        }