private IEnumerable <LinkDto> CreateLinksForCollections(WebApiSearchQueryParamsDto <TDto> resourceParameters, bool hasNext, bool hasPrevious)
        {
            var links = new List <LinkDto>();

            // self
            links.Add(
                new LinkDto(CreateResourceUri(resourceParameters,
                                              ResourceUriType.Current)
                            , "self", HttpMethod.Get.Method));

            links.Add(
                new LinkDto(Url.Action("Create", Url.ActionContext.RouteData.Values["controller"].ToString(),
                                       null, Url.ActionContext.HttpContext.Request.Scheme),
                            "add",
                            HttpMethod.Post.Method));

            if (hasNext)
            {
                links.Add(
                    new LinkDto(CreateResourceUri(resourceParameters,
                                                  ResourceUriType.NextPage),
                                "nextPage", HttpMethod.Get.Method));
            }

            if (hasPrevious)
            {
                links.Add(
                    new LinkDto(CreateResourceUri(resourceParameters,
                                                  ResourceUriType.PreviousPage),
                                "previousPage", HttpMethod.Get.Method));
            }

            return(links);
        }
        private List <LinkDto> CreateLinksForCollectionProperty(string collection, WebApiSearchQueryParamsDto resourceParameters, bool hasNext, bool hasPrevious)
        {
            var links = new List <LinkDto>();

            // self
            links.Add(
                new LinkDto(CreateCollectionPropertyResourceUri(collection, resourceParameters,
                                                                ResourceUriType.Current)
                            , "self", HttpMethod.Get.Method));

            //Todo if want to allow Add to collection property
            //  links.Add(
            // new LinkDto(Url.Action("Create", Url.ActionContext.RouteData.Values["controller"].ToString(),
            //null, Url.ActionContext.HttpContext.Request.Scheme),
            // "add",
            // "POST"));

            if (hasNext)
            {
                links.Add(
                    new LinkDto(CreateCollectionPropertyResourceUri(collection, resourceParameters,
                                                                    ResourceUriType.NextPage),
                                "nextPage", HttpMethod.Get.Method));
            }

            if (hasPrevious)
            {
                links.Add(
                    new LinkDto(CreateCollectionPropertyResourceUri(collection, resourceParameters,
                                                                    ResourceUriType.PreviousPage),
                                "previousPage", HttpMethod.Get.Method));
            }

            return(links);
        }
        private string CreateResourceUri(WebApiSearchQueryParamsDto <TDto> resourceParameters, ResourceUriType type)
        {
            switch (type)
            {
            case ResourceUriType.PreviousPage:
                return(Request.GetEncodedUrl().Replace($"page={resourceParameters.Page}", $"page={resourceParameters.Page - 1}"));

            case ResourceUriType.NextPage:
                return(Request.GetEncodedUrl().Replace($"page={resourceParameters.Page}", $"page={resourceParameters.Page + 1}"));

            default:
                //https://stackoverflow.com/questions/30755827/getting-absolute-urls-using-asp-net-core
                return(Request.GetEncodedUrl());
            }
        }
        private string CreateCollectionPropertyResourceUri(string collection, WebApiSearchQueryParamsDto resourceParameters, ResourceUriType type)
        {
            switch (type)
            {
            case ResourceUriType.PreviousPage:
                return(Url.Action(nameof(BulkGetByIds),
                                  Url.ActionContext.RouteData.Values["controller"].ToString(),
                                  new
                {
                    collection = collection,
                    fields = resourceParameters.Fields,
                    page = resourceParameters.Page - 1,
                    pageSize = resourceParameters.PageSize
                },
                                  Url.ActionContext.HttpContext.Request.Scheme));

            case ResourceUriType.NextPage:
                return(Url.Action(nameof(BulkGetByIds),
                                  Url.ActionContext.RouteData.Values["controller"].ToString(),
                                  new
                {
                    collection = collection,
                    fields = resourceParameters.Fields,
                    page = resourceParameters.Page + 1,
                    pageSize = resourceParameters.PageSize
                },
                                  Url.ActionContext.HttpContext.Request.Scheme));

            default:
                return(Url.Action(nameof(BulkGetByIds),
                                  Url.ActionContext.RouteData.Values["controller"].ToString(),
                                  new
                {
                    collection = collection,
                    fields = resourceParameters.Fields,
                    page = resourceParameters.Page,
                    pageSize = resourceParameters.PageSize
                },
                                  Url.ActionContext.HttpContext.Request.Scheme));
            }
        }
