public void TestInitilalization()
        {
            PreparedBonusesForTest = CreateMockBonuses();

            EmployeeRepositoryMock = new Mock<IRepository<Employee>>();
            EmployeeRepositoryMock.Setup(x => x.GetById(It.IsAny<int>()))
                                      .Returns(new Employee("name1", "lastname1", "ukr1")); ;

            RepositoryMock = new Mock<IRepository<BonusAggregate>>();
            RepositoryMock.Setup(x => x.FindAll(0, 2,
                                                It.IsAny<string>(),
                                                SortingDirection.Desc,
                                                It.IsAny<string>(),
                                                It.IsAny<string>()))
                                       .Returns(PreparedBonusesForTest);

            RepositoryWithExceptionMock = new Mock<IRepository<BonusAggregate>>();
            RepositoryWithExceptionMock.Setup(x => x.FindAll(0, -1,
                                                It.IsAny<string>(),
                                                SortingDirection.Desc,
                                                It.IsAny<string>(),
                                                It.IsAny<string>()))
                                        .Throws<ArgumentOutOfRangeException>();

            RepositoryWithExceptionMock.Setup(x => x.FindAll(It.IsAny<int>(), 0,
                                                It.IsAny<string>(),
                                                SortingDirection.Desc,
                                                It.IsAny<string>(),
                                                It.IsAny<string>()))
                                       .Returns(() => new PagedResponse<BonusAggregate>(null, 0));
        }
        public void PagedResponseNullTest()
        {
            var pr = new PagedResponse<string>(null, 10);

            Assert.IsNotNull(pr.Value);
            Assert.AreEqual(0, pr.Value.Count);
            Assert.AreEqual(10, pr.Count);
        }
        public void PagedResponseTest()
        {
            var strings = new[] {"123", "321"};
            var pr = new PagedResponse<string>(strings, 10);

            Assert.AreEqual(strings, pr.Value);
            Assert.AreEqual(10, pr.Count);
        }
        public async Task List_files()
        {
            // Arrange
            var files = new[]
            {
                new File("foo.txt", "abc", 8, "some foo", ContentEncoding.Utf8),
                new File("bar.txt", "def", 8, "some bar", ContentEncoding.Utf8)
            };
            var expected = new PagedResponse<File>(files, new RangeResponse(1, 2, 2));
            var connector = Mock.Of<IGalleryConnector>()
                .ThatGetsJson("/acme/sandboxes/john/vanilla/1.2.3/files/front", expected);
            var client = new SandboxesClient(connector);

            // Act
            var result = await client.ListFilesAsync("acme", "john", "vanilla", "1.2.3", "front", null, None);

            // Assert
            result.ShouldBe(expected);
        }
        public async Task List_files_with_all_parameters()
        {
            // Arrange
            var files = new[]
            {
                new File("foo.txt", "abc", 8, "some foo", ContentEncoding.Utf8),
                new File("bar.txt", "def", 8, "some bar", ContentEncoding.Utf8)
            };
            var expected = new PagedResponse<File>(files, new RangeResponse(1, 2, 2));
            var options = new AppFileListingOptions(new[] {"a", "b"}, 1, 2, true);
            var connector = Mock.Of<IGalleryConnector>()
                .ThatGetsJson("/acme/sandboxes/john/vanilla/1.2.3/files/front?f=a&f=b&_from=1&_to=2&content=true",
                    expected);
            var client = new SandboxesClient(connector);

            // Act
            var result = await client.ListFilesAsync("acme", "john", "vanilla", "1.2.3", "front", options, None);

            // Assert
            result.ShouldBe(expected);
        }
        public async Task <IPagedResponse <CustomerTransaction> > GetCustomerTransactionsAsync(int pageSize = 10, int pageNumber = 1, int?customerId = null, int?transactionTypeId = null, int?invoiceId = null, int?paymentMethodId = null)
        {
            Logger?.LogInformation("{0} has been invoked", nameof(GetCustomerTransactionsAsync));

            var response = new PagedResponse <CustomerTransaction>();

            try
            {
                Expression <Func <CustomerTransaction, bool> > predicate = c => true;

                if (customerId.HasValue)
                {
                    predicate = predicate.And(c => c.CustomerId == customerId);
                }

                if (transactionTypeId.HasValue)
                {
                    predicate = predicate.And(c => c.TransactionTypeId == transactionTypeId);
                }

                if (invoiceId.HasValue)
                {
                    predicate = predicate.And(c => c.InvoiceId == invoiceId);
                }

                if (paymentMethodId.HasValue)
                {
                    predicate = predicate.And(c => c.PaymentMethodId == paymentMethodId);
                }

                response.Model = await UnitOfWork.Repository <CustomerTransaction>().GetAsync(predicate, includeString: null, page: pageNumber, pageSize: pageSize);
            }
            catch (Exception ex)
            {
                return(new PagedResponse <CustomerTransaction>(Logger, nameof(GetCustomerTransactionsAsync), ex));
            }

            return(response);
        }
        public PagedResponse <ProductDto> Execute(SearchProduct search)
        {
            var query = _context.Products.Include(x => x.Brand).Include(x => x.Gender).Include(x => x.ShoeType).AsQueryable();

            if (!string.IsNullOrEmpty(search.Name) || !string.IsNullOrWhiteSpace(search.Name))
            {
                query = query.Where(x => x.Name.ToLower().Contains(search.Name.ToLower()));
            }
            if (search.BrandId != null)
            {
                query = query.Where(x => x.BrandId == search.BrandId);
            }
            if (search.GenderId != null)
            {
                query = query.Where(x => x.GenderId == search.GenderId);
            }
            if (search.ShoeTypeId != null)
            {
                query = query.Where(x => x.ShoeTypeId == search.ShoeTypeId);
            }
            if (search.MinPrice != null)
            {
                query = query.Where(x => x.Price >= search.MinPrice);
            }
            if (search.MaxPrice != null)
            {
                query = query.Where(x => x.Price <= search.MaxPrice);
            }
            var skipCount = search.PerPage * (search.Page - 1);
            var response  = new PagedResponse <ProductDto>
            {
                CurrentPage  = search.Page,
                ItemsPerPage = search.PerPage,
                TotalCount   = query.Count(),
                Items        = _mapper.Map <List <ProductDto> >(query.Skip(skipCount).Take(search.PerPage).ToList())
            };

            return(response);
        }
