Esempio n. 1
0
        public async Task <PagintedList <Country> > GetCountriesAsync(CountryResourceParameters parameters)
        {
            var query = context.Countries.AsQueryable();

            if (!string.IsNullOrEmpty(parameters.EnglishName))
            {
                var englishName = parameters.EnglishName.Trim().ToLowerInvariant();
                query = query.Where(a => a.EnglishName.ToLowerInvariant() == englishName);
            }
            if (!string.IsNullOrEmpty(parameters.ChineseName))
            {
                //var chineseName = parameters.ChineseName.Trim().ToLowerInvariant();
                query = query.Where(a => a.ChineseName.Equals(parameters.ChineseName));
            }

            //query = query.ApplySort(parameters.OrderBy, new CountryMappingProperty());
            query = query.ApplySort(parameters.OrderBy, propertyMappingContainer.Resolve <CountryResource, Country>());
            var count = await query.CountAsync();

            var list = await query
                       .Skip(parameters.PageIndex *parameters.PageSize)
                       .Take(parameters.PageSize)
                       .ToListAsync();

            return(new PagintedList <Country>(parameters.PageSize, parameters.PageIndex, count, list));
        }
        public async Task <PaginatedList <Country> > GetCountriesAsync(CountryResourceParameters parameters)
        {
            var query = _myContext.Countries.AsQueryable();

            if (!string.IsNullOrEmpty(parameters.EnglishName))
            {
                var englishNameClause = parameters.EnglishName.Trim().ToLowerInvariant();
                query = query.Where(x => x.EnglishName.ToLowerInvariant() == englishNameClause);
            }

            if (!string.IsNullOrEmpty(parameters.ChineseName))
            {
                var chineseNameClause = parameters.ChineseName.Trim().ToLowerInvariant();
                query = query.Where(x => x.ChineseName.ToLowerInvariant() == chineseNameClause);
            }

            query = query.ApplySort(parameters.OrderBy, _propertyMappingContainer.Resolve <CountryResource, Country>());

            var count = await query.CountAsync();

            var items = await query
                        .Skip(parameters.PageSize *parameters.PageIndex)
                        .Take(parameters.PageSize).ToListAsync();

            return(new PaginatedList <Country>(parameters.PageIndex, parameters.PageSize, count, items));
        }
Esempio n. 3
0
        private IEnumerable <LinkResource> CreateLinksForCountries(CountryResourceParameters countryResourceParameters,
                                                                   bool hasPrevious, bool hasNext)
        {
            var links = new List <LinkResource>
            {
                new LinkResource(
                    CreateCountryUri(countryResourceParameters, PaginationResourceUriType.CurrentPage),
                    "self", "GET")
            };

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

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

            return(links);
        }
        //首先我们需要从参数(query string参数)传进来pageIndex和pageSize,还要赋默认值,以防止API的消费者没有设置pageIndex和pageSize;由于pageSize的值是由API的消费者来定的,所以应该在后端设定一个最大值,以免API的消费者设定一个很大的值
        //public async Task<IActionResult> Get([FromQuery] int pageIndex =0, int pageSize = 10)
        public async Task <IActionResult> GetCountries(CountryResourceParameters countryResourceParameters)
        {
            var pagedList = await _countryRepository.GetCountriesAsync(countryResourceParameters);

            var countryResources = _mapper.Map <List <CountryResource> >(pagedList);

            var previousPageLink = pagedList.HasPrevious ?
                                   CreateCountryUri(countryResourceParameters, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = pagedList.HasNext ?
                               CreateCountryUri(countryResourceParameters, PaginationResourceUriType.NextPage) : null;


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

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta));

            return(Ok(countryResources));
        }