Пример #5
0
        public virtual async Task <ActionResult> Index(int page = 1, int pageSize = 10, string orderBy = "Id desc", string search = "")
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var searchDto = new WebApiSearchQueryParamsDto()
                {
                    Page     = page,
                    PageSize = pageSize,
                    Search   = search,
                    OrderBy  = orderBy
                };

                var resp = await Service.SearchAsync(searchDto, cts.Token);

                var response = new WebApiPagedResponseDto <TDto>
                {
                    Page     = page,
                    PageSize = pageSize,
                    Records  = resp.pagingInfo.Records,
                    Rows     = resp.data.Value.ToList(),
                    OrderBy  = orderBy,
                    Search   = search
                };

                ViewBag.Search   = search;
                ViewBag.Page     = page;
                ViewBag.PageSize = pageSize;
                ViewBag.OrderBy  = orderBy;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;
                return(View("List", response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
        private async Task <ActionResult> List(WebApiSearchQueryParamsDto <TDto> resourceParameters)
        {
            if (string.IsNullOrEmpty(resourceParameters.OrderBy))
            {
                resourceParameters.OrderBy = "Id";
            }

            if (!UIHelper.ValidOrderByFor <TDto>(resourceParameters.OrderBy))
            {
                return(BadRequest(Messages.OrderByInvalid));
            }

            if (!UIHelper.ValidFieldsFor <TDto>(resourceParameters.Fields))
            {
                return(BadRequest(Messages.FieldsInvalid));
            }

            if (!UIHelper.ValidFilterFor <TDto>(HttpContext.Request.Query))
            {
                return(BadRequest(Messages.FiltersInvalid));
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var dataTask = Service.SearchAsync(cts.Token, resourceParameters.UserId, resourceParameters.Search, UIHelper.GetFilter <TDto>(HttpContext.Request.Query), resourceParameters.OrderBy, resourceParameters.Page, resourceParameters.PageSize, false);

            await TaskHelper.WhenAllOrException(cts, dataTask);

            var data = dataTask.Result;

            var paginationMetadata = new PagingInfoDto
            {
                Page             = resourceParameters.Page,
                PageSize         = resourceParameters.PageSize,
                Records          = data.TotalCount,
                PreviousPageLink = null,
                NextPageLink     = null
            };

            if (paginationMetadata.HasPrevious)
            {
                paginationMetadata.PreviousPageLink = CreateResourceUri(resourceParameters, ResourceUriType.PreviousPage);
            }

            if (paginationMetadata.HasNext)
            {
                paginationMetadata.NextPageLink = CreateResourceUri(resourceParameters, ResourceUriType.NextPage);
            }

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata).Replace(Environment.NewLine, ""));

            var links = CreateLinksForCollections(resourceParameters,
                                                  paginationMetadata.HasNext, paginationMetadata.HasPrevious);

            var shapedData = UIHelper.ShapeListData(data.ToList(), resourceParameters.Fields);

            var shapedDataWithLinks = shapedData.Select(dto =>
            {
                var dtoAsDictionary = dto as IDictionary <string, object>;
                var dtoLinks        = CreateLinks(
                    dtoAsDictionary["Id"].ToString(), resourceParameters.Fields);

                dtoAsDictionary.Add("links", dtoLinks);

                return(dtoAsDictionary);
            });

            var linkedCollectionResource = new
            {
                value = shapedDataWithLinks,
                links = links
            };

            return(Ok(linkedCollectionResource));
        }
        public virtual async Task <ActionResult <WebApiListResponseDto <TDto> > > Search([FromQuery] WebApiSearchQueryParamsDto <TDto> resourceParameters)
        {
            if (User.Claims.Where(c => c.Type == JwtClaimTypes.Scope && c.Value.EndsWith(ResourceCollectionsCore.CRUD.Operations.Read)).Count() == 0)
            {
                resourceParameters.UserId = UserId;
            }

            return(await List(resourceParameters));
        }
        public virtual async Task <IActionResult> GetByIdChildCollection(string id, string collection, WebApiSearchQueryParamsDto resourceParameters)
        {
            if (string.IsNullOrEmpty(resourceParameters.OrderBy))
            {
                resourceParameters.OrderBy = "Id";
            }


            //order by
            if (!UIHelper.ValidOrderByFor <TDto>(resourceParameters.OrderBy))
            {
                return(BadRequest(Messages.OrderByInvalid));
            }

            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(BadRequest(Messages.CollectionInvalid));
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(await GetCollectionItem(id, collection, resourceParameters.Fields));
            }

            var collectionItemType = RelationshipHelper.GetCollectionExpressionType(collection, typeof(TDto));

            //fields
            if (!UIHelper.ValidFieldsFor(collectionItemType, resourceParameters.Fields))
            {
                return(BadRequest(Messages.FieldsInvalid));
            }

            //filter
            if (!UIHelper.ValidFilterFor(collectionItemType, HttpContext.Request.Query))
            {
                return(BadRequest(Messages.FiltersInvalid));
            }

            var filter = UIHelper.GetFilter(collectionItemType, HttpContext.Request.Query);

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            var result = await Service.GetByIdWithPagedCollectionPropertyAsync(cts.Token, id, collection, resourceParameters.Search, filter, resourceParameters.OrderBy, resourceParameters.Page, resourceParameters.PageSize);

            IEnumerable <Object> list = ((IEnumerable <Object>)RelationshipHelper.GetCollectionExpressionData(collection, typeof(TDto), result.Dto));

            var paginationMetadata = new PagingInfoDto
            {
                Page             = resourceParameters.Page,
                PageSize         = resourceParameters.PageSize,
                Records          = result.TotalCount,
                PreviousPageLink = null,
                NextPageLink     = null
            };

            if (paginationMetadata.HasPrevious)
            {
                paginationMetadata.PreviousPageLink = CreateCollectionPropertyResourceUri(collection, resourceParameters, ResourceUriType.PreviousPage);
            }

            if (paginationMetadata.HasNext)
            {
                paginationMetadata.NextPageLink = CreateCollectionPropertyResourceUri(collection, resourceParameters, ResourceUriType.NextPage);
            }

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata).Replace(Environment.NewLine, ""));

            var links = CreateLinksForCollectionProperty(collection, resourceParameters, paginationMetadata.HasNext, paginationMetadata.HasPrevious);

            var shapedData = UIHelper.ShapeListData(list, collectionItemType, resourceParameters.Fields);

            var shapedDataWithLinks = shapedData.Select(collectionPropertyDtoItem =>
            {
                var collectionPropertyDtoItemAsDictionary = collectionPropertyDtoItem as IDictionary <string, object>;
                var collectionPropertyDtoItemLinks        = CreateLinksForCollectionItem(id, collection + "/" + collectionPropertyDtoItemAsDictionary["Id"].ToString(), resourceParameters.Fields);

                collectionPropertyDtoItemAsDictionary.Add("links", collectionPropertyDtoItem);

                return(collectionPropertyDtoItemAsDictionary);
            }).ToList();

            var linkedCollectionResource = new WebApiListResponseDto <IDictionary <string, object> >
            {
                Value = shapedDataWithLinks
                ,
                Links = links
            };

            return(Ok(linkedCollectionResource));
        }
