/// <summary>
        /// Serializes a value.
        /// </summary>
        /// <param name="context">The serialization context.</param>
        /// <param name="args">The serialization args.</param>
        /// <param name="value">The value.</param>
        protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, GeoJsonBoundingBox <TCoordinates> value)
        {
            var bsonWriter = context.Writer;

            // serialize min and max to a dummy document and then flatten the two arrays and serialize that
            var document = new BsonDocument();

            using (var documentWriter = new BsonDocumentWriter(document))
            {
                var documentContext = BsonSerializationContext.CreateRoot(documentWriter);
                documentWriter.WriteStartDocument();
                documentWriter.WriteName("min");
                _coordinatesSerializer.Serialize(documentContext, value.Min);
                documentWriter.WriteName("max");
                _coordinatesSerializer.Serialize(documentContext, value.Max);
                documentWriter.WriteEndDocument();
            }

            var flattenedArray = new BsonArray();

            flattenedArray.AddRange(document["min"].AsBsonArray);
            flattenedArray.AddRange(document["max"].AsBsonArray);

            BsonArraySerializer.Instance.Serialize(context, flattenedArray);
        }
Пример #2
0
        private void ProcessPropertyInfo(dynamic property, PropertyInfo propertyInfo, BsonDocument propertyDoc, bool fromAPI = false)
        {
            var propertyValue = propertyInfo.GetValue(property);

            if (IsCollectionType(propertyValue, propertyInfo))
            {
                var items = new BsonArray();
                try
                {
                    items.AddRange(ListProperty(propertyValue, fromAPI));
                }
                catch (RuntimeBinderException)
                {
                    if (propertyInfo.PropertyType.IsArray)
                    {
                        items.AddRange(ListArray(propertyValue));
                    }
                }

                propertyDoc.Add(new BsonElement(propertyInfo.Name, items));
            }
            else
            {
                propertyDoc.Add(ProcessPropertyInfo(propertyInfo, propertyValue, fromAPI));
            }
        }
        /// <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 boundingBox = (GeoJsonBoundingBox <TCoordinates>)value;

                // serialize min and max to a dummy document and then flatten the two arrays and serialize that
                var document = new BsonDocument();
                using (var documentWriter = BsonWriter.Create(document))
                {
                    documentWriter.WriteStartDocument();
                    documentWriter.WriteName("min");
                    _coordinatesSerializer.Serialize(documentWriter, typeof(TCoordinates), boundingBox.Min, null);
                    documentWriter.WriteName("max");
                    _coordinatesSerializer.Serialize(documentWriter, typeof(TCoordinates), boundingBox.Max, null);
                    documentWriter.WriteEndDocument();
                }

                var flattenedArray = new BsonArray();
                flattenedArray.AddRange(document["min"].AsBsonArray);
                flattenedArray.AddRange(document["max"].AsBsonArray);

                BsonArraySerializer.Instance.Serialize(bsonWriter, typeof(BsonArray), flattenedArray, null);
            }
        }
Пример #4
0
        //private void AddExceptions(BsonDocument doc, dynamic model)
        //{
        //    var exceptionElements = _modelExceptionsFactory.ActivityLogExceptions(model);
        //    foreach (var exElement in exceptionElements)
        //    {
        //        doc.Add(exElement);
        //    }
        //}

        private BsonElement ProcessPropertyInfo(PropertyInfo propertyInfo, dynamic propertyValue, bool fromAPI = false)
        {
            var type = propertyInfo.PropertyType;

            if (IsPrimitiveType(type))
            {
                var elementValue = propertyValue ?? string.Empty;
                return(new BsonElement(propertyInfo.Name, elementValue.ToString()));
            }
            if (IsNumericType(type))
            {
                var elementValue = propertyValue.ToString() ?? string.Empty;
                return(new BsonElement(propertyInfo.Name, elementValue));
            }
            if (propertyInfo.PropertyType == typeof(DateTime?) || propertyInfo.PropertyType == typeof(DateTime))
            {
                var elementValue = propertyValue != null
                    ? ((DateTime)propertyValue).Date == DateTime.MinValue ? string.Empty : ((DateTime)propertyValue).ToString()
                    : string.Empty;
                return(new BsonElement(propertyInfo.Name, elementValue));
            }

            if (propertyInfo.ReflectedType != null && propertyInfo.ReflectedType == typeof(MobileResponseModel) && IsCollectionType(propertyValue, propertyInfo))
            {
                var items = new BsonArray();
                try
                {
                    items.AddRange(ListProperty(propertyValue, fromAPI));
                }
                catch (RuntimeBinderException)
                {
                    if (propertyInfo.PropertyType.IsArray)
                    {
                        items.AddRange(ListArray(propertyValue));
                    }
                }

                return(new BsonElement(propertyInfo.Name, items));
            }
            if (propertyInfo.PropertyType.IsNullableEnum() || propertyInfo.PropertyType.IsEnum)
            {
                var elementValue = propertyValue != null?propertyValue.ToString() : string.Empty;

                return(new BsonElement(propertyInfo.Name, elementValue));
            }
            else
            {
                var elementValue = propertyValue != null?ComplexProperty(propertyValue, fromAPI) : string.Empty;

                return(new BsonElement(propertyInfo.Name, elementValue));
            }
        }
