Esempio n. 1
0
        public async Task <PaginatedList <Post> > GetAllPostsAsync(PostParameters postParameters)
        {
            var query = _myContext.Posts.AsQueryable();

            //根据传入的标题来进行过滤
            if (!string.IsNullOrEmpty(postParameters.Title))
            {
                var title = postParameters.Title.ToLowerInvariant();//转换为小写
                query = query.Where(x => x.Title.ToLowerInvariant() == title);
            }
            //搜索的话,则是根据传入的条件模糊查询,这里就先不做

            //排序应用
            query = query.ApplySort(postParameters.OrderBy, _propertyMappingContainer.Resolve <PostResource, Post>());
            var count = await query.CountAsync();

            var data = await query
                                                      //跳过多少条返回(如PageIndex=0,跳过0条,返回第一页;PageIndex=1,跳过1*PageSize条,则返回第二页)
                       .Skip(postParameters.PageIndex *postParameters.PageSize)
                       .Take(postParameters.PageSize) //每页返回多少个
                       .ToListAsync();

            return(new PaginatedList <Post>(postParameters.PageIndex, postParameters.PageSize, count, data));
            //return await _myContext.Posts.ToListAsync();
        }
Esempio n. 2
0
        private string CreatePostUri(PostParameters parameters, PaginationResourceUriType uriType)
        {
            switch (uriType)
            {
            case PaginationResourceUriType.PreviousPage:
                var previousParameters = new
                {
                    pageIndex = parameters.PageIndex - 1,
                    pageSize  = parameters.PageSize,
                    orderBy   = parameters.OrderBy,
                    fields    = parameters.Fields
                };
                return(_urlHelper.Link("GetPosts", previousParameters));

            case PaginationResourceUriType.NextPage:
                var nextParameters = new
                {
                    pageIndex = parameters.PageIndex + 1,
                    pageSize  = parameters.PageSize,
                    orderBy   = parameters.OrderBy,
                    fields    = parameters.Fields
                };
                return(_urlHelper.Link("GetPosts", nextParameters));

            default:
                var currentParameters = new
                {
                    pageIndex = parameters.PageIndex,
                    pageSize  = parameters.PageSize,
                    orderBy   = parameters.OrderBy,
                    fields    = parameters.Fields
                };
                return(_urlHelper.Link("GetPosts", currentParameters));
            }
        }
Esempio n. 3
0
        public IActionResult Get(string userId, PostParameters parameters)
        {
            var posts = _repository.Pagination <PostsByUserDto>(parameters, c => c.UserId == userId);

            if (posts == null)
            {
                return(NotFound());
            }

            string previousPage = posts.HasPrevious
                ? CreateResourceUri(parameters, ResourceUriType.PreviousPage, userId)
                : null;

            string nextPage = posts.HasNext
                ? CreateResourceUri(parameters, ResourceUriType.NextPage, userId)
                : null;

            var paginationMetadata = new
            {
                totalCount       = posts.TotalCount,
                pageSize         = posts.PageSize,
                currentPage      = posts.CurrentPage,
                totalPages       = posts.TotalPages,
                previousPageLink = previousPage,
                nextPageLink     = nextPage
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata));
            var vm = Mapper.Map <List <PostsByUserDto> >(posts);

            return(Ok(vm.ShapeData(parameters.Fields)));
        }
Esempio n. 4
0
        //public async Task<IEnumerable<Post>> GetAllPostsAsync()
        //{
        //    return await _myContext.Posts.ToListAsync();//查出所有数据
        //}

        #endregion

        public async Task <PaginateList <Post> > GetAllPostsAsync(PostParameters postParameters)
        {
            //先排序
            //var query = _myContext.Posts.OrderBy(x => x.Id);

            //过滤
            var query = _myContext.Posts.AsQueryable();

            if (!string.IsNullOrEmpty(postParameters.Title))
            {
                var title = postParameters.Title.ToLowerInvariant();
                query = query.Where(x => x.Title.ToLowerInvariant() == title);
            }
            //容器


            //query = query.OrderBy(x => x.Id);
            // https://localhost:5001/api/posts?pageIndex=0&pageSize=10&orderBy=id 20desc 可以用倒序了 贼难
            query = query.ApplySort(postParameters.OrderBy, _propertyMappingContainer.Resolve <PostResource, Post>());

            var count = await query.CountAsync();

            var data = await query
                       .Skip(postParameters.PageIndex *postParameters.PageSize)
                       .Take(postParameters.PageSize)
                       .ToListAsync();

            return(new PaginateList <Post>(postParameters.PageIndex, postParameters.PageSize, count, data));
        }
