Esempio n. 1
0
 public static FilterDefinition <TEntity> NotDeletedAndIdEq <TEntity>(this FilterDefinitionBuilder <TEntity> filter, string id)
     where TEntity : SoftDeletableMongoEntity
 => filter.And(filter.NotDeleted(), filter.IdEq(id));
Esempio n. 2
0
        public async Task <dynamic> Post([FromBody] TBody requestBody)
        {
            var id = this.GetCurrentUserId();

            DateTime creationDate = DateTime.UtcNow;

            var newUserTask = BindUser(requestBody, creationDate);

            var userCollection = MongoWrapper.Database.GetCollection <TEntity>(nameof(Models.User));

            var userFilterBuilder = new FilterDefinitionBuilder <TEntity>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(u => u._id, new ObjectId(id)),
                GeneralUtils.NotDeactivated(userFilterBuilder)
                                    );

            var oldUser = (await userCollection.FindAsync(userFilter)).SingleOrDefault();

            if (oldUser == null)
            {
                Logger.LogError("User with valid JWT id was not found in database! Id: {}", id);
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Seu usuário não foi encontrado!",
                });
            }

            var newUser = await newUserTask;

            var gridFsBucket = new GridFSBucket <ObjectId>(MongoWrapper.Database);

            await this.UploadPhoto(requestBody.Foto, gridFsBucket, newUser, creationDate);

            var userUpdate = await CreateUpdateDefinition(oldUser, newUser);

            if (oldUser.Email != oldUser.Email)
            {
                userUpdate = userUpdate.Set(u => u.EmailConfirmed, false);
            }

            var userUpdateTask = userCollection.UpdateOneAsync(userFilter, userUpdate);

            var postCollection = MongoWrapper.Database.GetCollection <Models.Post>(nameof(Models.Post));

            var postFilterBuilder = new FilterDefinitionBuilder <Models.Post>();
            var postFilter        = postFilterBuilder.And
                                    (
                postFilterBuilder.Eq(p => p.Poster._id, oldUser._id),
                GeneralUtils.NotDeactivated(postFilterBuilder)
                                    );
            var postUpdateBuilder = new UpdateDefinitionBuilder <Models.Post>();
            var postUpdate        = postUpdateBuilder.Set(p => p.Poster.Avatar, newUser.Avatar)
                                    .Set(p => p.Poster.FullName, newUser.FullName);

            var commentFilterBuilder     = new FilterDefinitionBuilder <Comment>();
            var commentFilter            = commentFilterBuilder.Eq(c => c.Commenter._id, oldUser._id);
            var postCommentFilterBuilder = new FilterDefinitionBuilder <Models.Post>();
            var postCommentFilter        = postFilterBuilder.And
                                           (
                GeneralUtils.NotDeactivated(postFilterBuilder),
                postCommentFilterBuilder.ElemMatch(p => p.Comments, commentFilter)
                                           );
            var postCommentUpdateBuilder = new UpdateDefinitionBuilder <Models.Post>();
            var postCommentUpdate        = postUpdateBuilder
                                           .Set(p => p.Comments[-1].Commenter.Avatar, newUser.Avatar)
                                           .Set(p => p.Comments[-1].Commenter.FullName, newUser.FullName);

            var postUpdateTask        = postCollection.UpdateManyAsync(postFilter, postUpdate);
            var postCommentUpdateTask = postCollection.UpdateManyAsync(postCommentFilter, postCommentUpdate);

            await userUpdateTask;
            await postUpdateTask;

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Usuário editado com sucesso!",
            });
        }
        public async Task <dynamic> Get(string token)
        {
            var tokenCollection = MongoWrapper.Database.GetCollection <ReferenceToken>(nameof(ReferenceToken));
            var userCollection  = MongoWrapper.Database.GetCollection <Models.User>(nameof(Models.User));

            var randomPasswordTask = GeneralUtils.GenerateRandomString(
                10,
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-".ToCharArray()
                );

            var currentTime = DateTime.UtcNow;

            var confirmationFilterBuilder = new FilterDefinitionBuilder <ReferenceToken>();
            var confirmationFilter        = confirmationFilterBuilder.And
                                            (
                confirmationFilterBuilder.Eq(conf => conf._id, token),
                confirmationFilterBuilder.Eq(conf => conf.TokenType, TokenType.PasswordRecovery),
                GeneralUtils.NotDeactivated(confirmationFilterBuilder)
                                            );

            var confirmationUpdateBuilder = new UpdateDefinitionBuilder <ReferenceToken>();
            var confirmationUpdate        = confirmationUpdateBuilder.Set(conf => conf.DeactivationDate, currentTime);

            var oldConfirmation = await tokenCollection.FindOneAndUpdateAsync(confirmationFilter, confirmationUpdate, new FindOneAndUpdateOptions <ReferenceToken>()
            {
                ReturnDocument = ReturnDocument.Before
            });

            if (oldConfirmation == null)
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody()
                {
                    Code = ResponseCode.NotFound,
                    Data = null,
                    Message = "O token especificado não existe ou já foi expirado!",
                    Success = false
                });
            }

            var userFilterBuilder = new FilterDefinitionBuilder <Models.User>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(user => user._id, oldConfirmation.UserId),
                GeneralUtils.NotDeactivated(userFilterBuilder)
                                    );

            var randomPassword      = await randomPasswordTask;
            var randomPassEncrypted = Encryption.Encrypt(randomPassword);

            var userUpdateBuilder = new UpdateDefinitionBuilder <Models.User>();
            var userUpdate        = userUpdateBuilder.Set(user => user.Password, randomPassEncrypted);

            await userCollection.UpdateOneAsync(userFilter, userUpdate);

            return(new ResponseBody()
            {
                Code = ResponseCode.GenericSuccess,
                Data = randomPassword,
                Message = "Uma nova senha foi gerada!",
                Success = true
            });
        }