Пример #5
0
        public void TestAddRangeObjectIdNull()
        {
            var array  = new BsonArray();
            var values = (ObjectId[])null;

            Assert.Throws <ArgumentNullException>(() => { array.AddRange(values); });
        }
Пример #6
0
        /// <summary>
        ///     GetActionArray
        /// </summary>
        /// <param name="actionList"></param>
        /// <returns></returns>
        public static BsonArray GetActionArray(List <string> actionList)
        {
            var result = new BsonArray();

            result.AddRange(actionList);
            return(result);
        }
 public void TestAddRangeBooleanNull()
 {
     var array = new BsonArray();
     var values = (bool[])null;
     array.AddRange(values);
     Assert.AreEqual(0, array.Count);
 }
 public void TestAddRangeDateTimeNull()
 {
     var array = new BsonArray();
     var values = (DateTime[])null;
     array.AddRange(values);
     Assert.AreEqual(0, array.Count);
 }
 public void TestAddRangeInt32Null()
 {
     var array = new BsonArray();
     var values = (int[])null;
     array.AddRange(values);
     Assert.AreEqual(0, array.Count);
 }
Пример #10
0
        public async Task AtualizarInteresse(RegistroInteresseDTO dto)
        {
            await Task.Run(() =>
            {
                var query = Query.And(Query <UsuarioMOD> .EQ(_ => _.Id, dto.IdUsuario),
                                      Query.EQ("Interesses._id", dto.Interesse.Id));

                var portes = new BsonArray();
                portes.AddRange(dto.Interesse.Porte);

                var update = Update.Set("Interesses.$.IdadeMinimaEmAnos", dto.Interesse.IdadeMinimaEmAnos)
                             .Set("Interesses.$.IdadeMaximaEmAnos", dto.Interesse.IdadeMaximaEmAnos)
                             .Set("Interesses.$.Porte", portes)
                             .Set("Interesses.$.TomouVermifugo", dto.Interesse.TomouVermifugo)
                             .Set("Interesses.$.EhCastrado", dto.Interesse.EhCastrado)
                             .Set("Interesses.$.EhVacinado", dto.Interesse.EhVacinado)
                             .Set("Interesses.$.Especie", dto.Interesse.Especie);


                if (!string.IsNullOrWhiteSpace(dto.Interesse.Raca))
                {
                    update.Set("Interesses.$.Raca", dto.Interesse.Raca);
                }

                _conn.Conectar("mongodb://localhost", "napegada", "usuario").Update(query, update);
            });
        }
Пример #11
0
        public void TestAddRangeInt32Null()
        {
            var array  = new BsonArray();
            var values = (int[])null;

            array.AddRange(values);
            Assert.AreEqual(0, array.Count);
        }
Пример #12
0
        public void TestAddRangeDateTimeNull()
        {
            var array  = new BsonArray();
            var values = (DateTime[])null;

            array.AddRange(values);
            Assert.AreEqual(0, array.Count);
        }
Пример #13
0
        public void TestAddRangeIEnumerableNull()
        {
            var array  = new BsonArray();
            var values = (object[])null;

            array.AddRange(values);
            Assert.AreEqual(0, array.Count);
        }
Пример #14
0
        public void TestAddRangeBooleanNull()
        {
            var array  = new BsonArray();
            var values = (bool[])null;

            array.AddRange(values);
            Assert.AreEqual(0, array.Count);
        }
Пример #15
0
        public void TestAddRangeObjectIdNull()
        {
            var array  = new BsonArray();
            var values = (ObjectId[])null;

            array.AddRange(values);
            Assert.AreEqual(0, array.Count);
        }
        public static BsonArray ToBsonArray(this IEnumerable <BsonValue> values)
        {
            var array = new BsonArray();

            array.AddRange(values);

            return(array);
        }