Beispiel #8
0
        public static PagedResponse <T> CreatePaginatedResponse <T>(IUriService uriService, PaginationFilter pagination,
                                                                    List <T> response)
        {
            var nextPage = pagination.PageNumber >= 1
                ? uriService.GetAllPost(new PaginationQuery(pagination.PageNumber + 1, pagination.PageSize)).ToString()
                : null;

            var previousPage = pagination.PageNumber - 1 >= 1
                ? uriService.GetAllPost(new PaginationQuery(pagination.PageNumber - 1, pagination.PageSize)).ToString()
                : null;

            var paginationResponse = new PagedResponse <T>
            {
                Data         = response,
                PageNumber   = pagination.PageNumber >= 1 ? pagination.PageNumber : (int?)null,
                PageSize     = pagination.PageSize >= 1 ? pagination.PageSize : (int?)null,
                NextPage     = response.Any() ? nextPage : null,
                PreviousPage = previousPage
            };

            return(paginationResponse);
        }
Beispiel #9
0
        public async Task <PagedResponse <AuthorModel> > GetFilteredAuthorsAsync(AuthorFilterModel model, PaginationFilterModel pagination)
        {
            if (string.IsNullOrWhiteSpace(model.SortBy) && string.IsNullOrWhiteSpace(model.TypeSort))
            {
                model.SortBy   = Constants.Sort.DefaultSortById;
                model.TypeSort = Constants.Sort.DefaultSortByAsc;
            }

            (IEnumerable <Author> authors, int count)tupleAuthors = await _authorRepository.GetFilteredAuthorsAsync(model, pagination);

            var authorModel = _autoMapper.Map <IEnumerable <AuthorModel> >(tupleAuthors.authors);

            var pagedResponse = new PagedResponse <AuthorModel>
            {
                Data       = authorModel,
                PageNumber = pagination.PageNumber,
                PageSize   = pagination.PageSize,
                TotalItems = tupleAuthors.count
            };

            return(pagedResponse);
        }
Beispiel #10
0
        public PagedResponse GetTotalPages()
        {
            PagedResponse resp = new PagedResponse();

            try
            {
                resp.TotalResultCount = _userDAL.GetCountByContains();
                if (resp.TotalResultCount <= 0)
                {
                    resp.Message = "无记录!";
                }
                else
                {
                    resp.Succeed = true;
                }
            }
            catch (Exception ex)
            {
                Log(ex);
            }
            return(resp);
        }