Esempio n. 5
0
        public async Task <IActionResult> Get(PostParameters postParameters)
        {
            // Get the certain page's Post list and map it to PostResource list
            var postList = await postRepository.GetAllPostAsync(postParameters);

            var postResources = mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);

            // Get prev and next page uri by current page parameters
            var previousPageLink = postList.HasPrevious ?
                                   CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;
            var NextPageLink = postList.HasNext?
                               CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

            // Save page turning meta info
            var meta = new
            {
                pageSize        = postList.PageSize,
                pageIndex       = postList.PageIndex,
                totalItemsCount = postList.TotalItemsCount,
                pageCount       = postList.PageCount,
                previousPageLink,
                NextPageLink
            };

            // Add meta info to response header
            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta));

            return(Ok(postResources));
        }
        public async Task <IActionResult> GetPostsForUser([FromBody] PostParameters postParameters)
        {
            var posts = await _repository.Post.GetPostsForUserAsync(postParameters, false);

            //Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(posts.MetaData));

            // TODO: fix this problem with CurrentUserLiked inside Likes, so you can use automapper
            //var postsDto = _mapper.Map<IEnumerable<PostDto>>(posts);
            var postsDto   = new List <PostDto>();
            var userFromDb = await _userManager.GetUserAsync(this.User);

            foreach (var post in posts)
            {
                var postDto = new PostDto()
                {
                    Id          = post.Id,
                    Body        = post.Body,
                    CreatedById = post.CreatedById,
                    Title       = post.Title,
                    Likes       = new LikeDto()
                    {
                        LikesCount       = post.Likes.Count,
                        CurrentUserLiked = post.Likes.Any(l => l.LikerId == userFromDb.Id)
                    },
                    Photos = _mapper.Map <IEnumerable <PhotoDto> >(post.Photos)
                };

                IEnumerable <CommentDto> commentsDto = _mapper.Map <IEnumerable <CommentDto> >(post.Comments);
                postDto.Comments = commentsDto;

                postsDto.Add(postDto);
            }

            return(Ok(postsDto));
        }
        public async Task<IActionResult> Get(PostParameters postParameters, [FromHeader(Name = "Accept")] string mediaType)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor<PostViewModel, Post>(postParameters.OrderBy))
                return BadRequest("Can't finds fields for sorting");

            if (!_typeHelperService.TypeHasProperties<PostViewModel>(postParameters.Fields))
                return BadRequest("Fields not exist");
            var postlist = await _postRepository.GetAllPostsAsync(postParameters);

            var postViewModels = _mapper.Map<IEnumerable<Post>, IEnumerable<PostViewModel>>(postlist);

            var shapedPostViewModels = postViewModels.ToDynamicIEnumerable(postParameters.Fields);

            var previousPageLink = postlist.HasPrevious ? CreatePostUri(postParameters, PaginationResourceUriType.PerviousPage) : null;
            var nextPageLink = postlist.HasNext ? CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                postlist.PageSize,
                postlist.PageIndex,
                postlist.TotalItemsCount,
                postlist.PageCount,
                previousPageLink,
                nextPageLink
            };
            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return Ok(shapedPostViewModels);


        }
Esempio n. 8
0
        public async Task <IActionResult> GetHateoas(PostParameters postParameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not exist."));
            }
            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            var postResource       = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);
            var shapedPostResource = postResource.ToDynamicIEnumerable(postParameters.Fields);
            var proviousPage       = postList.HasPrevious ? CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;
            var nextPage           = postList.HasNext ? CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;
            var meta = new
            {
                PageIndex       = postList.PageIndex,
                PageSize        = postList.PageSize,
                TotalItemsCount = postList.TotalItemsCount,
                PageCount       = postList.Count,
                proviousPage,
                nextPage
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
            return(Ok(shapedPostResource));
        }
Esempio n. 9
0
        public async Task <IActionResult> Get(PostParameters postParameters)
        {
            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            var postResources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);

            var previousPageLink = postList.HasPrevious ?
                                   CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLik = postList.HasNext ?
                              CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                Pagesize       = postList.PageSize,
                PageIndex      = postList.PageIndex,
                TotalItemCount = postList.TotalItemsCount,
                PageCount      = postList.PageCount,
                previousPageLink,
                nextPageLik
            };

            _logger.LogInformation("Get All Posts");

            //添加头  页面信息
            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            //throw new Exception("Error!!!!");
            //_logger.LogInformation(_configuration["Key1"]);

            return(Ok(postResources));
        }