Пример #17
0
 /// <summary>
 /// 获取角色下所有角色
 /// </summary>
 /// <param name="RoleId">角色Id</param>
 /// <returns>返回所有角色集合</returns>
 public BsonArray GetAllChildren(ObjectId RoleId)
 {
     BsonArray RoleList = new BsonArray();
     List<BsonDocument> RoleDoc = dh.GetAllData("userroles", new BsonDocument { { "PUserRole", RoleId } });
     foreach (BsonDocument Role in RoleDoc)
     {
         UserRole ur = new UserRole(Role);
         ur.UserRolePowers = ups.GetAll(ur.UserRolePowers);
         RoleList.AddRange(GetAllChildren(ur.Id));
         RoleList.Add(ur.ToBsonDocument());
     }
     return RoleList;
 }
Пример #18
0
        /// <summary>
        ///     添加自定义角色
        /// </summary>
        public static CommandResult createRole(MongoDatabase mongoDb, Role role)
        {
            var mongoCmd   = new CommandDocument("createRole", role.Rolename);
            var privileges = new BsonArray();

            privileges.AddRange(role.Privileges.Select(x => x.AsBsonDocument()));
            mongoCmd.Add("privileges", privileges);
            var roles = new BsonArray();

            roles.AddRange(role.Roles.Select(x => x.AsBsonValue()));
            mongoCmd.Add("roles", roles);
            return(ExecuteMongoDBCommand(mongoCmd, mongoDb));
        }
 private static void AddClause(BsonArray clauses, BsonDocument filter)
 {
     if (filter.ElementCount == 1 && filter.GetElement(0).Name == "$or")
     {
         // flatten nested $or
         clauses.AddRange((BsonArray)filter[0]);
     }
     else
     {
         // we could shortcut the user's query if there are no elements in the filter, but
         // I'd rather be literal and let them discover the problem on their own.
         clauses.Add(filter);
     }
 }
        /// <summary>
        /// Converts an <see cref="OriginalContext"/> into its <see cref="BsonDocument" /> representation
        /// </summary>
        /// <param name="originalContext">The <see cref="OriginalContext"/></param>
        /// <returns>A <see cref="BsonDocument" /> representation of the <see cref="OriginalContext"/></returns>
        public static BsonDocument AsBson(this OriginalContext originalContext)
        {
            var claims = new BsonArray();

            claims.AddRange(originalContext.Claims.Select(_ => _.ToBsonDocument()));

            return(new BsonDocument(new Dictionary <string, object>
            {
                { EventConstants.APPLICATION, originalContext.Application.Value },
                { EventConstants.BOUNDED_CONTEXT, originalContext.BoundedContext.Value },
                { EventConstants.TENANT, originalContext.Tenant.Value },
                { EventConstants.ENVIRONMENT, originalContext.Environment.Value },
                { EventConstants.CLAIMS, claims }
            }));
        }
        public async void CrwaledProducts(string[] ids)
        {
            BsonArray array = new BsonArray();

            array.AddRange(ids.Select(x => ObjectId.Parse(x)));
            var query = Query <DigikalaBasePage> .In(x => x._id, array);

            var basePages = digikalaBasePages.Find(query);

            foreach (var item in basePages)
            {
                item.Crawled   = true;
                item.CrawlDate = DateTime.Now;
                digikalaBasePages.Save(item);
            }
        }
Пример #22
0
 /// <summary>
 ///     增加条件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void cmdAddCondition_Click(object sender, EventArgs e)
 {
     try
     {
         var frmAddStage = new FrmAddStage();
         UIAssistant.OpenModalForm(frmAddStage, false, true);
         if (frmAddStage.DialogResult == DialogResult.OK)
         {
             stages.AddRange(frmAddStage.BsonDocumentList);
             FillStagesTreeview();
         }
     }
     catch (Exception ex)
     {
         Utility.ExceptionDeal(ex);
     }
 }
Пример #23
0
        /// <summary>
        ///     修改用户(完全替换)
        /// </summary>
        /// <param name="user"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static CommandResult updateUser(MongoUserEx user, MongoDatabase db)
        {
            var mongoCmd = new CommandDocument {
                { "updateUser", user.Username }
            };

            mongoCmd.Add("pwd", user.Password);
            var roles = new BsonArray();

            roles.AddRange(user.Roles.Select(x => x.AsBsonValue()));
            mongoCmd.Add("roles", roles);
            if (user.customData != null)
            {
                mongoCmd.Add("customData", user.customData);
            }
            return(ExecuteMongoDBCommand(mongoCmd, db));
        }