Beispiel #11
0
        public PagedResponse <Role> GetAll(PagedData <SearchCriteria> pagedInput)
        {
            bool AllRecords = false;
            var  input      = pagedInput.Data;
            var  result     = new PagedResponse <Role>();

            var start = pagedInput.PageNumber.HasValue ? pagedInput.PageNumber.Value : 1;
            var next  = pagedInput.NumberOfRecords.HasValue ? pagedInput.NumberOfRecords.Value : 20;

            AllRecords          = (next == -1);
            start               = (start - 1) * next;
            result.TotalRecords = this.Roles.Count();// FromSql<Role>(qry).Count();
            if (AllRecords)
            {
                result.Data = this.Roles;// .FromSql<Role>(qry);
            }
            else
            {
                result.Data = this.Roles.Skip(start).Take(next);
            }
            return(result);
        }
        protected async override Task <PagedResponse <MessageDto> > DoExecute(GetMessagesDto request)
        {
            if (request.Parameters.Page < 1)
            {
                request.Parameters.Page = 1;
            }

            var queriedMessages = _dbContext.Messages.Where(m =>
                                                            m.FromId == request.From && m.ToId == request.To ||
                                                            m.ToId == request.From && m.FromId == request.To);

            var messagesTask = queriedMessages.OrderByDescending(m => m.Timestamp)
                               .Skip((request.Parameters.Page - 1) * request.Parameters.PageSize)
                               .Take(request.Parameters.PageSize)
                               .ToListAsync();
            var countTask = queriedMessages.CountAsync();

            await Task.WhenAll(messagesTask, countTask);

            List <Message> messages = messagesTask.Result;
            int            count    = countTask.Result;

            // Set received messages as read
            await _setQueriedMessagesAsReadCommand.Execute(messages.Where(m => request.From == m.ToId && !m.IsRead));

            PagedResponse <MessageDto> response = new PagedResponse <MessageDto>()
            {
                Page       = request.Parameters.Page,
                TotalCount = count,
                Data       = messages.Select(m => new MessageDto()
                {
                    IsMine    = m.FromId == request.From,
                    Message   = m.Text,
                    Timestamp = m.Timestamp
                })
            };

            return(response);
        }
Beispiel #13
0
        public PagedResponse <UserDto> Execute(UserSearch search)
        {
            var query = _context.Users.AsQueryable();

            if (!string.IsNullOrEmpty(search.FirstName) || !string.IsNullOrWhiteSpace(search.FirstName))
            {
                query = query.Where(x => x.FirstName.ToLower().Contains(search.FirstName.ToLower()));
            }

            query = query.Where(x => x.IsActive == true);

            var skipCount = search.PerPage * (search.Page - 1);

            var response = new PagedResponse <UserDto>
            {
                CurrentPage  = search.Page,
                ItemsPerPage = search.PerPage,
                TotalCount   = query.Count(),
                Items        = query.Skip(skipCount).Take(search.PerPage).Select(x => new UserDto
                {
                    Id        = x.Id,
                    FirstName = x.FirstName,
                    LastName  = x.LastName,
                    Username  = x.UserName,
                    Email     = x.Email
                }).ToList()
            };

            foreach (var user in response.Items)
            {
                user.Blogs = _context.Blogs.Where(b => b.UserId == user.Id).Select(b => new BlogUserDto
                {
                    Id   = b.Id,
                    Name = b.Name
                }).ToList();
            }

            return(response);
        }
Beispiel #14
0
        public PagedResponse <TEntity> GetMultiple <TRequest, TEntity, TSortColumn>(TRequest request,
                                                                                    GetMultipleQuery <TRequest, TEntity, TSortColumn> query)
            where TRequest : SortablePageableRequest <TSortColumn>, IRequest
            where TEntity : AuditableEntity
            where TSortColumn : struct
        {
            Logger.LogTrace($"GetMultiple of {typeof(TEntity).Name}. By user {Username} ");
            var response = new PagedResponse <TEntity>();

            if (request.IsRequestInvalid(response, ContextInfo))
            {
                return(response);
            }

            query.ContextRequest = WrapRequest(request);
            var result = Repository.ExecuteQuery(query);

            response.Merge(result);


            return(response);
        }