Esempio n. 4
0
        [HttpGet]//获取一个类别下所有的资产名称和资产编码
        public List <List <string> > Get_ZC_NI(string Type, string Name = null, int n = 0)
        {
            try
            {
                List <string> key   = new List <string>();
                List <string> value = new List <string>();
                if (Name != null)
                {
                    M_Db_Operate m_Db_Operate = new M_Db_Operate();
                    var          collection   = m_Db_Operate.database.GetCollection <SJ_ZC_Model>("ZC_data");
                    FilterDefinitionBuilder <SJ_ZC_Model> builderFilters = Builders <SJ_ZC_Model> .Filter;
                    FilterDefinitionBuilder <SJ_SX_Model> builderFilter  = Builders <SJ_SX_Model> .Filter;
                    var filter = builderFilters.ElemMatch("ZC_SX", builderFilter.And(builderFilter.Eq("V", Name), builderFilter.Eq("mp", "0004")));
                    var result = collection.Find(filter).ToList();
                    var s      = from one in result
                                 from sx in one.ZC_SX
                                 where sx.mp == "0004"
                                 select sx.V;
                    List <string> sn = s.GroupBy(p => p).Select(g => g.First()).ToList();
                    s = from one in result
                        from sx in one.ZC_SX
                        where sx.mp == "0003"
                        select sx.V;
                    List <string> si = new List <string>();
                    if (Name != null)
                    {
                        si = s.Distinct().ToList();
                    }
                    List <List <string> > resu = new List <List <string> >()
                    {
                        sn, si
                    };
                    return(resu);
                }
                else
                {
                    M_Db_Operate m_Db_Operate = new M_Db_Operate();
                    var          collection   = m_Db_Operate.database.GetCollection <SJ_ZC_Model>("ZC_data");
                    FilterDefinitionBuilder <SJ_ZC_Model> builderFilters = Builders <SJ_ZC_Model> .Filter;
                    FilterDefinitionBuilder <SJ_SX_Model> builderFilter  = Builders <SJ_SX_Model> .Filter;
                    FilterDefinition <SJ_ZC_Model>        filter         = builderFilters.ElemMatch("ZC_SX", builderFilter.And(builderFilter.Eq("V", Type), builderFilter.Eq("mp", "0002")));
                    var result = collection.Find(filter).ToList();
                    var s      = from one in result
                                 from sx in one.ZC_SX
                                 where sx.mp == "0004"
                                 select sx.V;
                    List <string> sn = s.GroupBy(p => p).Select(g => g.First()).ToList();
                    s = from one in result
                        from sx in one.ZC_SX
                        where sx.mp == "0003"
                        select sx.V;
                    List <string> si = new List <string>();
                    if (Name != null)
                    {
                        si = s.Distinct().ToList();
                    }
                    List <List <string> > resu = new List <List <string> >()
                    {
                        sn, si
                    };
                    return(resu);
                }
                //M_Db_Operate m_Db_Operate = new M_Db_Operate();
                //var collection = m_Db_Operate.database.GetCollection<SJ_ZC_Model>("ZC_data");
                //FilterDefinitionBuilder<SJ_ZC_Model> builderFilter = Builders<SJ_ZC_Model>.Filter;
                ////约束条件
                //List<FilterDefinition<SJ_ZC_Model>> builderFilterss = new List<FilterDefinition<SJ_ZC_Model>>();
                //for (int i = 0; i < key.Count; i++)
                //    builderFilterss.Add(builderFilter.Eq(key[i], value[i]));
                //FilterDefinition<SJ_ZC_Model> filter = builderFilter.And(builderFilterss.ToArray());
                ////获取数据
                //var res = collection.Find(filter).Skip(n * 100).ToList();
                //var s = from one in res
                //         from sx in one.ZC_SX
                //         where sx.mp == "0004"
                //         select sx.V;
                //List<string> sn = s.GroupBy(p => p).Select(g => g.First()).ToList();
                //s = from one in res
                //    from sx in one.ZC_SX
                //    where sx.mp == "0003"
                //    select sx.V;
                //List<string> si = new List<string>();
                //if (Name != null)
                //    si = s.Distinct().ToList();
                //var res = m_Db_Operate.Inquire_Data(collection, key, value).Skip(1).Take(100).ToList();

                /*List<string> name = new List<string>();
                 * List<string> ID = new List<string>();
                 * for (int i = 0; i < res.Count; i++)
                 * {
                 *  for (int j = 0; j < res[i].ZC_SX.Count; j++)
                 *  {
                 *      if (res[i].ZC_SX[j].mp == "0004")
                 *          if (!name.Contains(res[i].ZC_SX[j].V))
                 *              name.Add(res[i].ZC_SX[j].V);
                 *      if(res[i].ZC_SX[j].mp == "0003")
                 *          ID.Add(res[i].ZC_SX[j].V);
                 *  }
                 * }*/
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Esempio n. 5
0
        private async Task <IEnumerable <T> > FetchEntities <T>
        (
            string metaPhrase,
            ProjectionDefinition <T> projection,
            IMongoCollection <T> collection,
            double daysTolerance,
            int limit,
            GeoJsonPoint <GeoJson3DGeographicCoordinates> targetPosition = null
        ) where T : IIdentifiable <ObjectId>, ILocatable, IMetaScored
        {
            var referenceDate = DateTime.UtcNow;

            var filterBuilder = new FilterDefinitionBuilder <T>();
            var filter        = filterBuilder.And
                                (
                filterBuilder.Gt
                (
                    post => post._id,
                    new ObjectId(referenceDate.Subtract(TimeSpan.FromDays(daysTolerance)), 0, 0, 0)
                ),
                filterBuilder.Or
                (
                    filterBuilder.Text(metaPhrase, new TextSearchOptions
            {
                CaseSensitive      = false,
                DiacriticSensitive = false,
            })
                    ,
                    filterBuilder.Exists(p => p._id)
                )
                                );

            var sortBuilder = new SortDefinitionBuilder <T>();
            var sort        = sortBuilder.Combine
                              (
                sortBuilder.MetaTextScore("metaScore"),
                sortBuilder.Descending(p => p._id)
                              );

            var cursor = await collection.FindAsync(filter, new FindOptions <T>
            {
                AllowPartialResults = true,
                Limit      = limit,
                Sort       = sort,
                Projection = projection
            });

            var enumerable = cursor.ToEnumerable();

            if (targetPosition != null)
            {
                enumerable = enumerable.OrderBy
                             (
                    item =>
                    item.Position.Coordinates.ToGeoCoordinate().GetDistanceTo(targetPosition.Coordinates.ToGeoCoordinate())
                    -
                    Math.Pow(item.MetaScore, 2)
                             );
            }

            return(enumerable);
        }
Esempio n. 6
0
        public Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            return(DoAndLog(nameof(WriteStateAsync), async() =>
            {
                var grainCollection = GetCollection(grainType);
                var grainKey = grainReference.ToKeyString();

                var grainData = serializer.Serialize(grainState);

                var etag = grainState.ETag;

                var newData = grainData.ToBson();
                var newETag = Guid.NewGuid().ToString();

                try
                {
                    await grainCollection.UpdateOneAsync(
                        Filter.And(
                            Filter.Eq(FieldId, grainKey),
                            Filter.Eq(FieldEtag, grainState.ETag)
                            ),
                        Update
                        .Set(FieldEtag, newETag)
                        .Set(FieldDoc, newData),
                        Upsert);
                }
                catch (MongoException ex)
                {
                    if (ex.IsDuplicateKey())
                    {
                        await ThrowForOtherEtag(grainCollection, grainKey, etag, ex);

                        var document = new BsonDocument
                        {
                            [FieldId] = grainKey,
                            [FieldEtag] = grainKey,
                            [FieldDoc] = newData
                        };

                        try
                        {
                            await grainCollection.ReplaceOneAsync(Filter.Eq(FieldId, grainKey), document, Upsert);
                        }
                        catch (MongoException ex2)
                        {
                            if (ex2.IsDuplicateKey())
                            {
                                await ThrowForOtherEtag(grainCollection, grainKey, etag, ex2);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        throw;
                    }
                }

                grainState.ETag = newETag;
            }));
        }
Esempio n. 7
0
 public override FilterDefinition <TObject> BuildFilter(FilterDefinitionBuilder <TObject> filterBuilder)
 => filterBuilder.And(Specifications.Select(s => s.BuildFilter(filterBuilder)).ToArray());
Esempio n. 8
0
        public override FilterDefinition <MongoContentEntity> Visit(BinaryOperatorNode nodeIn)
        {
            if (nodeIn.OperatorKind == BinaryOperatorKind.And)
            {
                return(Filter.And(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }

            if (nodeIn.OperatorKind == BinaryOperatorKind.Or)
            {
                return(Filter.Or(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }

            if (nodeIn.Left is SingleValueFunctionCallNode functionNode)
            {
                var regexFilter = Visit(functionNode);

                var value = BuildValue(nodeIn.Right);

                if (value is bool booleanRight)
                {
                    if ((nodeIn.OperatorKind == BinaryOperatorKind.Equal && !booleanRight) ||
                        (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual && booleanRight))
                    {
                        regexFilter = Filter.Not(regexFilter);
                    }

                    return(regexFilter);
                }
            }
            else
            {
                if (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual)
                {
                    var field = BuildFieldDefinition(nodeIn.Left);

                    return(Filter.Or(
                               Filter.Not(Filter.Exists(field)),
                               Filter.Ne(field, BuildValue(nodeIn.Right))));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.Equal)
                {
                    return(Filter.Eq(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.LessThan)
                {
                    return(Filter.Lt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.LessThanOrEqual)
                {
                    return(Filter.Lte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThan)
                {
                    return(Filter.Gt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual)
                {
                    return(Filter.Gte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }
            }

            throw new NotSupportedException();
        }
Esempio n. 9
0
 public IEnumerable <FlowReferenceItem> Get()
 {
     return(coll.Find(bf.And(bf.Eq(x => x.School, HttpContext.GetFlowLoginUserFromToken().School), bf.Eq(x => x.IsFlowRole, true))).Project(x => new FlowReferenceItem(x.Id, x.Name)).ToList());
 }