Пример #24
0
        public BsonDocument ToBson()
        {
            // Standard values
            BsonDocument doc = new BsonDocument
            {
                { "name", this.NAME },
                { "username", this.USERNAME },
                { "time_start", this.TIMESTART },
                { "time_end", this.TIMEEND },
            };

            var hash = HashParameters();

            foreach (var entry in hash)
            {
                if (entry.Value.Count > 1)
                {
                    var array = new BsonArray();
                    array.AddRange(entry.Value);

                    doc.Add(new BsonElement(entry.Key, array));
                }
                else if (entry.Value.Count == 1)
                {
                    int intValue;
                    if (int.TryParse(entry.Value[0], out intValue))
                    {
                        doc.Add(entry.Key, intValue);
                    }
                    else
                    {
                        DateTime dt;
                        if (DateTime.TryParse(entry.Value[0], out dt))
                        {
                            doc.Add(entry.Key, dt);
                        }
                        else
                        {
                            doc.Add(entry.Key, entry.Value[0]);
                        }
                    }
                }
            }

            return doc;
        }
Пример #25
0
        public BsonDocument CreateFromEditModel(dynamic model, bool fromAPI = false)
        {
            if (model.GetType().FullName == "System.Dynamic.ExpandoObject")
            {
                return(((ExpandoObject)model).ToBsonDocument());
            }
            var doc = new BsonDocument();

            PropertyInfo[] members = model.GetType().GetProperties();
            foreach (var propertyInfo in members)
            {
                if (propertyInfo.GetCustomAttributes(typeof(IgnoreAuditAttribute), false).Any())
                {
                    continue;
                }
                var propertyValue = propertyInfo.GetValue(model);

                if (propertyValue == null)
                {
                    continue;
                }

                //if ((propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)) || propertyInfo.PropertyType.IsArray) || IsCollectionType(propertyValue, propertyInfo))
                if (propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>) || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList <>) || propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List <>)) || propertyInfo.PropertyType.IsArray)
                {
                    var items = new BsonArray();
                    items.AddRange(ListProperty(propertyValue, fromAPI));
                    doc.Add(new BsonElement(propertyInfo.Name, items));
                }
                else if (propertyValue.GetType().FullName == "System.Dynamic.ExpandoObject")
                {
                    doc.Add(((ExpandoObject)propertyValue).ToBsonDocument());
                }
                else
                {
                    doc.Add(ProcessPropertyInfo(propertyInfo, propertyValue, fromAPI));
                }
            }
            return(doc);
        }
Пример #26
0
        /// <summary>
        /// 处理文档(key转小写)
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="projectFields"></param>
        /// <returns></returns>
        static BsonArray HandleDocs(BsonArray docs, string projectFields)
        {
            BsonArray newDoc = new BsonArray();

            foreach (var doc in docs)
            {
                if (doc.IsBsonArray)
                {
                    newDoc.Add(HandleDocs(doc.AsBsonArray, projectFields));
                }
                else if (doc.IsBsonDocument)
                {
                    newDoc.Add(HandleDoc(doc.AsBsonDocument, projectFields));
                }
                else
                {
                    newDoc.AddRange(docs);
                    break;
                }
            }

            return(newDoc);
        }