Beispiel #15
0
        public void GetPaged_populates_total_record_count()
        {
            //  Arrange
            int take = 10;
            int skip = 0;
            var data = new PagedResponse <BranchDTO> {
                Data = new List <BranchDTO> {
                    new BranchDTO()
                }, TotalRecords = 1
            };

            _dataProvider.GetPagedBranches(take, skip).Returns(data);

            //  Act
            var result = _controller.GetPaged(take, skip) as OkNegotiatedContentResult <ApiResponse <IList <BranchDTO> > >;

            //  Assert
            _dataProvider.Received(1).GetPagedBranches(Arg.Is(take), Arg.Is(skip));
            Assert.IsInstanceOf <OkNegotiatedContentResult <ApiResponse <IList <BranchDTO> > > >(result);
            Assert.AreEqual(1, result.Content.TotalRecords);
            Assert.AreEqual(1, result.Content.Records);
        }
Beispiel #16
0
        public PagedResponse <GetProizvodDto> Execute(ProizvodSearch search)
        {
            var upit = _context.Proizvodi.Include(x => x.Cenovnici).Include(x => x.Slike).AsQueryable();

            if (!string.IsNullOrEmpty(search.Naziv) || !string.IsNullOrWhiteSpace(search.Naziv))
            {
                upit = upit.Where(x => x.Naziv.ToLower().Contains(search.Naziv.ToLower()));
            }
            if (search.IdKat != 0)
            {
                if (_context.Kategorije.Any(x => x.Id == search.IdKat))
                {
                    upit = upit.Where(x => x.IdKat == search.IdKat);
                }
                else
                {
                    throw new NotFoundException(search.IdKat, typeof(Kategorija));
                }
            }
            var preskokBrojenja = search.PoStrani * (search.Strana - 1);
            var odgovor         = new PagedResponse <GetProizvodDto>
            {
                TrenutnaStrana   = search.Strana,
                StavkePoStranici = search.PoStrani,
                UkupniBrojStavki = upit.Count(),
                Stavke           = upit.Skip(preskokBrojenja).Take(search.PoStrani).Select(x => new GetProizvodDto
                {
                    Naziv    = x.Naziv,
                    Kolicina = x.Kolicina,
                    Slika    = x.Slika,
                    Slike    = x.Slike.Select(x => x.Putanja),
                    Opis     = x.Opis,
                    Cena     = x.Cenovnici.OrderByDescending(y => y.Id).Select(x => x.CenaProizvod).First(),
                    IdKat    = x.IdKat
                }).ToList()
            };

            return(odgovor);
        }
Beispiel #17
0
        public async Task <IActionResult> GetAllBinsAsync([FromQuery] PagingParams pageParams = null)
        {
            var response = new PagedResponse <BinViewModel>();

            try
            {
                var bins = await _binRepository.ReadAllAsync(pageParams);

                response.Model      = _mapper.Map <List <BinViewModel> >(bins);
                response.PageNumber = pageParams.PageNumber;
                response.PageSize   = pageParams.PageSize;
                response.ItemsCount = await _binRepository.GetCount();
            }
            catch (Exception ex)
            {
                response.DidError     = true;
                response.ErrorMessage = "Server Error";
                response.ErrorDetails = $"{ex.Message}\n{ex.InnerException?.Message}\n{ex.InnerException?.InnerException?.Message}";
            }

            return(response.ToHttpResponse());
        }
Beispiel #18
0
        GetAllApartmentByOwnerIdAsync(string ownerId, PagedRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            Guid id = Guid.Parse(ownerId);

            try
            {
                var count = await _db.Apartments.Where(_ => _.OwnerId == id).CountAsync();

                var apartments = await _db.Apartments.Where(_ => _.OwnerId == id)
                                 .Skip((request.PageNumber - 1) * request.PageSize)
                                 .Take(request.PageSize)
                                 .Include(_ => _.Address.Country)
                                 .Include(_ => _.Address)
                                 .AsNoTracking().ToListAsync(cancellationToken);

                List <ApartmentView> result = new List <ApartmentView>();

                foreach (var apartment in apartments)
                {
                    var view = MakeApartmentView(apartment);

                    result.Add(view);
                }

                PagedResponse <ApartmentView> response
                    = new PagedResponse <ApartmentView>(result,
                                                        count,
                                                        request.PageNumber,
                                                        request.PageSize);

                return((Result <PagedResponse <ApartmentView> >) Result <PagedResponse <ApartmentView> >
                       .Ok(response));
            }
            catch (ArgumentNullException ex)
            {
                return((Result <PagedResponse <ApartmentView> >) Result <PagedResponse <ApartmentView> >
                       .Fail <PagedResponse <ApartmentView> >($"Source is null. {ex.Message}"));
            }
        }