Esempio n. 10
0
        private IEnumerable <LinkResource> CreateLinksForPosts(PostParameters postResourceParameters,
                                                               bool hasPrevious, bool hasNext)
        {
            var links = new List <LinkResource>
            {
                new LinkResource(
                    CreatePostUri(postResourceParameters, PaginationResourceUriType.CurrentPage),
                    "self", "GET")
            };

            if (hasPrevious)
            {
                links.Add(
                    new LinkResource(
                        CreatePostUri(postResourceParameters, PaginationResourceUriType.PreviousPage),
                        "previous_page", "GET"));
            }

            if (hasNext)
            {
                links.Add(
                    new LinkResource(
                        CreatePostUri(postResourceParameters, PaginationResourceUriType.NextPage),
                        "next_page", "GET"));
            }

            return(links);
        }
Esempio n. 11
0
        public async Task <IActionResult> GetHateoas(PostParameters parameters)
        {
            //验证排序属性映射是否存在
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostDTO, Post>(parameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }

            //验证Filed是否存在
            if (!_typeHelperService.TypeHasProperties <PostDTO>(parameters.Fields))
            {
                return(BadRequest("Filed not exits"));
            }


            var posts = await _postRepository.GetPostsAsync(parameters);

            var postDto = _mapper.Map <IEnumerable <Post>, IEnumerable <PostDTO> >(posts);

            var shapePostDTO     = postDto.ToDynamicIEnumerable(parameters.Fields);
            var previousPageLink = posts.HasPrevious ?
                                   CreatePostUri(parameters, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = posts.HasNext ?
                               CreatePostUri(parameters, PaginationResourceUriType.NextPage) : null;


            var shapedWithLinks = shapePostDTO.Select(x =>
            {
                var dict      = x as IDictionary <string, object>;
                var postLinks = CreateLinksForPost((int)dict["Id"], parameters.Fields);
                dict.Add("links", postLinks);
                return(dict);
            });
            var links  = CreateLinksForPosts(parameters, posts.HasPrevious, posts.HasNext);
            var result = new
            {
                value = shapedWithLinks,
                links
            };


            var meta = new
            {
                PageSize       = posts.PageSize,
                PageIndex      = posts.PageIndex,
                TotalItemCount = posts.TotalItemsCount,
                PageCount      = posts.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(Ok(result));
        }
Esempio n. 12
0
 public async Task <IEnumerable <Post> > GetPostsForUserAsync(PostParameters postParameters, bool trackChanges)
 {
     return(await FindAll(trackChanges)
            .SearchUserPosts(postParameters.CreatedByUserId)
            .SortPosts(postParameters.OrderBy)
            .Include(p => p.Likes)
            .Include(p => p.Comments)
            .ThenInclude(c => c.CommentedBy)
            .Include(c => c.Photos)
            .ToListAsync());
 }
Esempio n. 13
0
        //
        // POST form
        //

        public RestResponse <string> PostForm(string endpoint,
                                              PostParameters parameters,
                                              HttpHeaders headers = null,
                                              HttpCookies cookies = null)
        {
            return(MakeRequest <string>(endpoint,
                                        HttpMethod.Post,
                                        ToFormContent(parameters),
                                        headers ?? NoHeaders,
                                        cookies ?? NoCookies,
                                        MaxRedirects));
        }
Esempio n. 14
0
        public async Task <PaginatedList <Post> > GetAllPostAsync(PostParameters postParameters)
        {
            var query = myContext.Posts.OrderBy(x => x.Id);

            var count = await query.CountAsync();

            var data = await query
                       .Skip(postParameters.PageIndex *postParameters.PageSize)
                       .Take(postParameters.PageSize)
                       .ToListAsync();

            return(new PaginatedList <Post>(postParameters.PageIndex, postParameters.PageSize, count, data));
        }
Esempio n. 15
0
        public virtual void ConvertFile(Stream inStream, string fileName, Stream outStream, bool compressRequest)
        {
            byte[] data = new byte[inStream.Length];
            inStream.Read(data, 0, data.Length);
            inStream.Close();

            /*            if (!PostParameters.ContainsKey("OutputFileName"))
            *               SetOutputFileName(Path.GetFileNameWithoutExtension(fileName));*/

            PostParameters.Add("file", new FormUpload.FileParameter(data, fileName, Helpers.GetMimeType(fileName)));

            Convert(PostParameters, outStream, compressRequest);
        }
Esempio n. 16
0
 public RestResponse <string, T> PostForm <T>(string endpoint,
                                              PostParameters parameters,
                                              HttpHeaders headers = null,
                                              HttpCookies cookies = null)
 {
     return(MakeRequest <string, T>(endpoint,
                                    HttpMethod.Post,
                                    ToFormContent(parameters),
                                    headers ?? NoHeaders,
                                    cookies ?? NoCookies,
                                    MaxRedirects,
                                    JsonConvert.DeserializeObject <T>));
 }
Esempio n. 17
0
        public async Task <IActionResult> GetHateoas(PostParameters postParameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not exist."));
            }

            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            var postResources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);

            // 资源塑形
            var shapedPostResources = postResources.ToDynamicIEnumerable(postParameters.Fields);

            var shapedWithLinks = shapedPostResources.Select(x =>
            {
                var dict      = x as IDictionary <string, object>;
                var postlinks = CreateLinksForPost((int)dict["Id"], postParameters.Fields);
                dict.Add("links", postlinks);
                return(dict);
            });

            var links = CreateLinksForPosts(postParameters, postList.HasPrevious, postList.HasNext);

            var result = new
            {
                value = shapedWithLinks,
                links
            };

            var meta = new
            {
                postList.PageSize,
                postList.PageIndex,
                postList.TotalItemsCount,
                postList.PageCount,
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(Ok(result));
        }
Esempio n. 18
0
 public void Restore()
 {
     if (PostParameters != null && PostParameters["file"] != null)
     {
         new BatchJob(this, delegate() {
             Batch.Status      = "Loading new data";
             UploadedFile data = PostParameters.As <UploadedFile>("file");
             Database.Logging  = LogLevel.None;
             Database.BeginTransaction();
             JObject d           = data.Content.JsonTo <JObject>();
             List <Table> tables = Database.TableNames.Select(n => Database.TableFor(n)).ToList();
             Batch.Records       = tables.Count * 4;
             foreach (Table t in tables)
             {
                 if (d[t.Name] != null)
                 {
                     Batch.Records += ((JArray)d[t.Name]).Count;
                 }
             }
             Batch.Status            = "Deleting existing data";
             TableList orderedTables = new TableList(tables);
             foreach (Table t in orderedTables)
             {
                 Database.Execute("DELETE FROM " + t.Name);
                 Batch.Record += 4;
             }
             Database.Logging = LogLevel.None;
             foreach (Table t in orderedTables.Reverse <Table>())
             {
                 if (d[t.Name] != null)
                 {
                     Batch.Status = "Restoring " + t.Name + " data";
                     foreach (JObject record in (JArray)d[t.Name])
                     {
                         Database.Insert(t.Name, record);
                         Batch.Record++;
                     }
                 }
             }
             Batch.Status = "Checking database version";
             Database.Upgrade();
             Database.Commit();
             Batch.Status = "Compacting database";
             Database.Clean();
             _settings    = Database.QueryOne <Settings>("SELECT * FROM Settings");
             Batch.Status = Message = "Database restored successfully";
         });
     }
 }
Esempio n. 19
0
 public void YearEnd()
 {
     if (Request.HttpMethod == "POST")
     {
         bool clear = PostParameters.AsInt("clear") > 0;
         Database.BeginTransaction();
         foreach (Full_Member m in Database.Query <Full_Member>(@"SELECT * FROM Full_Member WHERE Hidden <> 1").ToList())
         {
             m.AmountDue     = m.AnnualSubscription + (clear ? 0 : m.AmountDue);
             m.PaymentAmount = Math.Round(m.AmountDue / (m.NumberOfPayments < 1 ? 1 : m.NumberOfPayments), 2);
             Database.Update(m, true);
         }
         Database.Commit();
         Redirect("/members");
     }
 }
Esempio n. 20
0
        public object Post([FromBody] PostParameters param)
        {
            if (param == null || string.IsNullOrEmpty(param.Signal))
            {
                return(BadRequest("You must post a signal!"));
            }

            var s = new Signal()
            {
                Content = param.Signal
            };

            db.Signal.Insert(s);

            return(Ok(s.Id));
        }
Esempio n. 21
0
        public async Task <IActionResult> Get(PostParameters postParameters)
        {
            //检查按照某个字段排序时该字段是否存在
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("OrderBy is not exist"));
            }
            //检查资源塑性字段是否存在
            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields is not exist"));
            }
            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            //转化实体
            var postResources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> > (postList);

            //资源塑性
            var shapedPostResources = postResources.ToDynamicIEnumerable(postParameters.Fields);

            //前一页
            var previousPageLink = postList.HasPrevious ?
                                   CreatePostUri(postParameters,
                                                 PaginationResourceUriType.PreviousPage) : null;
            //后一页
            var nextPageLink = postList.HasNext ?
                               CreatePostUri(postParameters,
                                             PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                PageSize        = postList.PageSize,
                PageIndex       = postList.PageIndex,
                TotalItemsCount = postList.TotalItemsCount,
                PageCount       = postList.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver() //转化数据不管大小写,首字母都转化为小写
            }));


            return(Ok(shapedPostResources));
        }