Пример #27
0
        public static BsonDocument ToMatchDocument(this MatchDefinition source)
        {
            var result = new BsonDocument();
            var matchFilterElements = new List<BsonElement>();
            source.Filters.Where(x=>x.AvailableFilterValues.Any(y=>y.Active)).ToList().ForEach(f =>
            {
                var colDoc = new BsonDocument();
                var selectedValues = new BsonArray();
                var selectedFilterValues = f.AvailableFilterValues.Where(x=>x.Active).Select(x => x.Value).Select(x => new BsonString(x)).ToList();
                selectedValues.AddRange(selectedFilterValues);
                //var itemE
                var itemElm = new BsonElement("$in", selectedValues);
                colDoc.Add(itemElm);
                var colElm = new BsonElement(f.Column.ColumnName, colDoc);
                matchFilterElements.Add(colElm);
            });
            var elementsDoc = new BsonDocument();
            elementsDoc.AddRange(matchFilterElements);

            var matchElement = new BsonElement("$match", elementsDoc);
            result.Add(matchElement);
            return result;
        }
        public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag)
        {
            var jobGraph = database.GetCollection <BsonDocument>(storageOptions.Prefix + ".jobGraph");

            var counters    = jobGraph.Find(new BsonDocument("_t", "CounterDto")).ToList();
            var idsToRemove = new BsonArray();

            foreach (var countersByKey in counters.GroupBy(c => c["Key"].AsString))
            {
                var key             = countersByKey.Key;
                var groupedCounters = countersByKey.ToList();

                // if only one, nothing to do, continue...
                if (groupedCounters.Count == 1)
                {
                    continue;
                }

                // if all have the same value take the newest
                var allSameValue = groupedCounters.Select(c => Convert.ToInt32(c["Value"])).Distinct().Count() == 1;
                if (allSameValue)
                {
                    var newestObjectId = groupedCounters.Select(c => c["_id"].AsObjectId).Max();
                    idsToRemove.AddRange(groupedCounters.Where(c => c["_id"].AsObjectId != newestObjectId).Select(c => c["_id"]));
                    continue;
                }

                // if more with different values delete all with value = '1' and sum the rest, most likely there have been
                // created a new counterDto, which will have been counted instead of the aggregated one.
                idsToRemove.AddRange(groupedCounters.Where(c => Convert.ToInt32(c["Value"]) == 1).Select(c => c["_id"]));

                // verify there is only one counter left. if more, sum the results and put in a new document,
                // delete the existing
                groupedCounters.RemoveAll(c => idsToRemove.Contains(c["_id"].AsObjectId));

                if (groupedCounters.Count <= 1)
                {
                    continue;
                }

                var sum = groupedCounters.Sum(c =>
                {
                    var value = c["Value"];
                    return(value.IsInt32 ? value.AsInt32 : value.AsInt64);
                });

                var expireAt = groupedCounters.Any(c => c.Contains("ExpireAt") && c["ExpireAt"] != BsonNull.Value)
                    ? (BsonValue)groupedCounters.Select(c => c["ExpireAt"].ToUniversalTime()).Max()
                    : BsonNull.Value;

                var counterToInsert = new BsonDocument
                {
                    ["Key"]      = key,
                    ["Value"]    = sum,
                    ["_id"]      = ObjectId.GenerateNewId(),
                    ["ExpireAt"] = expireAt,
                    ["_t"]       = new BsonArray(new[] { "BaseJobDto", "ExpiringJobDto", "KeyJobDto", "CounterDto" })
                };
                jobGraph.InsertOne(counterToInsert);
                idsToRemove.AddRange(groupedCounters.Select(c => c["_id"]));
            }

            if (!idsToRemove.Any())
            {
                return(true);
            }

            jobGraph.DeleteMany(new BsonDocument("_id", new BsonDocument("$in", idsToRemove)));
            return(true);
        }
 public void TestAddRangeObjectIdNull()
 {
     var array = new BsonArray();
     var values = (ObjectId[])null;
     array.AddRange(values);
     Assert.AreEqual(0, array.Count);
 }