Beispiel #19
0
        public PagedResponse <GetPostDto> Execute(PostSearch request)
        {
            var query = _context.Posts.Where(r => r.IsDeleted == false).AsQueryable();

            if (request.Title != null)
            {
                if (!query.Any(r => r.Title.ToLower().Contains(request.Title.ToLower())))
                {
                    throw new EntityNotFoundException("Post");
                }

                query = query.Where(r => r.Title.ToLower().Contains(request.Title.ToLower()));
            }

            var totalCount = query.Count();

            query = query.Include(s => s.PostImage).Skip((request.PageNumber - 1) * request.PerPage).Take(request.PerPage);

            var pagesCount = (int)Math.Ceiling((double)totalCount / request.PerPage);

            var response = new PagedResponse <GetPostDto>
            {
                PagesCount  = pagesCount,
                CurrentPage = request.PageNumber,
                TotalCount  = totalCount,
                Data        = query.Select(r => new GetPostDto
                {
                    Id          = r.Id,
                    Title       = r.Title,
                    Description = r.Description,
                    ImageName   = r.PostImage.ImageName,
                    PostImageId = r.PostImageId,
                    Rating      = r.Rating,
                    UserId      = r.UserId
                })
            };

            return(response);
        }
Beispiel #20
0
        public static PagedResponse <List <T> > CreatePagedReponse <T>(List <T> pagedData, PaginationFilter validFilter, int totalRecords, IUriService uriService, string route)
        {
            var respose           = new PagedResponse <List <T> >(pagedData, validFilter.PageNumber, validFilter.PageSize);
            var totalPages        = ((double)totalRecords / (double)validFilter.PageSize);
            int roundedTotalPages = Convert.ToInt32(Math.Ceiling(totalPages));

            respose.NextPage =
                validFilter.PageNumber >= 1 && validFilter.PageNumber < roundedTotalPages
                ? uriService.GetPageUri(new PaginationFilter(validFilter.PageNumber + 1, validFilter.PageSize), route)
                : null;

            respose.PreviousPage =
                validFilter.PageNumber - 1 >= 1 && validFilter.PageNumber <= roundedTotalPages
                ? uriService.GetPageUri(new PaginationFilter(validFilter.PageNumber - 1, validFilter.PageSize), route)
                : null;

            respose.FirstPage    = uriService.GetPageUri(new PaginationFilter(1, validFilter.PageSize), route);
            respose.LastPage     = uriService.GetPageUri(new PaginationFilter(roundedTotalPages, validFilter.PageSize), route);
            respose.TotalPages   = roundedTotalPages;
            respose.TotalRecords = totalRecords;
            return(respose);
        }
