Exemple #1
0
        public void BuildNavigationLinks_BuildsNextLink_WhenSkipIsNotProvided()
        {
            // Arrange
            var url          = $"{_faker.Internet.UrlWithPath()}?{_faker.Lorem.Word()}={_faker.Lorem.Word()}";
            var expectedSkip = "skip=10";
            var expectedUrl  = $"{url}&{expectedSkip}";
            var uri          = new Uri(url);
            var pagedList    = new PagedListDto <string>
            {
                HasNextPage    = true,
                LastItemOnPage = 10
            };

            // Act
            pagedList.BuildNavigationLinks(uri);

            // Assert
            Assert.That(pagedList.Links, Is.Not.Null);
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNameSelf));
            Assert.That(pagedList.Links[ResourceBase.RelationNameSelf], Is.EqualTo(url));
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNameNext), Is.True);
            var nextLink = pagedList.Links[ResourceBase.RelationNameNext];

            Assert.That(nextLink, Is.Not.Null);
            Assert.That(nextLink.ToLower(), Is.EqualTo(expectedUrl));
        }
Exemple #2
0
        /// <summary>
        /// Fills navigation for the paged list with the hyperlinks: self, previous and next, when applicable.
        /// </summary>
        public static void BuildNavigationLinks <T>(this PagedListDto <T> pagedList, Uri currentUri)
        {
            pagedList.Links[ResourceBase.RelationNameSelf] = currentUri.AbsoluteUri;
            var        queryString = HttpUtility.ParseQueryString(currentUri.Query);
            SearchBase searchParam;
            var        skipParameterName = nameof(searchParam.Skip);

            if (pagedList.HasNextPage)
            {
                var nbElementsToSkip = pagedList.LastItemOnPage;
                queryString.Set(skipParameterName, nbElementsToSkip.ToString());
                var newUri = new UriBuilder(currentUri)
                {
                    Query = queryString.ToString()
                }.Uri;
                pagedList.Links[ResourceBase.RelationNameNext] = newUri.AbsoluteUri;
            }

            if (pagedList.HasPreviousPage)
            {
                var nbElementsToSkip = pagedList.FirstItemOnPage - 1 - pagedList.PageSize;
                queryString.Set(skipParameterName, nbElementsToSkip.ToString());
                var newUri = new UriBuilder(currentUri)
                {
                    Query = queryString.ToString()
                }.Uri;
                pagedList.Links[ResourceBase.RelationNamePrevious] = newUri.AbsoluteUri;
            }
        }
        public ActionResult <PagedListDto <ArticleWithIncludeDto> > GetList([FromQuery] ArticleQueryDto dto,
                                                                            [FromQuery] string include, [FromQuery] Paging paging)
        {
            PagedListDto <ArticleWithIncludeDto> list = _app.GetList(dto, include, paging);

            return(Ok(list));
        }
Exemple #4
0
        public void BuildNavigationLinks_BuildsPreviousLink_WhenPageHasPreviousPage()
        {
            // Arrange
            var urlPrefix   = $"{_faker.Internet.UrlWithPath()}?{_faker.Lorem.Word()}={_faker.Lorem.Word()}";
            var url         = $"{urlPrefix}&skip=10&limit=5";
            var expectedUrl = $"{urlPrefix}&skip=5&limit=5";
            var uri         = new Uri(url);
            var pagedList   = new PagedListDto <string>
            {
                HasPreviousPage = true,
                FirstItemOnPage = 11,
                PageSize        = 5
            };

            // Act
            pagedList.BuildNavigationLinks(uri);

            // Assert
            Assert.That(pagedList.Links, Is.Not.Null);
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNameSelf));
            Assert.That(pagedList.Links[ResourceBase.RelationNameSelf], Is.EqualTo(url));
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNamePrevious), Is.True);
            var previousLink = pagedList.Links[ResourceBase.RelationNamePrevious];

            Assert.That(previousLink, Is.Not.Null);
            Assert.That(previousLink.ToLower(), Is.EqualTo(expectedUrl));
        }