Esempio n. 22
0
        [RequestHeaderMatchingMediaType("Accept", new[] { "application/json" })] //新增媒体类型参数,在Header里是叫做Accept的key
        public async Task <IActionResult> Get(PostParameters postParameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                //如果需要查询排序的字段不存在,则返回400错误
                return(BadRequest("Can't finds fields for sorting"));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                //如果需要查询的字段不存在,则返回400错误
                return(BadRequest("Fields not exist."));
            }

            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            //var a =postList.FirstOrDefault();
            var postResource = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);
            //如果Headers里面有注明输出的媒体类型为application/vnd.cgzl.hateoas+json 则走下面,带links的

            var previousPageLink = postList.HasPrevious ?
                                   CreatePostUri(postParameters,
                                                 PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = postList.HasNext ?
                               CreatePostUri(postParameters,
                                             PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                postList.TotalItemsCount,
                postList.PageSize,
                postList.PageIndex,
                postList.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(Ok(postResource.ToDynamicIEnumerable(postParameters.Fields)));
        }
Esempio n. 23
0
        public async Task <PaginatedList <Post> > GetAllPostsAsync(PostParameters postParameters)
        {
            var query = myContext.Post.AsQueryable();

            if (!string.IsNullOrEmpty(postParameters.Title))
            {
                var title = postParameters.Title;//不知道为什么转大小写后会报错 所以没有ToUpperInvariant
                query = query.Where(x => x.Title.Contains(title));
            }
            query = query.ApplySort(postParameters.OrderBy, propertyMappingContainer.Resolve <PostDTO, Post>());
            //query = query.OrderBy(x => x.Id);

            var count = await query.CountAsync();

            var data = await query.Skip(postParameters.PageIndex *postParameters.PageSize).Take(postParameters.PageSize).ToListAsync();

            return(new PaginatedList <Post>(postParameters.PageIndex, postParameters.PageSize, count, data));
        }
Esempio n. 24
0
        public async Task <ActionResult> Get(PostParameters parameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(parameters.OrderBy))
            {
                return(BadRequest("OrderBy not exist "));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(parameters.Fields))
            {
                return(BadRequest("fields not exist "));
            }

            var postsList = await _postRepository.GetAllPostsAsync(parameters);

            //  _logger.LogError(12,"get post all/.....");
            var resources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postsList);

            //动态查询字段
            var result = resources.ToDynamicIEnumerable(parameters.Fields);

            //创建上一页
            var previousPagelink = postsList.HasPrevious ? CreatePostUri(parameters, PaginationResourceUriType.PreviousPage) : null;
            //创建下一页
            var nextPagelink = postsList.HasNext ? CreatePostUri(parameters, PaginationResourceUriType.NextPage) : null;


            var meta = new
            {
                postsList.PageSize,
                postsList.PageIndex,
                postsList.TotalItemCount,
                postsList.PageCount,
                previousPagelink,
                nextPagelink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                //大写转小写
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
            return(Ok(result));
        }