Beispiel #21
0
        public async Task <PagedResponse <IEnumerable <Winery> > > GetAllWineriesAsync(Request request)
        {
            try
            {
                var response = new PagedResponse <IEnumerable <Winery> >();

                var wineries = await DataStore.GetAllWineriesAsync();

                response.Total = wineries.Count();
                wineries       = wineries.SearchWineries(request.Token);
                wineries       = wineries.FilterWineries(request.Filters);
                wineries       = wineries.SortWineries(request.Sort);
                wineries       = wineries.Skip(request.Skip).Take(request.Take);

                response.Result = wineries.Select(x => x.MapToWineryContract());
                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public PagedResponse <UserDto> Execute(UserSearch search)
        {
            var query = _context.Users.Include(x => x.UserUseCases).AsQueryable();

            if (!string.IsNullOrEmpty(search.FirstLastUserName) || !string.IsNullOrWhiteSpace(search.FirstLastUserName)
                )
            {
                query = query.Where(x => x.FirstLastUsername.ToLower().Contains(search.FirstLastUserName.ToLower()));
            }

            var skipCount = search.PerPage * (search.Page - 1);

            var reponse = new PagedResponse <UserDto>
            {
                CurrentPage  = search.Page,
                ItemsPerPage = search.PerPage,
                TotalCount   = query.Count(),
                Items        = query.Skip(skipCount).Take(search.PerPage).Select(x => mapper.Map <UserDto>(x)).ToList()
            };

            return(reponse);
        }
Beispiel #23
0
        private PagedResponse <Reports> GetPagedResponse(ReportsSearch obj)
        {
            var listaObjava = reportsService.Get(obj);
            PagedResponse <Reports> respons = new PagedResponse <Reports>();

            respons.TotalPageCount = (int)Math.Ceiling((double)listaObjava.Count() / (double)obj.Limit);
            respons.Stavke         = listaObjava.Skip((obj.Page - 1) * obj.Limit).Take(obj.Limit).ToList();

            ReportsSearch iducaKlon = obj.Clone() as ReportsSearch;

            iducaKlon.Page = (iducaKlon.Page + 1) > respons.TotalPageCount ? -1 : iducaKlon.Page + 1;
            String iduciUrl = iducaKlon.Page == -1 ? null : this.Url.Action("Get", null, iducaKlon, Request.Scheme);

            ReportsSearch proslaKlon = obj.Clone() as ReportsSearch;

            proslaKlon.Page = (proslaKlon.Page - 1) < 0 ? -1 : proslaKlon.Page - 1;
            String prosliUrl = proslaKlon.Page == -1 ? null : this.Url.Action("Get", null, proslaKlon, Request.Scheme);

            respons.IducaStranica  = !String.IsNullOrWhiteSpace(iduciUrl) ? new Uri(iduciUrl) : null;
            respons.ProslaStranica = !String.IsNullOrWhiteSpace(prosliUrl) ? new Uri(prosliUrl) : null;
            return(respons);
        }
Beispiel #24
0
        public async Task <PagedResponse <InvoiceSearchDto> > SearchInvoice(string searchText, int pageIndex, int pageSize)
        {
            List <SqlParameter> parms = _searchManager.Search("invoiceSearch", searchText, pageIndex, pageSize, out SqlParameter outParam);
            var cartonList            = await _tcContext.Set <InvoiceSearch>().FromSqlRaw(SearchStoredProcedure.Sql, parms.ToArray()).ToListAsync();

            var totalRows = (int)outParam.Value;

            #region paging
            var postResponse = _mapper.Map <List <InvoiceSearchDto> >(cartonList);

            var paginationResponse = new PagedResponse <InvoiceSearchDto>
            {
                Data       = postResponse,
                pageNumber = pageIndex,
                pageSize   = pageSize,
                totalCount = totalRows,
                totalPages = (int)Math.Ceiling(totalRows / (double)pageSize),
            };
            #endregion

            return(paginationResponse);
        }
Beispiel #25
0
        public static async Task <List <Player> > SearchPlayer(string LastName)
        {
            var url = "http://localhost:5003/api/players/search?LastName=" + LastName;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);

                HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    PagedResponse <List <Player> > game = await response.Content.ReadAsAsync <PagedResponse <List <Player> > >();

                    return(game.Data);
                }
                else
                {
                    return(null);
                }
            }
        }
        public IEnumerable <ScrapedPost> Scrape(PageMetadata[] pages, DateTime since, DateTime until)
        {
            Debug.Assert(pages != null);

            Console.WriteLine($"Started scraping {pages.Length} pages for their posts");

            DateTime start         = DateTime.Now;
            int      numberOfPosts = 0;

            for (int i = 0; i < pages.Length; i++)
            {
                PageMetadata page = pages[i];
                Console.WriteLine($"{i + 1}/{pages.Length}: {page.Name}");

                // Query the Facebook Graph API to get all posts in the given range, published only by
                // the page.
                var graphRequest = new PostsRequest(page.FacebookId, PostsRequestEdge.Posts)
                {
                    Since           = since,
                    Until           = until,
                    PaginationLimit = 100
                };

                PagedResponse <ScrapedPost> postsResponse = GraphClient.GetPosts <ScrapedPost>(graphRequest);
                foreach (ScrapedPost post in postsResponse.AllData())
                {
                    UpdateMetadata(post, page.Name);
                    Save(post, Refresh.False);

                    numberOfPosts++;
                    yield return(post);
                }

                Console.WriteLine(numberOfPosts);
            }

            Console.WriteLine($"Done scraping {pages.Length} pages for their posts");
        }
Beispiel #27
0
        public void Ok_Should_Return_Correctly_With_PagedResponse_Data()
        {
            var content = new PagedResponse <string>
            {
                Data          = new [] { "data" },
                PrevPageIndex = 111,
                NextPageIndex = 222
            };
            var message = "message";
            var actual  = ApiResponseHelper.Ok(message, content);

            actual.Should().BeOfType <ActionResult <ApiResponse> >();

            actual.Result.Should().BeOfType <ObjectResult>();
            actual.Result.As <ObjectResult>().StatusCode.Should().Be(StatusCodes.Status200OK);

            actual.Result.As <ObjectResult>().Value.Should().BeOfType <ApiResponse>();
            actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Success.Should().Be(true);
            actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Message.Should().Be(message);
            actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Data.Should().Be(content.Data);
            actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Navigation.PrevPageIndex.Should().Be(content.PrevPageIndex);
            actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Navigation.NextPageIndex.Should().Be(content.NextPageIndex);
        }