Exemple #5
0
        public static IPagedList <TResult> Select <T, TResult>(this IPagedList <T> query, Func <T, TResult> select)
            where T : class
            where TResult : class
        {
            var paged = new PagedListDto <TResult>(query.CurrentPage, query.TotalCount, query.List.Select(select).ToList(), query.PageSize);

            return(paged);
        }
        public async Task <IActionResult> GetFiltered([FromBody] UserFilterAdminDto filter)
        {
            // Check if valid user
            var currentUser = await _identityService.GetCurrentPersonIdentityAsync();

            if (currentUser == null)
            {
                return(BadRequest(new RequestMessageResponse()
                {
                    Success = false, Message = "Forbidden"
                }));
            }

            // Create pager
            PagingParams pager = new PagingParams();

            pager.PageNumber = filter.PageNumber;
            pager.PageSize   = filter.PageSize;

            // Get filtered list from dB
            var usersList = _userService.GetAllUsersPagedList(pager, filter.Email, filter.UserName, filter.Firstname, filter.Lastname);

            // Get roles
            var rolesList = await _userService.GetAllRolesAsync();

            // Map entitites to dto
            IList <UserSmallAdminDto> userSmallDtos = new List <UserSmallAdminDto>();

            foreach (var user in usersList.List)
            {
                UserSmallAdminDto smallModel = new UserSmallAdminDto()
                {
                    Id             = user.Id,
                    Email          = user.Email,
                    EmailConfirmed = user.EmailConfirmed,
                    Firstname      = user.Firstname,
                    Lastname       = user.Lastname,
                    CreatedOnUtc   = user.CreatedOnUtc.ToShortDateString(),
                    Role           = rolesList[user.UserRoles[0].RoleId].Name
                };

                userSmallDtos.Add(smallModel);
            }

            // Initialize result
            PagedListDto <UserSmallAdminDto> returnDto = new PagedListDto <UserSmallAdminDto>();

            returnDto.PagingHeader = usersList.GetHeader();
            returnDto.List         = userSmallDtos;

            // Return result
            return(new OkObjectResult(returnDto));
        }
        public async Task <HttpResponseMessage> GetAsync([FromUri] int pageSize, [FromUri] int pageNumber)
        {
            try
            {
                PagedListDto <UserDto> users = await userService.GetUsers(pageSize, pageNumber);

                return(Request.CreateResponse(HttpStatusCode.OK, users));
            }
            catch (EntityException e)
            {
                tracer.Error(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, e);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
        public async Task <HttpResponseMessage> GetUsersbyRoleAsync(int roleId, [FromUri] int pageSize, [FromUri] int pageNumber)
        {
            if (roleId != Constants.Roles.BlockedIndex)
            {
                var role = roleService.GetAsync(roleId);
                if (role == null)
                {
                    const string roleErorMessage = "No roles with this id  in database.";
                    return(Request.CreateErrorResponse(HttpStatusCode.NoContent, roleErorMessage));
                }
            }
            PagedListDto <UserDto> users = await userService.GetUsersByRoleAsync(roleId, pageSize, pageNumber);

            return(Request.CreateResponse(HttpStatusCode.OK, users));
        }
Exemple #9
0
        public void BuildNavigationLinks_BuildsSelfLink_WithValidUri()
        {
            // Arrange
            var url       = _faker.Internet.UrlWithPath();
            var pagedList = new PagedListDto <string>();

            // Act
            pagedList.BuildNavigationLinks(url);

            // Assert
            Assert.That(pagedList.Links, Is.Not.Null);
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNameSelf), Is.True);
            Assert.That(pagedList.Links[ResourceBase.RelationNameSelf], Is.EqualTo(url));
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNameNext), Is.False);
            Assert.That(pagedList.Links.ContainsKey(ResourceBase.RelationNamePrevious), Is.False);
        }
        public async Task <IActionResult> GetFiltered([FromBody] MediaFileFilterDto filter)
        {
            // Check if valid user
            var currentUser = await _identityService.GetCurrentPersonIdentityAsync();

            if (currentUser == null)
            {
                return(BadRequest(new RequestMessageResponse()
                {
                    Success = false, Message = "Forbidden"
                }));
            }

            // Create pager
            PagingParams pager = new PagingParams();

            pager.PageNumber = filter.PageNumber;
            pager.PageSize   = filter.PageSize;

            // Get filtered list from dB
            var fileList = _mediaFileService.GetAllMediaFilesPagedList(pager, currentUser.Id);

            // Map entitites to dto
            IList <MediaFileSmallDto> mediaFileSmallDtos = new List <MediaFileSmallDto>();

            foreach (var file in fileList.List)
            {
                MediaFileSmallDto smallModel = new MediaFileSmallDto()
                {
                    Id           = file.Id,
                    Title        = file.Title,
                    CreatedOnUtc = file.CreatedOnUtc.ToShortTimeString(),
                    Size         = file.Size.GetHumanReadableFileSize()
                };

                mediaFileSmallDtos.Add(smallModel);
            }

            // Initialize result
            PagedListDto <MediaFileSmallDto> returnDto = new PagedListDto <MediaFileSmallDto>();

            returnDto.PagingHeader = fileList.GetHeader();
            returnDto.List         = mediaFileSmallDtos;

            // Return result
            return(new OkObjectResult(returnDto));
        }
        public PagedListDto <T2> Convert(IPagedList <T1> source, PagedListDto <T2> destination, ResolutionContext context)
        {
            var items = context.Mapper.Map <List <T2> >(source);

            return(new PagedListDto <T2>
            {
                Items = items,
                FirstItemOnPage = source.FirstItemOnPage,
                HasNextPage = source.HasNextPage,
                HasPreviousPage = source.HasPreviousPage,
                IsFirstPage = source.IsFirstPage,
                IsLastPage = source.IsLastPage,
                LastItemOnPage = source.LastItemOnPage,
                PageCount = source.PageCount,
                PageNumber = source.PageNumber,
                PageSize = source.PageSize,
                TotalItemCount = source.TotalItemCount
            });
        }