Esempio n. 25
0
        public async Task <PaginatedList <Post> > GetPostsAsync(PostParameters parameters)
        {
            var Query = _myContext.Posts.AsQueryable();

            if (!string.IsNullOrEmpty(parameters.Title))
            {
                var title = parameters.Title.ToLowerInvariant();
                Query = Query.Where(x => x.Title.ToLowerInvariant().Contains(title));
            }
            Query = Query.ApplySort(parameters.OrderBy, _propertyMappingContainer.Resolve <PostDTO, Post>());

            // Query = Query.OrderBy(x => x.Id);

            var count = await Query.CountAsync();

            var data = await Query.Skip(parameters.PageIndex *parameters.PageSize).Take(parameters.PageSize).ToListAsync();

            return(new PaginatedList <Post>(parameters.PageIndex, parameters.PageSize, count, data));
        }
Esempio n. 26
0
        public void FilterAndSearchQuery(PostParameters parameters, ref IQueryable <Post> result)
        {
            if (!parameters.Search.IsNullEmptyOrWhiteSpace())
            {
                result = result.Where(user =>
                                      user.Title.Contains(parameters.Search) ||
                                      user.Body.Contains(parameters.Search));
            }

            if (!parameters.Title.IsNullEmptyOrWhiteSpace())
            {
                result = result.Where(Post => Post.Title == parameters.Title).AsQueryable();
            }

            if (!parameters.Body.IsNullEmptyOrWhiteSpace())
            {
                result = result.Where(Post => Post.Body.Contains(parameters.Body)).AsQueryable();
            }
        }