Esempio n. 5
0
        public async Task <IActionResult> Get(CountryResourceParameters parameters,
                                              [FromHeader(Name = "Accept")] string mediaType)
        {
            var countries = await countryRepository.GetCountriesAsync(parameters);

            var countryResource = mapper.Map <List <CountryResource> >(countries);

            if (mediaType == "application/vnd.mycompany.heatoas+json")
            {
                var meta = new
                {
                    countries.TotalItemsCount,
                    countries.PaginationBase.PageIndex,
                    countries.PaginationBase.PageSize,
                    countries.PageCount,
                };
                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta));

                var links                   = CreateCountriesLinks(parameters, countries.HasPrevious, countries.HasNext);
                var shapedResource          = countryResource.ToDynamicIEnumerable(parameters.Fields);
                var shapedResourceWithLinks = shapedResource.Select(country =>
                {
                    var countryDit   = country as IDictionary <string, object>;
                    var countryLinks = CreateCountryLinks((Guid)countryDit["Id"], parameters.Fields);
                    countryDit.Add("links", countryLinks);
                    return(countryDit);
                });
                var linkedCountries = new
                {
                    value = shapedResourceWithLinks,
                    links,
                };
                return(Ok(linkedCountries));
            }
            else
            {
                var perviousPagelink = countries.HasPrevious ?
                                       CreateCountryUri(parameters, PaginationResourceUriType.PreviousPage):null;

                var nextPagelink = countries.HasNext ?
                                   CreateCountryUri(parameters, PaginationResourceUriType.NextPage) : null;

                var meta = new
                {
                    countries.TotalItemsCount,
                    countries.PaginationBase.PageIndex,
                    countries.PaginationBase.PageSize,
                    countries.PageCount,
                    perviousPagelink,
                    nextPagelink
                };
                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta));
                return(Ok(countryResource.ToDynamicIEnumerable(parameters.Fields)));
            }
        }
        //需要确保的是要在迭代发生之前,使用Skip()和Take()以及Where()
        public async Task <PaginatedList <Country> > GetCountriesAsync(CountryResourceParameters parameters)
        {
            //             return await _myContext.Countries
            //                 .OrderBy(x => x.Id)
            //                 .Skip(parameters.PageSize * parameters.PageIndex)
            //                 .Take(parameters.PageSize)
            //                 .ToListAsync();

            var query = _myContext.Countries.OrderBy(x => x.Id);

            var count = await query.CountAsync();

            var items = await query
                        .Skip(parameters.PageSize *parameters.PageIndex)
                        .Take(parameters.PageSize).ToListAsync();

            return(new PaginatedList <Country>(parameters.PageIndex, parameters.PageSize, count, items));
        }
Esempio n. 7
0
        private string CreateCountryUri(CountryResourceParameters parameters, PaginationResourceUriType uriType)
        {
            switch (uriType)
            {
            case PaginationResourceUriType.PreviousPage:
                var previousParameters = new
                {
                    pageIndex   = parameters.PageIndex - 1,
                    pageSize    = parameters.PageSize,
                    orderBy     = parameters.OrderBy,
                    fields      = parameters.Fields,
                    chineseName = parameters.ChineseName,
                    englishName = parameters.EnglishName
                };
                return(_urlHelper.Link("GetCountries", previousParameters));

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

            default:
            case PaginationResourceUriType.CurrentPage:
                var currentParameters = new
                {
                    pageIndex   = parameters.PageIndex,
                    pageSize    = parameters.PageSize,
                    orderBy     = parameters.OrderBy,
                    fields      = parameters.Fields,
                    chineseName = parameters.ChineseName,
                    englishName = parameters.EnglishName
                };
                return(_urlHelper.Link("GetCountries", currentParameters));
            }
        }
Esempio n. 8
0
        private string CreateCountriesResourceUri(CountryResourceParameters countryResourceParameters, ResourceUriType type)
        {
            switch (type)
            {
            case ResourceUriType.PreviousPage:
                return(_urlHelper.Link("GetCountries",
                                       new
                {
                    fields = countryResourceParameters.Fields,
                    orderBy = countryResourceParameters.OrderBy,
                    searchQuery = countryResourceParameters.SearchQuery,
                    name = countryResourceParameters.Name,
                    pageNumber = countryResourceParameters.PageNumber - 1,
                    pageSize = countryResourceParameters.PageSize
                }));

            case ResourceUriType.NextPage:
                return(_urlHelper.Link("GetCountries",
                                       new
                {
                    fields = countryResourceParameters.Fields,
                    orderBy = countryResourceParameters.OrderBy,
                    searchQuery = countryResourceParameters.SearchQuery,
                    name = countryResourceParameters.Name,
                    pageNumber = countryResourceParameters.PageNumber + 1,
                    pageSize = countryResourceParameters.PageSize
                }));

            default:
                return(_urlHelper.Link("GetCountries",
                                       new
                {
                    fields = countryResourceParameters.Fields,
                    orderBy = countryResourceParameters.OrderBy,
                    searchQuery = countryResourceParameters.SearchQuery,
                    name = countryResourceParameters.Name,
                    pageNumber = countryResourceParameters.PageNumber,
                    pageSize = countryResourceParameters.PageSize
                }));
            }
        }