Пример #30
0
        private void CombineDocs(ref BsonDocument aggregateDoc, BsonDocument bsonDoc)
        {
            var elements = aggregateDoc.Elements.ToList();

            foreach (BsonElement el in bsonDoc.Elements)
            {
                // BsonElement currentEl = aggregateDoc.GetElement(el.Name);

                object boxedCurrentEl = (object)elements.Find(e => e.Name == el.Name);

                if (el.Value.IsBsonDocument)
                {
                    bool         shouldAdd = true;
                    BsonDocument subDoc;

                    if (((BsonElement)boxedCurrentEl).Value == null)
                    {
                        subDoc = new BsonDocument(false);
                    }
                    else
                    {
                        if (((BsonElement)boxedCurrentEl).Value.IsBsonNull || !((BsonElement)boxedCurrentEl).Value.IsBsonDocument ||
                            ((BsonElement)boxedCurrentEl).Value.AsBsonDocument.ElementCount == 0)
                        {
                            aggregateDoc.RemoveElement(((BsonElement)boxedCurrentEl));
                            subDoc = new BsonDocument(false);
                        }
                        else
                        {
                            subDoc    = ((BsonElement)boxedCurrentEl).Value.AsBsonDocument;
                            shouldAdd = false;
                        }
                    }

                    CombineDocs(ref subDoc, el.Value.AsBsonDocument);
                    if (shouldAdd)
                    {
                        aggregateDoc.Add(new BsonElement(el.Name, subDoc));
                    }
                }
                else if (el.Value.IsBsonArray)
                {
                    BsonArray subArray;

                    if (((BsonElement)boxedCurrentEl).Value == null)
                    { // This element doesn't exist in the aggregate document yet.
                        subArray = CombineArray(el.Value.AsBsonArray);
                        aggregateDoc.Add(new BsonElement(el.Name, subArray));
                    }
                    else
                    {
                        if (((BsonElement)boxedCurrentEl).Value.IsBsonNull || !((BsonElement)boxedCurrentEl).Value.IsBsonArray ||
                            ((BsonElement)boxedCurrentEl).Value.AsBsonArray.Count == 0)
                        { // This element does exist in the aggregate document but is no good.
                            aggregateDoc.RemoveElement(((BsonElement)boxedCurrentEl));
                            subArray = CombineArray(el.Value.AsBsonArray);
                            aggregateDoc.Add(new BsonElement(el.Name, subArray));
                        }
                        else
                        { // The array already exists in the aggregate document.
                            var newBsonArray = el.Value.AsBsonArray;
                            if (newBsonArray.Count > 0)
                            {
                                var preCombinedArray = new BsonArray(((BsonElement)boxedCurrentEl).Value.AsBsonArray);
                                preCombinedArray.AddRange(newBsonArray);
                                var combinedArray = CombineArray(preCombinedArray);
                                //boxedCurrentEl.SetValue(combinedArray);
                                BsonElementValueProperty.SetValue(boxedCurrentEl, combinedArray);
                                //currentEl = new BsonElement(currentEl.Name, combinedArray);
                            }
                        }
                    }
                }
                else
                {
                    if (((BsonElement)boxedCurrentEl).Value != null)
                    {
                        if (((BsonElement)boxedCurrentEl).Value.IsBsonNull)
                        {
                            //currentEl.SetValue(el.Value.Clone());
                            BsonElementValueProperty.SetValue(boxedCurrentEl, el.Value.Clone());
                            //var test = ((BsonElement) boxedCurrentEl).Value;
                            //currentEl = new BsonElement(currentEl.Name ?? "", BsonNull.Value);
                        }
                        else if (IsTypeGreater(((BsonElement)boxedCurrentEl).Value, el.Value))
                        {
                            //currentEl.SetValue(el.Value.Clone());
                            BsonElementValueProperty.SetValue(boxedCurrentEl, el.Value.Clone());
                            //currentEl = new BsonElement(currentEl.Name, el.Value.Clone());
                        }
                    }
                    else
                    {
                        aggregateDoc.Add(el.Clone());
                    }
                }
            }
        }
 public void TestAddRangeIEnumerableNull()
 {
     var array = new BsonArray();
     var values = (object[])null;
     array.AddRange(values);
     Assert.AreEqual(0, array.Count);
 }
Пример #32
0
 public void TestAddRangeStringNull()
 {
     var array = new BsonArray();
     var values = (string[])null;
     Assert.Throws<ArgumentNullException>(() => { array.AddRange(values); });
 }
Пример #33
0
 public void TestAddRangeIEnumerableNull()
 {
     var array = new BsonArray();
     var values = (object[])null;
     Assert.Throws<ArgumentNullException>(() => { array.AddRange(values); });
 }