Beispiel #28
0
        /// <summary>
        /// Set the list with houses from the response
        /// </summary>
        /// <param name="url"></param>
        private async void SetHousesList(String url)
        {
            try
            {
                var service = new ThroneService();
                PagedResponse <List <House> > obj = await service.GetHousesAsync(url);

                if (obj.result != null)
                {
                    List <House> houses = obj.result;
                    foreach (House item in houses)
                    {
                        Houses.Add(item);
                    }
                }

                Buttons = obj.links;
            }
            catch (RedirectMainException)
            {
                NavigationService.Navigate(typeof(MainPage));
            }
        }
Beispiel #29
0
        public PagedResponse <UlogaDto> Execute(UlogaSearch search)
        {
            var query = context.Uloge.AsQueryable();

            if (!string.IsNullOrEmpty(search.NazivUloge) || !string.IsNullOrWhiteSpace(search.NazivUloge))
            {
                query = query.Where(x => x.NazivUloge.ToLower().Contains(search.NazivUloge.ToLower()));
            }
            var skipCount = search.PerPage * (search.Page - 1);

            var response = new PagedResponse <UlogaDto>
            {
                CurrentPage  = search.Page,
                ItemsPerPage = search.PerPage,
                TotalCount   = query.Count(),
                Items        = query.Skip(skipCount).Take(search.PerPage).Select(x => new UlogaDto
                {
                    NazivUloge = x.NazivUloge
                }).ToList()
            };

            return(response);
        }
Beispiel #30
0
        public async Task can_list()
        {
            SetupServerPagedResponse(PaginationJson, $"{Transaction2},{Transaction3},{Transaction4},{Transaction5}");

            var r = await client.Transactions.ListTransactionsAsync("fff");

            var truth = new PagedResponse <Transaction>
            {
                Pagination = PaginationModel,
                Data       = new[]
                {
                    Transaction2Model,
                    Transaction3Model,
                    Transaction4Model,
                    Transaction5Model
                }
            };

            truth.Should().BeEquivalentTo(r);

            server.ShouldHaveExactCall("https://api.coinbase.com/v2/accounts/fff/transactions")
            .WithVerb(HttpMethod.Get);
        }
Beispiel #31
0
        public static PagedResponse <IEnumerable <T> > CreatePagedReponse <T>(IEnumerable <T> pagedData, uint pageNumber, uint pageSize, int totalRecords, IUriService uriService, string route)
        {
            var respose           = new PagedResponse <IEnumerable <T> >(pagedData, (int)pageNumber, (int)pageSize);
            var totalPages        = ((double)totalRecords / (double)pageSize);
            int roundedTotalPages = Convert.ToInt32(Math.Ceiling(totalPages));

            respose.NextPage =
                pageNumber >= 1 && pageNumber < roundedTotalPages
                ? uriService.GetPageUri(new PaginationInfo(pageNumber + 1, pageSize), route)
                : null;

            respose.PreviousPage =
                pageNumber - 1 >= 1 && pageNumber <= roundedTotalPages
                ? uriService.GetPageUri(new PaginationInfo(pageNumber - 1, pageSize), route)
                : null;

            respose.FirstPage    = uriService.GetPageUri(new PaginationInfo(1, pageSize), route);
            respose.LastPage     = uriService.GetPageUri(new PaginationInfo((uint)roundedTotalPages, pageSize), route);
            respose.TotalPages   = roundedTotalPages;
            respose.TotalRecords = totalRecords;

            return(respose);
        }
Beispiel #32
0
        public async Task <IActionResult> SearchBranchesByName([FromQuery] string searchTerm,
                                                               [FromQuery] int pageNumber          = PagingConstants.DefaultPageNumber,
                                                               [FromQuery] int pageSize            = PagingConstants.DefaultPageSize,
                                                               CancellationToken cancellationToken = default)
        {
            try
            {
                var apiResponse = await _branchService.SearchBranchesByNameAsync(searchTerm, pageNumber, pageSize, cancellationToken);

                if (apiResponse.Success)
                {
                    var pagedApiResponse = new PagedResponse <BranchListResponse>(apiResponse.Data);
                    return(Ok(pagedApiResponse));
                }

                return(BadRequest(apiResponse));
            }

            catch (Exception exception)
            {
                return(_actionResultMapper.Map(exception));
            }
        }