Esempio n. 9
0
        public IActionResult GetCountries(CountryResourceParameters countryResourceParameters)
        {
            if (!_propertyMappingService.ValidMappingExistsFor <CountryApiModel, Country>(countryResourceParameters.OrderBy))
            {
                return(BadRequest());
            }

            if (!_typeHelperService.TypeHasProperties <CountryApiModel>(countryResourceParameters.Fields))
            {
                return(BadRequest());
            }

            var countriesFromRepo = _countryRepository.GetCountries(countryResourceParameters);

            var previousPageLink = countriesFromRepo.HasPrevious
                ? CreateCountriesResourceUri(countryResourceParameters, ResourceUriType.PreviousPage)
                : null;

            var nextPageLink = countriesFromRepo.HasNext
                ? CreateCountriesResourceUri(countryResourceParameters, ResourceUriType.NextPage)
                : null;

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

            Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationMetadata));


            var countries = Mapper.Map <IEnumerable <CountryApiModel> >(countriesFromRepo);

            return(Ok(countries.ShapeData(countryResourceParameters.Fields)));
        }
Esempio n. 10
0
        public PagedList <Country> GetCountries(CountryResourceParameters countryResourceParameters)
        {
            //var collectionBeforePaging = _context.Countries
            //    .OrderBy(a => a.Name).AsQueryable();

            var collectionBeforePaging =
                _context.Countries.ApplySort(countryResourceParameters.OrderBy,
                                             _propertyMappingService.GetPropertyMapping <CountryApiModel, Country>());


            if (!string.IsNullOrEmpty(countryResourceParameters.Deleted.ToString()))
            {
                var genreForWhereClause = countryResourceParameters.Deleted;
                collectionBeforePaging =
                    collectionBeforePaging.Where(a => (a.DeleteDate == null) != genreForWhereClause);
            }


            if (!string.IsNullOrEmpty(countryResourceParameters.Name))
            {
                var genreForWhereClause = countryResourceParameters.Name.Trim().ToLowerInvariant();
                collectionBeforePaging =
                    collectionBeforePaging.Where(a => a.Name.ToLowerInvariant() == genreForWhereClause);
            }

            if (!string.IsNullOrEmpty(countryResourceParameters.SearchQuery))
            {
                var searchQueryForWhereClause = countryResourceParameters.SearchQuery.Trim().ToLowerInvariant();

                collectionBeforePaging =
                    collectionBeforePaging.Where(a => a.Name.ToLowerInvariant().Contains(searchQueryForWhereClause));
            }

            return(PagedList <Country> .Create(collectionBeforePaging,
                                               countryResourceParameters.PageNumber,
                                               countryResourceParameters.PageSize));
        }
Esempio n. 11
0
        public async Task <IActionResult> GetCountries(CountryResourceParameters countryResourceParameters,
                                                       [FromHeader(Name = "Accept")] string mediaType)
        {
            foreach (var claim in User.Claims)
            {
                Console.WriteLine(claim.Type + ", " + claim.Value);
            }

            if (!_propertyMappingContainer.ValidMappingExistsFor <CountryResource, Country>(countryResourceParameters.OrderBy))
            {
                return(BadRequest("Can't find the fields for sorting."));
            }

            if (!_typeHelperService.TypeHasProperties <CountryResource>(countryResourceParameters.Fields))
            {
                return(BadRequest("Can't find the fields on Resource."));
            }

            var pagedList = await _countryRepository.GetCountriesAsync(countryResourceParameters);

            var countryResources = _mapper.Map <List <CountryResource> >(pagedList);

            if (mediaType == "application/vnd.solenovex.hateoas+json")
            {
                var meta = new
                {
                    pagedList.TotalItemsCount,
                    pagedList.PaginationBase.PageSize,
                    pagedList.PaginationBase.PageIndex,
                    pagedList.PageCount
                };

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

                var links                    = CreateLinksForCountries(countryResourceParameters, pagedList.HasPrevious, pagedList.HasNext);
                var shapedResources          = countryResources.ToDynamicIEnumerable(countryResourceParameters.Fields);
                var shapedResourcesWithLinks = shapedResources.Select(country =>
                {
                    var countryDict  = country as IDictionary <string, object>;
                    var countryLinks = CreateLinksForCountry((int)countryDict["Id"], countryResourceParameters.Fields);
                    countryDict.Add("links", countryLinks);
                    return(countryDict);
                });
                var linkedCountries = new
                {
                    value = shapedResourcesWithLinks,
                    links
                };

                return(Ok(linkedCountries));
            }
            else
            {
                var previousPageLink = pagedList.HasPrevious ?
                                       CreateCountryUri(countryResourceParameters,
                                                        PaginationResourceUriType.PreviousPage) : null;

                var nextPageLink = pagedList.HasNext ?
                                   CreateCountryUri(countryResourceParameters,
                                                    PaginationResourceUriType.NextPage) : null;

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

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

                return(Ok(countryResources.ToDynamicIEnumerable(countryResourceParameters.Fields)));
            }
        }