public PagedResult<Party> GetParties(int page, int resultsPerPage) { PagedResult<Party> parties = new PagedResult<Party>(); parties.PageNumber = page; parties.ItemsPerPage = resultsPerPage; string sql = @"Select VintageRabbit.Parties.* From VintageRabbit.Parties Inner Join VintageRabbit.Orders On VintageRabbit.Parties.OrderGuid = VintageRabbit.Orders.Guid Where VintageRabbit.Orders.Status In ('Complete', 'AwaitingShipment') Order By VintageRabbit.Parties.DateCreated Desc OFFSET @Offset ROWS FETCH NEXT @ResultsPerPage ROWS ONLY; Select Count(*) From VintageRabbit.Parties;"; int offset = (page - 1) * resultsPerPage; using (SqlConnection connection = new SqlConnection(this._connectionString)) { using (var multi = connection.QueryMultiple(sql, new { Offset = offset, ResultsPerPage = resultsPerPage })) { parties.AddRange(multi.Read<Party>()); parties.TotalResults = multi.Read<int>().First(); } } return parties; }
public PagedResult<SystemPermission> GetPermissionPaging(int companyId, string keyword, bool? isDeleted, PagingInput pagingInput) { var query = GetPermissions(companyId, keyword, isDeleted); var result = new PagedResult<SystemPermission>(query); result.SetPaging(pagingInput); return result; }
public PagedResult<MemberListItem> GetMembers(FormDataCollection queryStrings) { // Base Query data int pageNumber = queryStrings.HasKey("pageNumber") ? queryStrings.GetValue<int>("pageNumber") : 1; int pageSize = queryStrings.HasKey("pageSize") ? queryStrings.GetValue<int>("pageSize") : 10; string orderBy = queryStrings.HasKey("orderBy") ? queryStrings.GetValue<string>("orderBy") : "email"; Direction orderDirection = queryStrings.HasKey("orderDirection") ? queryStrings.GetValue<Direction>("orderDirection") : Direction.Ascending; string memberType = queryStrings.HasKey("memberType") ? queryStrings.GetValue<string>("memberType") : ""; string filter = queryStrings.HasKey("filter") ? queryStrings.GetValue<string>("filter") : ""; int totalMembers = 0; var members = Mapper.Map<IEnumerable<MemberListItem>>(MemberSearch.PerformMemberSearch(filter, queryStrings, out totalMembers, memberType, pageNumber, pageSize, orderBy, orderDirection)); if (totalMembers == 0) return new PagedResult<MemberListItem>(0, 0, 0); var pagedResult = new PagedResult<MemberListItem>( totalMembers, pageNumber, pageSize); pagedResult.Items = members; return pagedResult; }
public async Task<PagedResult<LinkDTO>> GetLinks(int userId, int page = 1, int pageSize = 30) { PagedResult<ShortenedLink> shortenedLinksPagedResult = new PagedResult<ShortenedLink>(); PagedResult<LinkDTO> linksDtoPagedResult = new PagedResult<LinkDTO>(); linksDtoPagedResult.Results = new List<LinkDTO>(); var existingUser = await _usersRepository.Get(userId); if (existingUser != null) { shortenedLinksPagedResult = await _shortenedLinksRepository.GetPagedResultByQuery(page, pageSize, sl => sl.User.Id == existingUser.Id, sl => sl.Created, true); foreach (var shortenLink in shortenedLinksPagedResult.Results) { var linkDto = new LinkDTO() { CreatedDate = shortenLink.Created?.ToShortDateString(), CreatedTime = shortenLink.Created?.ToShortTimeString(), FullLink = shortenLink.FullLink, ShortLink = ShortLinkCreator.CreateShortLink(Request.RequestUri, shortenLink.ShortLink), VisitsCount = shortenLink.VisitCount }; linksDtoPagedResult.Results.Add(linkDto); } linksDtoPagedResult.TotalCount = shortenedLinksPagedResult.TotalCount; linksDtoPagedResult.CurrentPage = shortenedLinksPagedResult.CurrentPage; linksDtoPagedResult.PageCount = shortenedLinksPagedResult.PageCount; linksDtoPagedResult.PageSize = shortenedLinksPagedResult.PageSize; } return linksDtoPagedResult; }
public PagedResult<Company> GetCompaniesPaging(string keyword, bool? isActived, bool? isRootSite, bool? isDeleted, PagingInput pagingInput) { var query = GetCompanies(keyword, isActived, isRootSite, isDeleted); var result = new PagedResult<Company>(query); result.SetPaging(pagingInput); return result; }
public void SearchingCatalog(ICollection<CatalogEntryModel> products, PagedResult<CatalogEntryModel> productsResult) { "Given existing catalog items". f(() => { products = new List<CatalogEntryModel> { new CatalogEntryModel {ProductId = 1}, new CatalogEntryModel {ProductId = 2}, new CatalogEntryModel {ProductId = 3} }; }); "When they are retrieved". f(async () => { CatalogServiceMock.Setup(m => m.SearchAsync(It.IsAny<QueryOptions>(), "test")).ReturnsAsync(new PagedResult<CatalogEntryModel>(products)); Request.RequestUri = new Uri(string.Format("{0}?criteria={1}", CatalogSearchUrl, "test")); Response = await Client.SendAsync(Request); productsResult = await Response.Content.ReadAsAsync<PagedResult<CatalogEntryModel>>(); }); "Then a '200 OK' status is returned". f(() => Response.StatusCode.ShouldBe(HttpStatusCode.OK)); "Then they are all returned". f(() => productsResult.Items.Count().ShouldBe(products.Count())); }
public PagedResult<UserModel> GetByOrganizationId(string organizationId, int page = 1, int pageSize = 10) { if (String.IsNullOrEmpty(organizationId) || !User.CanAccessOrganization(organizationId)) throw new ArgumentException("Invalid organization id.", "organizationId"); // TODO: These should probably throw http Response exceptions. int skip = (page - 1) * pageSize; if (skip < 0) skip = 0; if (pageSize < 1) pageSize = 10; List<UserModel> results = _userRepository.GetByOrganizationId(organizationId).Select(u => new UserModel { Id = u.Id, FullName = u.FullName, EmailAddress = u.EmailAddress, IsEmailAddressVerified = u.IsEmailAddressVerified, HasAdminRole = User.IsInRole(AuthorizationRoles.GlobalAdmin) && u.Roles.Contains(AuthorizationRoles.GlobalAdmin) }).ToList(); var organization = _organizationRepository.GetByIdCached(organizationId); if (organization.Invites.Any()) results.AddRange(organization.Invites.Select(i => new UserModel { EmailAddress = i.EmailAddress, IsInvite = true })); var result = new PagedResult<UserModel>(results.Skip(skip).Take(pageSize).ToList()) { Page = page > 1 ? page : 1, PageSize = pageSize >= 1 ? pageSize : 10, TotalCount = results.Count }; return result; }
public PagedResult<IUserView> AllUsers() { PagedResult<IUserView> p = new PagedResult<IUserView>(); p.Rows = UserDataFactory.AllUsers(); p.Total = p.Rows.Count; return p; }
public PagedResult<IProductView> GetProducts(int Prdcat, int Anzahl, int Start) { PagedResult<IProductView> resultSet = new PagedResult<IProductView>(); resultSet.Rows = ProductDataFactory.GetProducts(Prdcat, Anzahl, Start); resultSet.Total = resultSet.Rows.Count; return resultSet; }
public void SetupPaging(PagedResult<MessageInfo> pagedResult) { Result = pagedResult.Result; CurrentPage = pagedResult.TotalCount > 0 ? pagedResult.CurrentPage : 0; TotalItemCount = pagedResult.TotalCount; NotifyPropertiesChanged(); }
public PagedResult<ISupplierView> AllSupplier() { PagedResult<ISupplierView> resultSet = new PagedResult<ISupplierView>(); IList<ISupplierView> result = SupplierDataFactory.GetAllSuppliers(); resultSet.Rows = new List<ISupplierView>(result); resultSet.Total = result.Count; return resultSet; }
public PagedResult<IProductView> AllProducts() { var resultSet = new PagedResult<IProductView>(); resultSet.Rows = ProductDataFactory.AllProducts().ToList(); resultSet.Total = resultSet.Rows.Count; return resultSet; }
public void TotalPages() { var resultsPerPage = 10; var totalResults = 100; var pagedResults = new PagedResult<Customer>(1, null, resultsPerPage, totalResults); Assert.Equal(10, pagedResults.TotalPages); }
public PagedResult<ManageUser> GetAll() { var result = new PagedResult<ManageUser> { Result = DbContext.ManageUser.OrderByDescending(p => p.CreateTime).ToList() }; return result; }
public void User_GivenQuery_ReturnListFromView() { var extension = new Search(PortalApplication.Object); var expected = new PagedResult<IResult>(0, 0, null); PortalApplication.Setup(m => m.ViewManager.GetView("Users").Query(It.IsAny<IQuery>())).Returns(expected); var actual = extension.Users("query"); Assert.That(actual, Is.SameAs(expected)); }
public PagedResult<IPrdcatView> AllProductCategorys() { var resultSet = new PagedResult<IPrdcatView> { Rows = ProductDataFactory.AllProductsCategorys().ToList(), }; resultSet.Total = resultSet.Rows.Count; return resultSet; }
public ActionResult FeedbackManage(SystemFeedbackSM sm, int Page = 1, int PageSize = 20) { var list = systemFeedbackRepo.GetList(sm, Page, PageSize); var vms = Mapper.Map<IList<SystemFeedbackVM>>(list.Results); var result = new PagedResult<SystemFeedbackVM>(vms, Page, PageSize, list.RowCount); if (Request.IsAjaxRequest()) return PartialView("_ListFeedbackManage", result); ViewBag.userList = SelectHelper.GetUserList(); return View(result); }
public void HasResultsReturnsTrueIfContainsResults() { var page = 1; var results = new List<Customer> { new Customer() }; var resultsPerPage = 10; var totalResults = 100; var pagedResults = new PagedResult<Customer>(page, results, resultsPerPage, totalResults); Assert.True(pagedResults.HasResults); }
public void MoreResultsAvailableReturnsTrueIfMoreResults() { var page = 1; var results = new List<Customer> { new Customer() }; var resultsPerPage = 10; var totalResults = 100; var pagedResults = new PagedResult<Customer>(page, results, resultsPerPage, totalResults); Assert.True(pagedResults.MoreResultsAvailable); }
public void HasResultsReturnsFalseIfNoResults() { var page = 1; var results = new List<Customer>(); var resultsPerPage = 10; var totalResults = 100; var pagedResults = new PagedResult<Customer>(page, results, resultsPerPage, totalResults); Assert.False(pagedResults.HasResults); }
public PagedResult<LogEntry> GetPagedLogs(int pageIndex, int pageSize) { PagedResult<LogEntry> result = null; ServiceSupport.AuthorizeAndExecute(() => { result = new PagedResult<LogEntry>(); result.Entities = LogRepository.GetPagedLogs(pageIndex, pageSize).ToList(); result.TotalItemCount = LogRepository.GetTotalLogCount(); }, "ktei"); return result; }
public PagedResult<User> GetAll() { var result = new PagedResult<User> { PageIndex = 0, PageSize = 10000, SizeCount = DbContext.User.Count(), Result = DbContext.User.OrderByDescending(p => p.CreateTime).ToList() }; return result; }
public CommentsModel(int pageNumber, PagedResult<Comment> comments) { PageNumber = pageNumber; Comments = comments; Paginator = new Paginator { ActionName = "Comments", CurrentPage = pageNumber, TotalPages = comments.TotalPages }; }
public void Search() { var entries = new PagedResult<EntryRevision>(new List<EntryRevision>(), 0, 0, 50); Repository.Find(Arg.Is<SwitchingSearchEntriesQuery>(q=>q.SearchText == "search"), Arg.Any<int>(), Arg.Any<int>()).Returns(entries); var result = (ViewResult)Controller.Search("search", false); Repository.Received().Find(Arg.Is<SwitchingSearchEntriesQuery>(q => q.SearchText == "search"), Arg.Any<int>(), Arg.Any<int>()); Assert.That(result.ViewName, Is.EqualTo("Search")); Assert.IsInstanceOf<SearchModel>(result.ViewData.Model); Assert.AreEqual(entries, ((SearchModel)result.ViewData.Model).Results); }
public RecentModel(string title, PagedResult<EntrySummary> results, string actionName) { Title = title; Results = results; ActionName = actionName; Paginator = new Paginator { ActionName = actionName, CurrentPage = Results.Page, TotalPages = Results.TotalPages }; }
public void ConstructorSetsProperties() { var page = 1; var results = new List<Customer> { new Customer() }; var resultsPerPage = 10; var totalResults = 100; var pagedResults = new PagedResult<Customer>(page, results, resultsPerPage, totalResults); Assert.Equal(page, pagedResults.Page); Assert.Equal(results, pagedResults.Results); Assert.Equal(resultsPerPage, pagedResults.ResultsPerPage); Assert.Equal(totalResults, pagedResults.TotalResults); }
public void TrackHistoryChanged(PagedResult<QueuedTrack> trackHistory) { try { using (var client = new SpotifyCallbackServiceClient()) { client.TrackHistoryChanged(trackHistory); } } catch (Exception ex) { logger.Error("TrackHistoryChanged failed with exception {0}", ex.Message); } }
public async Task<ActionResult> Index(int page = 0) { var styleList = Task.Factory.StartNew(() => { var viewModel = new PagedResult<StyleEntity, StyleDisplayViewModel>( _styleRepository.GetStyles(), page, ToDisplayModel); return viewModel; }); return View(await styleList); }
public IPagedResult<Data.Dto.v5.Object> Get(IQuery query, UUID accessPointGUID, bool includeMetadata = false, bool includeFiles = false, bool includeObjectRelations = false, bool includeAccessPoints = false) { var accesspointGuid = accessPointGUID != null ? accessPointGUID.ToGuid() : (Guid?)null; query.Query = query.Query.Replace("GUID:", "Id:"); query.Query = query.Query.Replace("ObjectTypeID:", "ObjectTypeId:"); var result = ObjectQueryHelper.GetObjects(query, accesspointGuid, GetFoldersWithAccess(), includeAccessPoints, includeMetadata, includeFiles, includeObjectRelations); var page = new PagedResult<Data.Dto.v5.Object>(result.FoundCount, result.StartIndex, result.Results.Select(item => Data.Dto.v5.Object.Create(((ObjectViewData) item).Object))); return page; }
public BudgetLinesPagedViewModel(string budgetId, PagedResult<BudgetLine> lines, DateTime? from, DateTime? to, IEnumerable<Category> categories, string category) { From = from; To = to; BudgetId = budgetId; Lines = lines; PageIndex = lines.PageIndex; TotalPages = lines.TotalPages(); var c = categories.ToList(); c.Insert(0, new Category()); Categories = c; Category = category; }
//Inject DataBase--End #endregion #region Search Products public IActionResult Search(string name, int categoryId = -1, int sortBy = 1, int pageNumber = 1, int pageSize = 12) { //Filter Name name = name ?? ""; var products = _db.ProductAbstract .Include(x => x.Category) .Include(x => x.Brand) .Include(x => x.ProductImage) .Include(x => x.ProductFeature) .Where(x => x.Name.Contains(name) || x.LatinName.ToLower().Contains(name.ToLower()) || x.Category.Name.Contains(name) || x.Brand.Name.Contains(name) ); //Filter Category string FilteredCategory = null; if (categoryId != -1) { products = products.Where(e => e.CategoryId == categoryId); FilteredCategory = dbCategory.GetAll().Where(e => e.Id == categoryId).FirstOrDefault().Name; ViewData["FilteredCategory"] = FilteredCategory; } //Sort switch (sortBy) { case 1: //newest products = products.OrderByDescending(x => x.RegDateTime); break; case 2: //cheapest products = products.OrderBy(x => x.BasePrice); break; case 3: //mostExpensive products = products.OrderByDescending(x => x.BasePrice); break; case 4: //Name products = products.OrderByDescending(x => x.Name); break; default: products = products.OrderByDescending(x => x.RegDateTime); break; } //Pagging var finalResult = PagedResult <ProductAbstract> .GetPaged(products, pageNumber, pageSize); //Parameters ViewData["pagenumber"] = pageNumber; ViewData["pagesize"] = pageSize; ViewData["totalRecords"] = products.Count(); ViewData["searchedName"] = name; ViewData["FilteredCategoryId"] = categoryId; ViewData["sortBy"] = sortBy; ViewData["IsFilterExist"] = false; ViewData["dbCategory"] = dbCategory.GetAll().Where(e => e.Status == true).ToList(); if (name != "" || FilteredCategory != null) { ViewData["IsFilterExist"] = true; } //Result var result = finalResult.Results.ToList(); return(View(result)); }
public async Task <PagedResult <EmployerRecord> > SearchEmployersAsync(string searchText, int page, int pageSize, bool test = false) { if (searchText.IsNumber()) { searchText = searchText.PadLeft(8, '0'); } var employersPage = new PagedResult <EmployerRecord> { PageSize = pageSize, CurrentPage = page, Results = new List <EmployerRecord>() }; if (test) { employersPage.ActualRecordTotal = 1; employersPage.VirtualRecordTotal = 1; var id = Numeric.Rand(100000, int.MaxValue - 1); var employer = new EmployerRecord { OrganisationName = SharedOptions.TestPrefix + "_Ltd_" + id, CompanyNumber = ("_" + id).Left(10), Address1 = "Test Address 1", Address2 = "Test Address 2", City = "Test Address 3", Country = "Test Country", PostCode = "Test Post Code", PoBox = null }; employersPage.Results.Add(employer); return(employersPage); } //Get the first page of results and the total records, number of pages, and page size var tasks = new List <Task <PagedResult <EmployerRecord> > >(); var page1task = SearchEmployersAsync(searchText, 1, pageSize); await page1task; //Calculate the maximum page size var maxPages = (int)Math.Ceiling((double)MaxRecords / page1task.Result.PageSize); maxPages = page1task.Result.PageCount > maxPages ? maxPages : page1task.Result.PageCount; //Add a task for ll pages from 2 upwards to maxpages for (var subPage = 2; subPage <= maxPages; subPage++) { tasks.Add(SearchEmployersAsync(searchText, subPage, page1task.Result.PageSize)); } //Wait for all the tasks to complete await Task.WhenAll(tasks); //Add page 1 to the list of completed tasks tasks.Insert(0, page1task); //Merge the results from each page into a single page of results foreach (var task in tasks) { employersPage.Results.AddRange(task.Result.Results); } //Get the toal number of records employersPage.ActualRecordTotal = page1task.Result.ActualRecordTotal; employersPage.VirtualRecordTotal = page1task.Result.VirtualRecordTotal; return(employersPage); }
public void AbsenceDaysCannotBookTests(AbsenceRange absenceRange, WorkingPattern workingPattern, IEnumerable <PublicHoliday> publicHolidays, IEnumerable <AbsenceDay> alreadyBookedAbsenceDays, IEnumerable <INotAbsenceDay> expectedAbsenceDays) { // Arrange _mockHRDataService.Setup(m => m.RetrievePublicHolidays(It.IsAny <Int32>(), It.IsAny <Int32>(), It.IsAny <Expression <Func <PublicHoliday, bool> > >(), It.IsAny <List <OrderBy> >(), It.IsAny <Paging>())).Returns(PagedResult <PublicHoliday> .Create(publicHolidays, 1, publicHolidays.Count(), 1, publicHolidays.Count())); _mockHRDataService.Setup(m => m.RetrieveAbsenceRangeBookedAbsenceDays(It.IsAny <AbsenceRange>())) .Returns(alreadyBookedAbsenceDays); // Act var actualAbsenceDays = _hrBusinessService.RetrieveCannotBeBookedDays(absenceRange, workingPattern); // Assert actualAbsenceDays.ShouldBeEquivalentTo(expectedAbsenceDays); _mockHRDataService.Verify(m => m.RetrievePublicHolidays(It.IsAny <Int32>(), It.IsAny <Int32>(), It.IsAny <Expression <Func <PublicHoliday, bool> > >(), It.IsAny <List <OrderBy> >(), It.IsAny <Paging>()), Times.Once); _mockHRDataService.Verify(m => m.RetrieveAbsenceRangeBookedAbsenceDays(It.IsAny <AbsenceRange>()), Times.Once); }
public PagedResult <CourseResult> FilterCourse(string userName, string FilterBy, Pageable pageable) { PagedResult <CourseResult> result = new PagedResult <CourseResult>(); result.Page = pageable.Page; result.Size = pageable.Size; int skipRow = PaginatorUtils.GetSkipRow(pageable.Page, pageable.Size); result.Total = _context.Course.Count(); if (result.Total > 0) { List <CourseResult> CourseFilterResult = new List <CourseResult>(); if (string.IsNullOrEmpty(FilterBy)) { CourseFilterResult = (from s in _context.Course join c in _context.StudentCourse on s.Id equals c.CourseId where s.Id == c.StudentId select new CourseResult() { Code = s.Code, Description = s.Description, Level = s.Level, TimeEnd = s.TimeEnd, TimeStar = s.TimeStar, TimeToRegister = s.TimeToRegister, TimeStarCourse = s.TimeStarCourse } ).ToList(); } else { switch (FilterBy) { case "ChuaBatDau": CourseFilterResult = (from s in _context.Course where s.TimeStar > DateTime.Now select new CourseResult { Code = s.Code, Description = s.Description, Level = s.Level, TimeEnd = s.TimeEnd, TimeStar = s.TimeStar, TimeToRegister = s.TimeToRegister, TimeStarCourse = s.TimeStarCourse } ).ToList(); break; case "DangHoc": CourseFilterResult = (from s in _context.Course where s.TimeStar <DateTime.Now && s.TimeEnd> DateTime.Now select new CourseResult { Code = s.Code, Description = s.Description, Level = s.Level, TimeEnd = s.TimeEnd, TimeStar = s.TimeStar, TimeToRegister = s.TimeToRegister, TimeStarCourse = s.TimeStarCourse }).ToList(); break; case "DaKetThuc": CourseFilterResult = (from s in _context.Course where s.TimeEnd < DateTime.Now select new CourseResult { Code = s.Code, Description = s.Description, Level = s.Level, TimeEnd = s.TimeEnd, TimeStar = s.TimeStar, TimeToRegister = s.TimeToRegister, TimeStarCourse = s.TimeStarCourse } ).ToList(); break; } } var ResultEnd = CourseFilterResult.Skip(skipRow).Take(pageable.Size).ToList(); result.Data = ResultEnd; } return(result); }
private PlacesResponse(PagedResult <PlaceInfoResource> pagedResult, bool success, string message) : base(success, message) { _pagedResult = pagedResult; }
public async Task <DepositsReport> GetAsync(GetDepositsReport query) { PagedResult <DepositDetails> deposits; if (query.DepositId == null) { deposits = await _depositRepository.BrowseAsync(new GetDeposits { Results = int.MaxValue }); } else { DepositDetails?detailsOfOne = await _depositRepository.GetAsync(query.DepositId); if (detailsOfOne is null) { return(DepositsReport.Empty); } deposits = PagedResult <DepositDetails> .Create(new[] { detailsOfOne }, 1, 1, 1, 1); } if (deposits.Items.Count == 0) { return(DepositsReport.Empty); } if (!deposits.Items.Any() || deposits.Items.Any(d => d is null)) { return(DepositsReport.Empty); } Dictionary <Keccak, DepositDetails> foundDeposits = deposits.Items .Where(d => (query.Provider is null || d.DataAsset.Provider.Address == query.Provider) && (query.AssetId is null || d.DataAsset.Id == query.AssetId)) .ToDictionary(d => d.Id, d => d); if (!foundDeposits.Any()) { return(DepositsReport.Empty); } IEnumerable <Keccak> assetIds = foundDeposits.Select(d => d.Value.DataAsset.Id); IReadOnlyList <DataDeliveryReceiptDetails> receipts = await _receiptRepository.BrowseAsync(query.DepositId, query.AssetId); Dictionary <Keccak, IEnumerable <DataDeliveryReceiptDetails> > depositsReceipts = receipts.Where(r => assetIds.Contains(r.DataAssetId)) .GroupBy(r => r.DepositId).ToDictionary(r => r.Key, r => r.AsEnumerable()); int page = query.Page; if (page <= 0) { page = 1; } int results = query.Results; if (results <= 0) { results = 10; } uint timestamp = (uint)_timestamper.UnixTime.Seconds; int skip = (page - 1) * results; List <DepositReportItem> items = new List <DepositReportItem>(); foreach ((Keccak _, DepositDetails deposit) in foundDeposits.OrderByDescending(d => d.Value.Timestamp).Skip(skip) .Take(results)) { depositsReceipts.TryGetValue(deposit.Id, out IEnumerable <DataDeliveryReceiptDetails>?depositReceipts); bool expired = deposit.IsExpired(timestamp); IEnumerable <DataDeliveryReceiptReportItem>?receiptItems = depositReceipts?.Select(r => new DataDeliveryReceiptReportItem(r.Id, r.Number, r.SessionId, r.ConsumerNodeId, r.Request, r.Receipt, r.Timestamp, r.IsMerged, r.IsClaimed)); PagedResult <ConsumerSession> sessions = await _sessionRepository.BrowseAsync(new GetConsumerSessions { DepositId = deposit.Id, Results = int.MaxValue }); uint consumedUnits = await _depositUnitsCalculator.GetConsumedAsync(deposit); items.Add(ToReportItem(deposit, expired, consumedUnits, receiptItems ?? Enumerable.Empty <DataDeliveryReceiptReportItem>())); } (UInt256 total, UInt256 claimed, UInt256 refunded) = CalculateValues(foundDeposits, depositsReceipts); int totalResults = foundDeposits.Count; int totalPages = (int)Math.Ceiling((double)totalResults / query.Results); return(new DepositsReport(total, claimed, refunded, PagedResult <DepositReportItem> .Create(items.OrderByDescending(i => i.Timestamp).ToList(), query.Page, query.Results, totalPages, totalResults))); }
/// <summary> /// GetApplicationListAsync /// </summary> /// <param name="previousPage"></param> /// <returns>ApplicationInfoApiModel</returns> public async Task <PagedResult <ApplicationInfoApiModel> > GetApplicationListAsync(PagedResult <ApplicationInfoApiModel> previousPage = null) { var pageResult = new PagedResult <ApplicationInfoApiModel>(); try { var query = new ApplicationRegistrationQueryApiModel { IncludeNotSeenSince = true }; var applications = new ApplicationInfoListApiModel(); if (string.IsNullOrEmpty(previousPage?.ContinuationToken)) { applications = await _registryService.QueryApplicationsAsync(query, _commonHelper.PageLength); if (!string.IsNullOrEmpty(applications.ContinuationToken)) { pageResult.PageCount = 2; } } else { applications = await _registryService.ListApplicationsAsync(previousPage.ContinuationToken, _commonHelper.PageLength); if (string.IsNullOrEmpty(applications.ContinuationToken)) { pageResult.PageCount = previousPage.PageCount; } else { pageResult.PageCount = previousPage.PageCount + 1; } } if (applications != null) { foreach (var app in applications.Items) { var application = (await _registryService.GetApplicationAsync(app.ApplicationId)).Application; pageResult.Results.Add(application); } } if (previousPage != null) { previousPage.Results.AddRange(pageResult.Results); pageResult.Results = previousPage.Results; } pageResult.ContinuationToken = applications.ContinuationToken; pageResult.PageSize = _commonHelper.PageLength; pageResult.RowCount = pageResult.Results.Count; } catch (UnauthorizedAccessException) { pageResult.Error = "Unauthorized access: Bad User Access Denied."; } catch (Exception e) { var message = "Can not get applications list"; _logger.Warning(e, message); pageResult.Error = message; } return(pageResult); }
/// <summary> /// GetDiscovererListAsync /// </summary> /// <param name="previousPage"></param> /// <returns>DiscovererInfo</returns> public async Task <PagedResult <DiscovererInfo> > GetDiscovererListAsync(PagedResult <DiscovererInfo> previousPage = null) { var pageResult = new PagedResult <DiscovererInfo>(); try { var discovererModel = new DiscovererQueryApiModel(); var applicationModel = new ApplicationRegistrationQueryApiModel(); var discoverers = new DiscovererListApiModel(); if (string.IsNullOrEmpty(previousPage?.ContinuationToken)) { discoverers = await _registryService.QueryDiscoverersAsync(discovererModel, _commonHelper.PageLengthSmall); if (!string.IsNullOrEmpty(discoverers.ContinuationToken)) { pageResult.PageCount = 2; } } else { discoverers = await _registryService.ListDiscoverersAsync(previousPage.ContinuationToken, _commonHelper.PageLengthSmall); if (string.IsNullOrEmpty(discoverers.ContinuationToken)) { pageResult.PageCount = previousPage.PageCount; } else { pageResult.PageCount = previousPage.PageCount + 1; } } if (discoverers != null) { if (discoverers.Items != null && discoverers.Items.Any()) { foreach (var disc in discoverers.Items) { var discoverer = await _registryService.GetDiscovererAsync(disc.Id); var info = new DiscovererInfo { DiscovererModel = discoverer, HasApplication = false, ScanStatus = (discoverer.Discovery == DiscoveryMode.Off) || (discoverer.Discovery == null) ? false : true }; applicationModel.DiscovererId = discoverer.Id; var applications = await _registryService.QueryApplicationsAsync(applicationModel, 1); if (applications != null) { info.HasApplication = true; } pageResult.Results.Add(info); } } } if (previousPage != null) { previousPage.Results.AddRange(pageResult.Results); pageResult.Results = previousPage.Results; } pageResult.ContinuationToken = discoverers.ContinuationToken; pageResult.PageSize = _commonHelper.PageLengthSmall; pageResult.RowCount = pageResult.Results.Count; } catch (UnauthorizedAccessException) { pageResult.Error = "Unauthorized access: Bad User Access Denied."; } catch (ResourceInvalidStateException) { pageResult.Error = "IotHubQuotaExceeded. Send and Receive operations are blocked for this hub until the next UTC day."; } catch (Exception e) { var message = "Cannot get discoverers as list"; _logger.Warning(e, message); pageResult.Error = message; } return(pageResult); }
public PagedResult <EmployerSearchModel> Search(EmployerSearchParameters searchParams, bool orderByRelevance) { List <SearchCachedOrganisation> allOrganisations = SearchRepository.CachedOrganisations .Where(o => o.IncludeInViewingService) .ToList(); List <SearchCachedOrganisation> filteredOrganisations = FilterByOrganisations(allOrganisations, searchParams); if (searchParams.Keywords == null) { List <SearchCachedOrganisation> orderedOrganisations = filteredOrganisations.OrderBy(o => o.OrganisationName.OriginalValue).ToList(); List <SearchCachedOrganisation> paginatedResultsForAllOrganisations = PaginateResults( orderedOrganisations, searchParams.Page, searchParams.PageSize); return(new PagedResult <EmployerSearchModel> { Results = ConvertToEmployerSearchModels(paginatedResultsForAllOrganisations), CurrentPage = searchParams.Page, PageSize = searchParams.PageSize, ActualRecordTotal = orderedOrganisations.Count, VirtualRecordTotal = orderedOrganisations.Count }); } string query = searchParams.Keywords.Trim().ToLower(); bool queryContainsPunctuation = WordSplittingRegex.ContainsPunctuationCharacters(query); List <string> searchTerms = SearchHelper.ExtractSearchTermsFromQuery(query, queryContainsPunctuation); var matchingOrganisations = new List <SearchCachedOrganisation>(); var convertedResults = new List <EmployerSearchModel>(); if (searchParams.SearchType == SearchType.NotSet) { throw new NotImplementedException(); } if (searchParams.SearchType == SearchType.ByEmployerName) { matchingOrganisations = GetMatchingOrganisationsByName( filteredOrganisations, searchTerms, query, queryContainsPunctuation); List <RankedViewingSearchOrganisation> organisationsWithRankings = CalculateOrganisationRankings( matchingOrganisations, searchTerms, query, queryContainsPunctuation); List <RankedViewingSearchOrganisation> rankedOrganisations = orderByRelevance ? OrderOrganisationsByRank(organisationsWithRankings) : OrderOrganisationsAlphabetically(organisationsWithRankings); List <RankedViewingSearchOrganisation> paginatedResults = PaginateResults( rankedOrganisations, searchParams.Page, searchParams.PageSize); convertedResults = ConvertRankedOrgsToEmployerSearchModels(paginatedResults); } if (searchParams.SearchType == SearchType.BySectorType) { matchingOrganisations = GetMatchingOrganisationsBySicCode( filteredOrganisations, searchTerms, query, queryContainsPunctuation); // Only alphabetically for SIC code search List <SearchCachedOrganisation> orderedOrganisations = matchingOrganisations.OrderBy(o => o.OrganisationName.OriginalValue).ToList(); List <SearchCachedOrganisation> paginatedSicCodeResults = PaginateResults( orderedOrganisations, searchParams.Page, searchParams.PageSize); convertedResults = ConvertSearchCachedOrganisationsToEmployerSearchModels(paginatedSicCodeResults); } var pagedResult = new PagedResult <EmployerSearchModel> { Results = convertedResults, CurrentPage = searchParams.Page, PageSize = searchParams.PageSize, ActualRecordTotal = matchingOrganisations.Count, VirtualRecordTotal = matchingOrganisations.Count }; return(pagedResult); }
public async Task <PagedResult <ContactPaginationDto> > GetPagedResultAsync(ContactPagingRequest contactPagingRequest) { PagedResult <ContactPaginationDto> pagedResult = await _contactRepository.GetPagedResultAsync(contactPagingRequest); return(pagedResult); }
public PagedResult <CourseFilterResult> CourseFilter(string userName, string filterBy, Pageable pageable) { var studentId = _context.Student.Where(p => String.Equals(p.UserName, userName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault().Id; PagedResult <CourseFilterResult> result = new PagedResult <CourseFilterResult>(); result.Page = pageable.Page; result.Size = pageable.Size; int skipRow = PaginatorUtils.GetSkipRow(pageable.Page, pageable.Size); result.Total = _context.Course.Count(); if (result.Total > 0) { List <CourseFilterResult> query = new List <CourseFilterResult>(); if (String.IsNullOrEmpty(filterBy)) { query = (from s in _context.Course join c in _context.CourseStudent on s.Id equals c.StudentId where c.StudentId == studentId select new CourseFilterResult() { Code = s.Code, Name = s.Name, Description = s.Description, BeginDate = s.BeginDate, EndDate = s.EndDate, RegisterDate = s.RegisterDate, MaxPeople = s.MaxPeople } ).ToList(); } else { switch (filterBy) { case "ChuaBatDau": query = (from s in _context.Course where s.BeginDate > DateTime.Now select new CourseFilterResult() { Code = s.Code, Name = s.Name, Description = s.Description, BeginDate = s.BeginDate, EndDate = s.EndDate, RegisterDate = s.RegisterDate, MaxPeople = s.MaxPeople } ).ToList(); break; case "DangHoc": query = (from s in _context.Course where s.BeginDate <= DateTime.Now && DateTime.Now >= s.EndDate select new CourseFilterResult() { Code = s.Code, Name = s.Name, Description = s.Description, BeginDate = s.BeginDate, EndDate = s.EndDate, RegisterDate = s.RegisterDate, MaxPeople = s.MaxPeople } ).ToList(); break; case "DaKetThuc": query = (from s in _context.Course where s.EndDate < DateTime.Now select new CourseFilterResult() { Code = s.Code, Name = s.Name, Description = s.Description, BeginDate = s.BeginDate, EndDate = s.EndDate, RegisterDate = s.RegisterDate, MaxPeople = s.MaxPeople } ).ToList(); break; } } var resultEnd = query.Skip(skipRow) .Take(pageable.Size).ToList(); result.Data = resultEnd; } return(result); }
/// <summary> /// Get activities for a conversation (Aka the transcript). /// </summary> /// <param name="channelId">Channel Id.</param> /// <param name="conversationId">Conversation Id.</param> /// <param name="continuationToken">Continuatuation token to page through results.</param> /// <param name="startDate">Earliest time to include.</param> /// <returns>PagedResult of activities.</returns> public async Task <PagedResult <IActivity> > GetTranscriptActivitiesAsync(string channelId, string conversationId, string continuationToken = null, DateTimeOffset startDate = default(DateTimeOffset)) { if (string.IsNullOrEmpty(channelId)) { throw new ArgumentNullException(nameof(channelId)); } if (string.IsNullOrEmpty(conversationId)) { throw new ArgumentNullException(nameof(conversationId)); } var pagedResult = new PagedResult <IActivity>(); var dirName = GetDirName(channelId, conversationId); var dir = this.Container.Value.GetDirectoryReference(dirName); var pageSize = 20; BlobContinuationToken token = null; List <CloudBlockBlob> blobs = new List <CloudBlockBlob>(); do { var segment = await dir.ListBlobsSegmentedAsync(false, BlobListingDetails.Metadata, null, token, null, null).ConfigureAwait(false); foreach (var blob in segment.Results.Cast <CloudBlockBlob>()) { if (DateTime.Parse(blob.Metadata["Timestamp"], CultureInfo.InvariantCulture).ToUniversalTime() >= startDate) { if (continuationToken != null) { if (blob.Name == continuationToken) { // we found continuation token continuationToken = null; } } else { blobs.Add(blob); if (blobs.Count == pageSize) { break; } } } } token = segment.ContinuationToken; }while (token != null && blobs.Count < pageSize); pagedResult.Items = blobs .Select(async bl => { var json = await bl.DownloadTextAsync().ConfigureAwait(false); return(JsonConvert.DeserializeObject <Activity>(json)); }) .Select(t => t.Result) .ToArray(); if (pagedResult.Items.Length == pageSize) { pagedResult.ContinuationToken = blobs.Last().Name; } return(pagedResult); }
public async Task <IActionResult> GetPage([FromQuery] GamePaginationRequest request = null) { PagedResult <GameResponse> pagedResult = await Games.GetPageAsync(request); return(ApiOk(pagedResult)); }
/// <summary> /// Initializes a new instance of the <see cref="ExampleEntityDataResponse"/> class. /// </summary> /// <param name="exampleEntities">The collection of Example Entities.</param> public ExampleEntityDataResponse(PagedResult <ExampleEntity> exampleEntities) { this.ExampleEntities = exampleEntities; }
public async Task Browse_empty_database() { PagedResult <DepositDetails> result = await repository.BrowseAsync(new GetDeposits()); result.Items.Should().HaveCount(0); }
public async Task ApplyActorActionAsync_ReturnsProcess() { int testId = -6; IList <int> activityComplete = new List <int>() { testId }; List <Process> returnList = new List <Process>(); returnList.Add(new Process() { ProcessId = testId, ProcessState = "PENDING", Activities = new Dictionary <int, Activity>() { { 1, new Activity() { ActivityId = 1, ActivityState = "PENDING", Actors = new Dictionary <int, Actor>() { { 1, new Actor() { ActorHanfordId = "Valid Id" } } } } } } }); PagedResult <Process> result = new PagedResult <Process>(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), returnList); ActorAction actorAction = new ActorAction() { ProcessId = testId, ActivityId = 1, ActorHanfordId = "Valid Id", }; Person person = new Person() { Id = "Valid Id", Network = new NetworkIdentifier() { Username = "******", Id = "Valid Id" } }; _mockProcessStore // arrange .Setup(store => store.GetAsync(It.Is <IList <int> >(s => s[0] == testId), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <CancellationToken>(), It.IsAny <IDictionary <object, object> >())) .ReturnsAsync(result); // no need to configure the store, controller itself handles this case try { var facade = InstanceActivityFacade(_mockActivityStore, _mockProcessStore, _mockPersonIdentificationStore, _mockApprovalsLegacyStore, _mockSecurityStore); var actual = await facade.ApplyActorActionAsync(actorAction, person, It.IsAny <CancellationToken>(), It.IsAny <IDictionary <object, object> >()); // act var objectResult = actual as ObjectResult; Assert.AreEqual(returnList[0], actual); } catch (Exception) { throw; } }
public StateListPageViewModel() { Country = new GeoCountryViewModel(); States = new PagedResult <IGeoZone>(); //Paging = new PaginationSettings(); }
private static void SetPagingInfo <T>(PagedResult <T> result, JsonDoc json) where T : class { result.TotalRecordCount = json.GetValue <int>("total_record_count", "total_count"); result.PageSize = json.GetValue <int>("max_page_size"); result.Page = json.GetValue <int>("page_number"); }
public static bool IsPageNumberLessThanLast <T>(this PagedResult <T> pagedResult) { return(pagedResult.PageNumber < pagedResult.TotalPages); }
public void TestPagedResultSorted() { var random = new Random(DateTime.Now.GetHashCode()); var teamMembers = new List <TeamMember>(); while (teamMembers.Count < 25) { var index = random.Next(9999); var administrator = CreateTeamMember <TeamMember>(index); if (teamMembers.All(a => a.UserId != administrator.UserId)) { teamMembers.Add(administrator); } } var createResults = DbAccess.Create <TeamMember, int>(teamMembers); Assert.True(createResults.Success); var expTeamMembers = teamMembers.OrderBy(a => a.UserId).ToList(); var sortFilter = new SortFilterString <TeamMember> { Expression = p => p.UserId }; var expRowCount = teamMembers.Count; var expPageCount = expRowCount / PagedResult <TeamMember> .PageSize_10; if (0 < expRowCount % PagedResult <TeamMember> .PageSize_10) { expPageCount++; } for (var pageNumber = 1; pageNumber <= expPageCount; pageNumber++) { Console.WriteLine($"Page {pageNumber}"); var pagedResult = new PagedResult <TeamMember> { SortFilters = new List <SortFilter <TeamMember> > { sortFilter }, PageNumber = pageNumber }; DbAccess.ReadPage <TeamMember, int>(pagedResult); Assert.AreEqual(pageNumber, pagedResult.PageNumber); Assert.AreEqual(expRowCount, pagedResult.RowCount); Assert.AreEqual(expPageCount, pagedResult.PageCount); var expPageSize = pageNumber < expPageCount || 0 == expPageCount % pagedResult.PageSize ? pagedResult.PageSize : expRowCount % pagedResult.PageSize; Assert.AreEqual(expPageSize, pagedResult.Results.Count()); for (var i = 0; i < expPageSize; i++) { var index = (pagedResult.PageNumber - 1) * pagedResult.PageSize + i; Console.WriteLine(pagedResult.Results[i].UserId); AssertTeamMember(expTeamMembers[index], pagedResult.Results[i]); } } sortFilter.Descending = true; expTeamMembers = teamMembers.OrderByDescending(a => a.UserId).ToList(); for (var pageNumber = 1; pageNumber <= expPageCount; pageNumber++) { Console.WriteLine($"Page {pageNumber}"); var pagedResult = new PagedResult <TeamMember> { SortFilters = new List <SortFilter <TeamMember> > { sortFilter }, PageNumber = pageNumber }; DbAccess.ReadPage <TeamMember, int>(pagedResult); var expPageSize = pageNumber < expPageCount || 0 == expPageCount % pagedResult.PageSize ? pagedResult.PageSize : expRowCount % pagedResult.PageSize; for (var i = 0; i < expPageSize; i++) { var index = (pagedResult.PageNumber - 1) * pagedResult.PageSize + i; Console.WriteLine(pagedResult.Results[i].UserId); AssertTeamMember(expTeamMembers[index], pagedResult.Results[i]); } } }
async Task <PagedResult <TimeEntryWithOwnerName> > ITimeEntryService.GetTimeEntries(GetTimeEntryQuery query) { Check.NotNull(query, errorMessage: "Query must be specified."); var currentPrincipal = await currentUserResolver.ResolveCurrentClaimsPrincipalAsync(); var operation = query.IncludeAllUsers ? Operation.ReadAll : Operation.Read; await authorizationService.AuthorizeResourceType(currentPrincipal, operation, typeof(TimeEntry)); var timeEntries = timeEntryRepository.GetTimeEntries(); var currentUser = await currentUserResolver.ResolveAsync(); if (operation == Operation.Read) { timeEntries = timeEntries.Where(te => te.OwnerId == currentUser.Id); } if (string.IsNullOrWhiteSpace(query.OrderBy)) { timeEntries = timeEntries.OrderBy(te => te.Date); } var pagedResult = new PagedResult <TimeEntryWithOwnerName>(); if (!string.IsNullOrEmpty(query.QueryString)) { try { var queryParserResult = await queryParser.ApplyQuery(timeEntries, query.QueryString); timeEntries = queryParserResult.Results; pagedResult.TotalCount = queryParserResult.TotalCount; } catch (Exception e) { throw new ValidationException("Invalid query string.", e); } } var pageSize = Constants.MaxPageSize; if (query.PageSize.HasValue && query.PageSize < Constants.MaxPageSize) { pageSize = query.PageSize.Value; } timeEntries = timeEntries.Take(pageSize); var preferredWorkingHourIndex = new Dictionary <string, double>(); foreach (var te in timeEntries) { var key = te.Date.Date.ToShortDateString() + "|" + te.OwnerId; if (!preferredWorkingHourIndex.ContainsKey(key)) { preferredWorkingHourIndex.Add(key, 0); } preferredWorkingHourIndex[key] += te.Duration; } var timeEntriesWithOwnerName = new List <TimeEntryWithOwnerName>(); foreach (var te in timeEntries) { var key = te.Date.Date.ToShortDateString() + "|" + te.OwnerId; timeEntriesWithOwnerName.Add(new TimeEntryWithOwnerName(te) { IsUnderPreferredWorkingHourPerDay = preferredWorkingHourIndex[key] < te.Owner.PreferredWorkingHourPerDay }); } pagedResult.Results = timeEntriesWithOwnerName.ToArray(); return(pagedResult); }
public static long NextPageNumber <T>(this PagedResult <T> pagedResult) { return(pagedResult.PageNumber + 1); }
public PlacesResponse(PagedResult <PlaceInfoResource> pagedResult) : this(pagedResult, true, string.Empty) { Console.WriteLine("Here 10"); Console.WriteLine(Success); }
public static long PreviousPageNumber <T>(this PagedResult <T> pagedResult) { return(pagedResult.PageNumber - 1); }
/// <summary> /// Get all paging /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <PagedResult <ProductViewModel> > GetAllPaging(GetManageProductPagingRequest request) { //select join var query = from p in _context.Products join pi in _context.ProductImages on p.Id equals pi.ProductId into pii from pi in pii.DefaultIfEmpty() join pt in _context.ProductTranslations on p.Id equals pt.ProductId join pic in _context.ProductInCategories on p.Id equals pic.ProductId into ppic from pic in ppic.DefaultIfEmpty()//left join join c in _context.Categories on pic.CategoryId equals c.Id into picc from c in picc.DefaultIfEmpty()//left join where pt.LanguageId == request.LanguageId && pi.IsDefault == true select new { p, pt, pic, pi }; //filter if (!string.IsNullOrEmpty(request.Keyword)) { query = query.Where(x => x.pt.Name.Contains(request.Keyword)); } if (request.CategoryId != null && request.CategoryId != 0) { query = query.Where(x => x.pic.CategoryId == request.CategoryId); } //paging int totalRow = await query.CountAsync(); var data = await query.Skip((request.PageIndex - 1) *request.PageSize) .Take(request.PageSize) .Select(x => new ProductViewModel() { Id = x.p.Id, Name = x.pt.Name, CreatedDate = x.p.CreatedDate, Description = x.pt.Description, Details = x.pt.Details, LanguageId = x.pt.LanguageId, OriginalPrice = x.p.OriginalPrice, Price = x.p.Price, SeoAlias = x.pt.SeoAlias, SeoDescription = x.pt.SeoDescription, SeoTitle = x.pt.SeoTitle, Stock = x.p.Stock, ViewCount = x.p.ViewCount, ThumbnailImage = x.pi.ImagePath }).ToListAsync(); //select and projection var pagedResult = new PagedResult <ProductViewModel>() { TotalRecords = totalRow, Items = data, PageSize = request.PageSize, PageIndex = request.PageIndex }; return(pagedResult); }
public async Task _ListTranscripts() { List <string> conversationIds = new List <string>(); DateTime start = DateTime.UtcNow; for (int i = 0; i < 100; i++) { conversationIds.Add($"_ListConversations{i}"); } List <Activity> activities = new List <Activity>(); foreach (var conversationId in conversationIds) { activities.AddRange(CreateActivities(conversationId, start, 1)); } // log in parallel batches of 10 int pos = 0; foreach (var group in activities.GroupBy(a => pos++ / 10)) { await Task.WhenAll(group.Select(a => store.LogActivityAsync(a))); } HashSet <string> seen = new HashSet <string>(); PagedResult <TranscriptInfo> pagedResult = null; var pageSize = 0; do { pagedResult = await store.ListTranscriptsAsync("test", pagedResult?.ContinuationToken); Assert.IsNotNull(pagedResult); Assert.IsNotNull(pagedResult.Items); // NOTE: Assumes page size is consistent if (pageSize == 0) { pageSize = pagedResult.Items.Count(); } else if (pageSize == pagedResult.Items.Count()) { Assert.IsTrue(!string.IsNullOrEmpty(pagedResult.ContinuationToken)); } foreach (var item in pagedResult.Items) { Assert.IsFalse(seen.Contains(item.Id)); if (item.Id.StartsWith("_ListConversations")) { seen.Add(item.Id); } } } while (pagedResult.ContinuationToken != null); Assert.AreEqual(conversationIds.Count(), seen.Count); foreach (var conversationId in conversationIds) { Assert.IsTrue(seen.Contains(conversationId)); } }
public static bool IsPageNumberGreaterThanFirst <T>(this PagedResult <T> pagedResult) { return(pagedResult.PageNumber > 1); }
public PagedResult <ContentItemBasic <ContentPropertyBasic> > GetChildren(int id, bool ignoreUserStartNodes, int pageNumber = 0, int pageSize = 0, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, bool orderBySystemField = true, string filter = "") { //if a request is made for the root node data but the user's start node is not the default, then // we need to return their start nodes if (id == Constants.System.Root && UserStartNodes.Length > 0 && (UserStartNodes.Contains(Constants.System.Root) == false && ignoreUserStartNodes == false)) { if (pageNumber > 0) { return(new PagedResult <ContentItemBasic <ContentPropertyBasic> >(0, 0, 0)); } var nodes = Services.MediaService.GetByIds(UserStartNodes).ToArray(); if (nodes.Length == 0) { return(new PagedResult <ContentItemBasic <ContentPropertyBasic> >(0, 0, 0)); } if (pageSize < nodes.Length) { pageSize = nodes.Length; // bah } var pr = new PagedResult <ContentItemBasic <ContentPropertyBasic> >(nodes.Length, pageNumber, pageSize) { Items = nodes.Select(Mapper.Map <IMedia, ContentItemBasic <ContentPropertyBasic> >) }; return(pr); } // else proceed as usual long totalChildren; List <IMedia> children; if (pageNumber > 0 && pageSize > 0) { IQuery <IMedia> queryFilter = null; if (filter.IsNullOrWhiteSpace() == false) { //add the default text filter queryFilter = SqlContext.Query <IMedia>() .Where(x => x.Name.Contains(filter)); } children = Services.MediaService .GetPagedChildren( id, (pageNumber - 1), pageSize, out totalChildren, queryFilter, Ordering.By(orderBy, orderDirection, isCustomField: !orderBySystemField)).ToList(); } else { //better to not use this without paging where possible, currently only the sort dialog does children = Services.MediaService.GetPagedChildren(id, 0, int.MaxValue, out var total).ToList(); totalChildren = children.Count; } if (totalChildren == 0) { return(new PagedResult <ContentItemBasic <ContentPropertyBasic> >(0, 0, 0)); } var pagedResult = new PagedResult <ContentItemBasic <ContentPropertyBasic> >(totalChildren, pageNumber, pageSize); pagedResult.Items = children .Select(Mapper.Map <IMedia, ContentItemBasic <ContentPropertyBasic> >); return(pagedResult); }
/// <summary> /// List conversations in the channelId. /// </summary> /// <param name="channelId">Channel Id.</param> /// <param name="continuationToken">Continuatuation token to page through results.</param> /// <returns>A <see cref="Task"/> A task that represents the work queued to execute.</returns> public async Task <PagedResult <TranscriptInfo> > ListTranscriptsAsync(string channelId, string continuationToken = null) { if (string.IsNullOrEmpty(channelId)) { throw new ArgumentNullException(nameof(channelId)); } var dirName = GetDirName(channelId); var dir = this.Container.Value.GetDirectoryReference(dirName); var pageSize = 20; BlobContinuationToken token = null; List <TranscriptInfo> conversations = new List <TranscriptInfo>(); do { var segment = await dir.ListBlobsSegmentedAsync(false, BlobListingDetails.Metadata, null, token, null, null).ConfigureAwait(false); foreach (var blob in segment.Results.Where(c => c is CloudBlobDirectory).Cast <CloudBlobDirectory>()) { // Unescape the Id we escaped when we saved it var conversation = new TranscriptInfo() { Id = Uri.UnescapeDataString(blob.Prefix.Split('/').Where(s => s.Length > 0).Last()), ChannelId = channelId }; if (continuationToken != null) { if (conversation.Id == continuationToken) { // we found continuation token continuationToken = null; } // skip record } else { conversations.Add(conversation); if (conversations.Count == pageSize) { break; } } } if (segment.ContinuationToken != null) { token = segment.ContinuationToken; } }while (token != null && conversations.Count < pageSize); var pagedResult = new PagedResult <TranscriptInfo>(); pagedResult.Items = conversations.ToArray(); if (pagedResult.Items.Length == 20) { pagedResult.ContinuationToken = pagedResult.Items.Last().Id; } return(pagedResult); }
public async Task ApplyActorActionAsync_ThrowsInvalidOperationException_InvalidActor() { int testId = -6; IList <int> activityComplete = new List <int>() { testId }; List <Process> returnList = new List <Process>(); returnList.Add(new Process() { ProcessId = testId, ProcessState = "PENDING", Activities = new Dictionary <int, Activity>() { { 1, new Activity() { ActivityId = 1, ActivityState = "PENDING", Actors = new Dictionary <int, Actor>() { { 1, new Actor() { ActorHanfordId = "Valid Id" } } } } } } }); PagedResult <Process> result = new PagedResult <Process>(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), returnList); ActorAction actorAction = new ActorAction() { ProcessId = testId, ActivityId = 1, ActorHanfordId = "Invalid", }; Person person = new Person() { Id = "Valid Id", Network = new NetworkIdentifier() { Username = "******", Id = "Valid Id" } }; _mockProcessStore // arrange .Setup(store => store.GetAsync(It.Is <IList <int> >(s => s[0] == testId), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <CancellationToken>(), It.IsAny <IDictionary <object, object> >())) .ReturnsAsync(result); _mockSecurityStore // arrange .Setup(store => store.GetAuthorizedAccountsAsync(It.IsAny <Process>(), It.IsAny <CancellationToken>(), It.IsAny <IDictionary <object, object> >())) .ReturnsAsync(new List <string>() { "Valid Id" }); try { var facade = InstanceActivityFacade(_mockActivityStore, _mockProcessStore, _mockPersonIdentificationStore, _mockApprovalsLegacyStore, _mockSecurityStore); var actual = await facade.ApplyActorActionAsync(actorAction, person, It.IsAny <CancellationToken>(), It.IsAny <IDictionary <object, object> >()); // act Assert.Fail(); } catch (Exception exception) { Assert.IsInstanceOfType(exception, typeof(InvalidOperationException)); } }