Пример #34
0
        public async Task <JsonResult> GetPlaces(Double latitude, Double longitude, String searchText, String tags = "", Int32 maxDistance = Int32.MaxValue, Int32 tipology = 0)
        {
            try
            {
                if (String.IsNullOrEmpty(searchText))
                {
                    searchText = String.Empty;
                }
                BsonArray location = new BsonArray();
                location.AddRange(new Double[] { longitude, latitude });
                var reviews = _database.GetCollection <Review>("reviews");
                var places  = _database.GetCollection <ReadPlace>("places");


                var builder       = Builders <BsonDocument> .Filter;
                var postGeoFilter = builder.Empty;

                if (!String.IsNullOrEmpty(searchText))
                {
                    postGeoFilter = postGeoFilter & builder.Regex("name", "/" + searchText + "/i") | builder.Regex("menu.dishName", "/" + searchText + "/i");
                }

                if (tipology != 0)
                {
                    postGeoFilter = postGeoFilter & builder.BitsAllSet("menu.tipology", tipology);
                }

                if (!String.IsNullOrEmpty(tags))
                {
                    var tagArray = tags.Split(',');
                    postGeoFilter = postGeoFilter & builder.In("tags", tagArray);
                }

                var docs = await places.Aggregate().AppendStage <BsonDocument>(new BsonDocument()
                {
                    { "$geoNear", new BsonDocument()
                      {
                          { "near", new BsonDocument()
                            {
                                { "type", "Point" },
                                { "coordinates", new BsonArray(new Double[] { longitude, latitude }) }
                            } },
                          { "distanceField", "dist.calculated" },
                          { "spherical", true },
                          { "maxDistance", maxDistance * 1000 },
                      } }
                })
                           .Match(postGeoFilter) // filtro menu & nome del posto
                           .Lookup <BsonDocument, Review, BsonDocument>(reviews, x => x["_id"], y => y.PlaceId, z => z["reviews"])
                           .Unwind(x => x["reviews"], new AggregateUnwindOptions <BsonDocument>()
                {
                    PreserveNullAndEmptyArrays = true
                })
                           .Group(new BsonDocument() // Espande l'array di reviews e tira fuori nReviews e rating
                {
                    { "_id", new BsonDocument()
                      {
                          { "_id", "$_id" },
                          { "name", "$name" },
                          { "distance", "$dist.calculated" },
                          { "phoneNumber", "$phoneNumber" },
                          { "address", "$address" },
                          { "description", "$description" },
                          { "website", "$website" },
                          { "gallery", "$gallery" },
                          { "type", "$type" },
                          { "location", "$location" }
                      } },
                    { "nReviews", new BsonDocument()
                      {
                          { "$sum", 1 }
                      } },
                    { "rating", new BsonDocument()
                      {
                          { "$avg", "$reviews.rating" }
                      } }
                })
                           .Project(new BsonDocument()
                {
                    { "_id", "$_id._id" },
                    { "name", "$_id.name" },
                    { "phoneNumber", "$_id.phoneNumber" },
                    { "address", "$_id.address" },
                    { "website", "$_id.website" },
                    { "description", "$_id.description" },
                    { "nReviews", "$nReviews" },
                    { "type", "$_id.type" },
                    { "gallery", "$_id.gallery" },
                    { "rating", "$rating" },
                    { "distance", "$_id.distance" },
                    { "location", "$_id.location" }
                })
                           .SortBy <BsonDocument>(x => x["distance"]) //Forse sono gia ordinati
                           .As <ReadPlace>()

                           .ToListAsync();

                return(Json(docs.ToJson(jsonWriterSettings)));
            }
            catch (Exception ex)
            {
                return(Json(ex.RaiseException()));
            }
        }