Exemple #12
0
        // Admin
        public PagedListDto <UserWithRolesDto> MapToUserWithRolesDto(PagedListData <Ssuser> pl)
        {
            var items = pl.Select(
                u => new UserWithRolesDto()
            {
                Id       = u.Id,
                UserName = u.UserName,
                Roles    = u.SsuserRole.Select(r => r.Role.ToString()).ToList(),  // is this right?? 062820/070620/070920
            }).ToList();

            var pldto = new PagedListDto <UserWithRolesDto>(items)
            {
                TotalItems   = pl.TotalItems,
                ItemsPerPage = pl.ItemsPerPage,
                CurrentPage  = pl.CurrentPage,
                TotalPages   = pl.TotalPages
            };

            return(pldto);
        }
Exemple #13
0
        public async Task GetArtists(ArtistPageParams p)
        {
            using (var mock = AutoMock.GetLoose())
            {
                var plArtists = new PagedListData <Artist>(new List <Artist>(), 1, 1, 1)
                {
                };
                var returnDto = new PagedListDto <ArtistForListDto>(new List <ArtistForListDto>());

                mock.Mock <IArtistData>().Setup(x => x.GetArtistsAsync(p.PN, p.IPP, p.Search, p.OrderBy)).Returns(Task.FromResult(plArtists));
                mock.Mock <IMap>().Setup(x => x.MapToArtistForListDto(plArtists)).Returns(returnDto);

                var cls      = mock.Create <ArtistRepo>();
                var expected = new PagedListDto <ArtistForListDto>(new List <ArtistForListDto>());
                var actual   = await cls.GetArtistsAsync(p);

                Assert.True(actual != null);
                Assert.Equal(expected, actual);
                // More Tests needed
            }
        }
Exemple #14
0
        // Artist
        public PagedListDto <ArtistForListDto> MapToArtistForListDto(PagedListData <Artist> pl)
        {
            var artists = pl.Select(a => new ArtistForListDto
            {
                Id             = a.ArtistId,
                Name           = a.ArtistName,
                ArtistStatusId = a.ArtistStatusId,
                YearsActive    = ArtistCalculations.CalculateArtistYearsActive(a.CareerBeginDate, a.CareerEndDate),
                ArtistGroup    = a.ArtistGroup,
                UserId         = a.UserId,
                Verified       = a.Verified,
                HomeCity       = GetHomeCity(a)
            }).ToList();

            var pldto = new PagedListDto <ArtistForListDto>(artists)
            {
                TotalItems   = pl.TotalItems,
                ItemsPerPage = pl.ItemsPerPage,
                CurrentPage  = pl.CurrentPage,
                TotalPages   = pl.TotalPages
            };;

            return(pldto);
        }
Exemple #15
0
 /// <summary>
 /// Fills navigation for the paged list with the hyperlinks: self, previous and next, when applicable.
 /// </summary>
 public static void BuildNavigationLinks <T>(this PagedListDto <T> pagedList, string currentUri)
 {
     pagedList.BuildNavigationLinks(new Uri(currentUri));
 }
        public static IHtmlContent ListView <T>(this IHtmlHelper htmlHelper, string viewName, PagedListDto <T> pagedList)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext);
            var mapper    = (IMapper)htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IMapper));
            var metaData  = mapper.Map <X.PagedList.PagedListMetaData>(pagedList.MetaData);

            var listContent = htmlHelper.Partial(viewName, pagedList.List);

            if (metaData.TotalItemCount <= 0)
            {
                return(new HtmlString("<div class='p-4 text-center' style='background: #fafafa'>Empty</div>"));
            }

            var paginationContent = htmlHelper.PagedListPager(
                metaData, page =>
            {
                var request = htmlHelper.ViewContext.HttpContext.Request;
                var uri     = Common.GetUpdatedUri(request, "page", page.ToString());
                return(Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(uri, "page", page.ToString()));
            }, Bootstrap4PagedListRenderOptions.ClassicPlusFirstAndLast);

            var content = new HtmlContentBuilder()
                          .AppendHtml(paginationContent)
                          .AppendHtml(listContent)
                          .AppendHtml(paginationContent);

            return(content);
        }
        public async Task <HttpResponseMessage> GetUsersbyStateAsync(bool state, [FromUri] int pageSize, [FromUri] int pageNumber)
        {
            PagedListDto <UserDto> users = await userService.GetUsersByStateAsync(state, pageSize, pageNumber);

            return(Request.CreateResponse(HttpStatusCode.OK, users));
        }