Пример #9
0
 public virtual async Task <ActionResult <WebApiListResponseDto <TDto> > > Search([FromQuery] WebApiSearchQueryParamsDto <TDto> resourceParameters)
 {
     return(await List(resourceParameters));
 }
Пример #10
0
        public virtual async Task <ActionResult> Collection(string id, string collection, int page = 1, int pageSize = 10, string orderBy = "Id desc", string search = "")
        {
            if (!RelationshipHelper.IsValidCollectionExpression(collection, typeof(TDto)))
            {
                return(HandleReadException());
            }

            if (RelationshipHelper.IsCollectionExpressionCollectionItem(collection))
            {
                return(await CollectionItemDetails(id, collection));
            }

            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var searchDto = new WebApiSearchQueryParamsDto()
                {
                    Page     = page,
                    PageSize = pageSize,
                    Search   = search,
                    OrderBy  = orderBy
                };

                var resp = await Service.GetByIdChildCollectionAsync <dynamic>(id, collection, searchDto, cts.Token);

                var response = new WebApiPagedResponseDto <dynamic>
                {
                    Page     = page,
                    PageSize = pageSize,
                    Records  = resp.pagingInfo.Records,
                    Rows     = resp.data.Value.ToList(),
                    OrderBy  = orderBy,
                    Search   = search
                };

                ViewBag.Search   = search;
                ViewBag.Page     = page;
                ViewBag.PageSize = pageSize;
                ViewBag.OrderBy  = orderBy;

                ViewBag.Collection = collection;
                ViewBag.Id         = id;

                //For the time being collection properties are read only. DDD states that only the Aggregate Root should get updated.
                ViewBag.DisableCreate       = true;
                ViewBag.DisableEdit         = true;
                ViewBag.DisableDelete       = true;
                ViewBag.DisableSorting      = false;
                ViewBag.DisableEntityEvents = true;
                ViewBag.DisableSearch       = false;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;
                return(View("List", response));
            }
            catch
            {
                return(HandleReadException());
            }
        }
        public async Task <(WebApiListResponseDto <TReadDto> data, PagingInfoDto pagingInfo)> SearchAsync(WebApiSearchQueryParamsDto resourceParameters = null, CancellationToken cancellationToken = default)
        {
            var response = await client.GetWithQueryString($"{ResourceCollection}", resourceParameters);

            await response.EnsureSuccessStatusCodeAsync();

            return(await response.ContentAsTypeAsync <WebApiListResponseDto <TReadDto> >(), response.Headers.FindAndParsePagingInfo());
        }