Esempio n. 27
0
        public async Task <PaginatedList <Post> > GetAllPostsAsync(PostParameters postParameters)
        {
            var query = _myContext.Posts.AsQueryable();

            if (!string.IsNullOrWhiteSpace(postParameters.Title))
            {
                var title = postParameters.Title.ToLowerInvariant();
                query = query.Where(x => x.Title.ToLowerInvariant() == title);
            }

            query = query.ApplySort(postParameters.OrderBy, _propertyMappingContainer.Resolve <PostResource, Post>());

            var count = await query.CountAsync();

            var data = await query.Skip(postParameters.PageIndex *postParameters.PageSize)
                       .Take(postParameters.PageSize)
                       .ToListAsync();

            return(new PaginatedList <Post>(postParameters.PageIndex, postParameters.PageSize, count, data));
        }
Esempio n. 28
0
        public async Task <PaginatedList <Post> > GetAllPostsAsync(PostParameters parameters)
        {
            var query = _myContext.Posts.AsQueryable();

            if (!string.IsNullOrEmpty(parameters.Title))
            {
                var whereStr = parameters.Title.ToLower();
                query = query.Where(x => x.Title.ToLower().Contains(parameters.Title));
            }

            query = query.ApplySort(parameters.OrderBy, _propertyMappingContainer.Resolve <Resources.PostResource, Post>());
            var totalCount = query.Count();

            var data = await query
                       .Skip((parameters.PageIndex - 1) *parameters.PageSize)
                       .Take(parameters.PageSize)
                       .ToListAsync();

            return(new PaginatedList <Post>(parameters.PageSize, parameters.PageIndex, totalCount, data));
        }
Esempio n. 29
0
        public override void AnalyzeRequestResponse(string page)
        {
            base.AnalyzeRequestResponse(page);

            // Loop through language options in the page to see the one's requested
            for (int i = 0; i < 100; i++)
            {
                string languageValue = Utilities.ReadInputFieldById(page, string.Format("ctl00_PlaceHolderMain_MUISettings_AlternateLanguagesSection_ctlSelectLanguages_CblAlternateLanguages_{0}", i));
                // leave when empty as we've iterated all supported languages
                if (languageValue.Length == 0)
                {
                    break;
                }

                // If we found one, set that as checked
                if (this.Languages.Contains(int.Parse(languageValue)))
                {
                    PostParameters.Add(string.Format("ctl00$PlaceHolderMain$MUISettings$AlternateLanguagesSection$ctlSelectLanguages$CblAlternateLanguages${0}", i), languageValue);
                }
            }
        }
Esempio n. 30
0
        public async Task <PaginatedList <Post> > GetPostsAsync(PostParameters postParameters)
        {
            var query = _myContext.Posts.AsQueryable();

            // 客户端有可能根据标题 Title 查询
            if (!string.IsNullOrEmpty(postParameters.Title))
            {
                string title = postParameters.Title.ToLowerInvariant();
                query = query.Where(p => p.Title.Contains(title));
            }
            //query = query.OrderBy(p => p.Id);
            query = query.ApplySort(postParameters.OrderBy, _propertyMappingContainer.Resolve <PostResource, Post>());

            int count = await query.CountAsync();

            var data = await query
                       .Skip((postParameters.PageIndex - 1) *postParameters.PageSize)
                       .Take(postParameters.PageSize).ToListAsync();

            return(new PaginatedList <Post>(postParameters.PageIndex, postParameters.PageSize, count, data));
        }