Пример #35
0
 /// <summary>
 ///     修改用户(完全替换)
 /// </summary>
 /// <param name="user"></param>
 /// <param name="db"></param>
 /// <returns></returns>
 public static CommandResult updateUser(MongoUserEx user, MongoDatabase db)
 {
     var mongoCmd = new CommandDocument { { "updateUser", user.Username } };
     mongoCmd.Add("pwd", user.Password);
     var roles = new BsonArray();
     roles.AddRange(user.Roles.Select(x => x.AsBsonValue()));
     mongoCmd.Add("roles", roles);
     if (user.customData != null)
     {
         mongoCmd.Add("customData", user.customData);
     }
     return ExecuteMongoDBCommand(mongoCmd, db);
 }
        /// <summary>
        /// Finds the list of users that match the criteria.
        /// </summary>
        /// <param name="filter">Filters the results to only users that match.</param>
        /// <param name="tablesorterMetadata">The tablesorter metadata.</param>
        /// <returns>
        /// The list of users that match the criteria.
        /// </returns>
        protected override UserList DoFindUsers(UserSearchCriteria filter, TablesorterMetadata tablesorterMetadata = null)
        {
            MongoCollection<BsonDocument> collection = this.database.GetCollection(iApplyDb.UserAccess._COLLECTION_NAME);

            QueryDocument outerQuery = new QueryDocument();
            List<IMongoQuery> orQueries = new List<IMongoQuery>();

            if (filter.OrganisationIds != null && filter.OrganisationIds.Any())
            {
                orQueries.AddRange(filter.OrganisationIds.Select(organisationId => Query.Exists(string.Format("{0}.{1}", iApplyDb.UserAccess.ORGANISATIONS, organisationId))));
            }

            if (filter.IncludeNoOrganisationUsers)
            {
                orQueries.Add(Query.NotExists(iApplyDb.UserAccess.ORGANISATIONS));
                orQueries.Add(Query.EQ(iApplyDb.UserAccess.ORGANISATIONS, new BsonDocument()));
            }

            if (!filter.IncludeServiceUsers)
            {
                outerQuery.AddRange(Query.NE(iApplyDb.UserAccess.ACCOUNT_TYPE, new BsonString(AccountType.Service.ToString())).ToBsonDocument());
            }

            if (filter.RoleIds != null && filter.RoleIds.Any())
            {
                orQueries.AddRange(filter.RoleIds.Select(roleId => Query.Exists(string.Format("{0}.{1}", iApplyDb.UserAccess.ROLES, roleId))));
            }

            IMongoQuery subQuery;
            if (orQueries.Count > 0)
            {
                subQuery = Query.Or(orQueries);
                outerQuery.AddRange(subQuery.ToBsonDocument());
            }

            if (filter.UserIds != null && filter.UserIds.Any())
            {
                BsonArray bsonUserIds = new BsonArray();
                bsonUserIds.AddRange(filter.UserIds.Select(u => new BsonObjectId(new ObjectId(u))));
                subQuery = Query.In(iApplyDb.UserAccess._ID, bsonUserIds);
                outerQuery.AddRange(subQuery.ToBsonDocument());
            }

            if (filter.Usernames != null && filter.Usernames.Any())
            {
                BsonArray bsonUserNames = new BsonArray();
                bsonUserNames.AddRange(filter.Usernames.Select(u => new BsonString(u)));
                subQuery = Query.In(iApplyDb.UserAccess.USERNAME, bsonUserNames);
                outerQuery.AddRange(subQuery.ToBsonDocument());
            }

            if (filter.ExternalIds != null && filter.ExternalIds.Any())
            {
                BsonArray bsonExternalIds = new BsonArray();
                bsonExternalIds.AddRange(filter.ExternalIds.Select(u => new BsonString(u)));
                subQuery = Query.In(iApplyDb.UserAccess.EXTERNAL_ID, bsonExternalIds);
                outerQuery.AddRange(subQuery.ToBsonDocument());
            }

            if (tablesorterMetadata != null && tablesorterMetadata.SearchFilters != null)
            {
                for (int i = 0; i < tablesorterMetadata.SearchFilters.Length; i++)
                {
                    var fieldName = tablesorterMetadata.HeaderList[i];
                    var searchTerm = tablesorterMetadata.SearchFilters[i];

                    if (string.IsNullOrWhiteSpace(fieldName) || string.IsNullOrWhiteSpace(searchTerm))
                    {
                        continue;
                    }

                    subQuery = Query.EQ(fieldName, new BsonRegularExpression(searchTerm.Trim(), "i"));
                    outerQuery.AddRange(subQuery.ToBsonDocument());
                }
            }

            MongoCursor<BsonDocument> documents = collection.Find(outerQuery);
            if (tablesorterMetadata != null)
            {
                tablesorterMetadata.TotalRows = Convert.ToInt32(collection.Count(outerQuery));
                documents.SetSkip(tablesorterMetadata.PageSize * tablesorterMetadata.PageIndex).SetLimit(tablesorterMetadata.PageSize);

                if (tablesorterMetadata.SortOrder != null)
                {
                    SortByBuilder newSortByBuilder = new SortByBuilder();
                    foreach (int[] sortCriteria in tablesorterMetadata.SortOrder)
                    {
                        var columnNum = sortCriteria[0];
                        var sortOrder = sortCriteria[1];
                        if (sortOrder == 1)
                        {
                            newSortByBuilder.Descending(tablesorterMetadata.HeaderList[columnNum]);
                        }
                        else
                        {
                            newSortByBuilder.Ascending(tablesorterMetadata.HeaderList[columnNum]);
                        }
                    }

                    documents.SetSortOrder(newSortByBuilder);
                }
            }

            UserList users = BsonConverter.ConvertToObjectViaJson<UserList>(documents);
            return users;
        }
Пример #37
0
 /// <summary>
 ///     添加自定义角色
 /// </summary>
 public static CommandResult createRole(MongoDatabase mongoDb, Role role)
 {
     var mongoCmd = new CommandDocument("createRole", role.Rolename);
     var privileges = new BsonArray();
     privileges.AddRange(role.Privileges.Select(x => x.AsBsonDocument()));
     mongoCmd.Add("privileges", privileges);
     var roles = new BsonArray();
     roles.AddRange(role.Roles.Select(x => x.AsBsonValue()));
     mongoCmd.Add("roles", roles);
     return ExecuteMongoDBCommand(mongoCmd, mongoDb);
 }
Пример #38
0
 /// <summary>
 ///     GetActionArray
 /// </summary>
 /// <param name="actionList"></param>
 /// <returns></returns>
 public static BsonArray GetActionArray(List<string> actionList)
 {
     var result = new BsonArray();
     result.AddRange(actionList);
     return result;
 }