Beispiel #33
0
        public PagedResponse GetTotalPages()
        {
            IEnumerable <FirstAssessment_FirstLevelSafetyAssessmentReportTable> source = _getFirstLevelSafetyAssessmentReportDAL.FindAll();
            PagedResponse resp = new PagedResponse();

            try
            {
                resp.TotalResultCount = source.Count();
                if (resp.TotalResultCount <= 0)
                {
                    resp.Message = "无记录!";
                }
                else
                {
                    resp.Succeed = true;
                }
            }
            catch (Exception ex)
            {
                Log(ex);
            }
            return(resp);
        }
Beispiel #34
0
        public PagedResponse <RoleDTO> Execute(SearchRoleDTO dto)
        {
            var rolesQuery = _context.Roles.AsQueryable();

            if (!string.IsNullOrEmpty(dto.Name) || !string.IsNullOrWhiteSpace(dto.Name))
            {
                rolesQuery = rolesQuery.Where(r => r.Name.ToLower().Contains(dto.Name.ToLower()));
            }

            var skipCount = dto.PerPage * (dto.Page - 1);

            var roles = _mapper.Map <List <RoleDTO> >(rolesQuery.Skip(skipCount).Take(dto.PerPage).ToList());

            var reponse = new PagedResponse <RoleDTO>
            {
                CurrentPage  = dto.Page,
                ItemsPerPage = dto.PerPage,
                TotalCount   = rolesQuery.Count(),
                Items        = roles
            };

            return(reponse);
        }
Beispiel #35
0
        /// <summary>
        /// Set the characterlist, which get from api request, with some error handling
        /// </summary>
        /// <param name="url"></param>
        private async void SetCharactersList(String url)
        {
            try
            {
                var service = new ThroneService();
                PagedResponse <List <Character> > obj = await service.GetCharactersAsync(url);

                if (obj.result != null)
                {
                    List <Character> characters = obj.result;
                    foreach (Character item in characters)
                    {
                        Characters.Add(item);
                    }
                }

                Buttons = obj.links;
            }
            catch (RedirectMainException)
            {
                NavigationService.Navigate(typeof(MainPage));
            }
        }
        /// <summary>
        /// Gets the list of photos with a specific status.
        /// </summary>
        /// <param name="status">The photo status.</param>
        /// <returns>A list of photos with provided status.</returns>
        public async Task<PagedResponse<PhotoContract>> GetPhotosWithStatus(PhotoStatus status)
        {
            var query = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri)
                .Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
                .Where(d => d.DocumentVersion == _currentDocumentVersion)
                .Where(p => p.Status == status);

            var documentQuery = query
                .OrderByDescending(p => p.CreatedDateTime.Epoch)
                .AsDocumentQuery();

            var documentResponse = await documentQuery.ExecuteNextAsync<PhotoDocument>();

            var photoContracts = await CreatePhotoContractsAndLoadUserData(documentResponse.ToList());

            var result = new PagedResponse<PhotoContract>
            {
                Items = photoContracts,
                ContinuationToken = documentResponse.ResponseContinuation
            };

            return result;
        }
        /// <summary>
        /// Fetches the photo stream data for a specified user.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="continuationToken">Last captured ticks in the form of a string.</param>
        /// <param name="includeNonActivePhotos">By default, false. If true, non-active photos are included.</param>
        /// <returns>List of photos up to the page size.</returns>
        public async Task<PagedResponse<PhotoContract>> GetUserPhotoStream(string userId, string continuationToken, bool includeNonActivePhotos = false)
        {
            var feedOptions = new FeedOptions
            {
                MaxItemCount = PhotoStreamPageSize,
                RequestContinuation = continuationToken
            };

            var query = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri,
                feedOptions)
                .Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
                .Where(d => d.DocumentVersion == _currentDocumentVersion)
                .Where(p => p.UserId == userId);

            if (!includeNonActivePhotos)
            {
                query = query
                    .Where(p => p.Status == PhotoStatus.Active);
            }

            var documentQuery = query
                .OrderByDescending(p => p.CreatedDateTime.Epoch)
                .AsDocumentQuery();

            var documentResponse = await documentQuery.ExecuteNextAsync<PhotoDocument>();

            var photoContracts = await CreatePhotoContractsAndLoadUserData(documentResponse.ToList());

            var result = new PagedResponse<PhotoContract>
            {
                Items = photoContracts,
                ContinuationToken = documentResponse.ResponseContinuation
            };

            return result;
        }