public void SetUp() { smartsheet = CreateClient(); // Remove user if it exists from a previous run. PaginatedResult <User> users = smartsheet.UserResources.ListUsers(null, new PaginationParameters(true, null, null)); foreach (User tmpUser in users.Data) { if (tmpUser.Email == email) { smartsheet.UserResources.RemoveUser((long)tmpUser.Id, null, null, true); break; } } }
public void ShouldBeEmptyWhenAddError() { var list = new List <int> { 1, 2, 3 }; var result = PaginatedResult <int> .Success(list, 3, 1, 3); var result2 = new PaginatedResult <int>(list, 3, 1, 3); result.AddError("Error"); result2.AddError("Error"); Assert.Empty(result.Data); Assert.Empty(result2.Data); }
public async Task <ActionResult <PaginatedResult <FamilySection> > > GetRunsFromFamily(string family, [FromQuery] int page, [FromQuery] int itemsPerPage, [FromQuery] string?pctId, // [int-int] [FromQuery] string?score) { try { var items = _context.FamilySections.Where(f => f.Family == family); if (pctId != null) { (int low, int high)pctIdLimits = Utilities.parseQueryParameterRange(pctId); items = items.Where(f => f.PctId >= pctIdLimits.low && f.PctId <= pctIdLimits.high); } if (score != null) { (int low, int high)scoreLimits = Utilities.parseQueryParameterRange(score); items = items.Where(f => f.Score >= scoreLimits.low && f.Score <= scoreLimits.high); } var families = await items.OrderByDescending(f => f.Score) .Skip((page - 1) * itemsPerPage) .Take(itemsPerPage).ToListAsync(); int numPages; var totalResults = await items.CountAsync(); if (totalResults % itemsPerPage != 0) { numPages = (totalResults / itemsPerPage) + 1; } else { numPages = totalResults / itemsPerPage; } var paginatedResult = new PaginatedResult <FamilySection> { Items = families, NumberOfPages = numPages }; return(paginatedResult); } catch (ArgumentException) { return(BadRequest()); } }
public async Task ListRolesAsync_WithNoInputs_ReturnsList() { // Arrange var roleService = Substitute.For <IRoleService>(); var inList = new List <RoleModel> { new RoleModel { Name = "Test Roles 1", Id = Guid.NewGuid() }, new RoleModel { Name = "Test Roles 2", Id = Guid.NewGuid() }, new RoleModel { Name = "Test Roles 3", Id = Guid.NewGuid() } }; PaginatedResult <RoleModel> paginatedResult = new PaginatedResult <RoleModel> { CurrentPage = 1, PageCount = 1, PageSize = 3, Results = inList }; roleService.GetPaginatedListAsync(Arg.Any <int>(), Arg.Any <int>(), Arg.Any <bool>(), Arg.Any <string>(), Arg.Any <List <KeyValuePair <string, string> > >()).Returns(paginatedResult); var controller = new RoleController(roleService, orderByHelper, paginationHelper, mapper); // Act IActionResult actionResult = await controller.ListRolesAsync(false, 0, 50, string.Empty, null); // Assert var okResult = actionResult as OkObjectResult; Assert.NotNull(okResult); var outList = okResult.Value as List <Role>; Assert.NotNull(outList); for (var i = 0; i < outList.Count; i++) { Assert.Equal(outList[i].Uuid, inList[i].Id); Assert.Equal(outList[i].Name, inList[i].Name); } }
public async Task <ActionResult <PaginatedResult <AccessionSection> > > GetRunsFromAccession(string genbank, [FromQuery] int page, [FromQuery] int itemsPerPage, [FromQuery] string?pctId, // [int-int] [FromQuery] string?cvgPct) { try { var items = _context.AccessionSections.Where(a => a.Acc == genbank); if (pctId != null) { (int low, int high)pctIdLimits = Utilities.parseQueryParameterRange(pctId); items = items.Where(a => a.PctId >= pctIdLimits.low && a.PctId <= pctIdLimits.high); } if (cvgPct != null) { (int low, int high)scoreLimits = Utilities.parseQueryParameterRange(cvgPct); items = items.Where(a => a.CvgPct >= scoreLimits.low && a.CvgPct <= scoreLimits.high); } var accs = await items.OrderByDescending(a => a.CvgPct) .Skip((page - 1) * itemsPerPage) .Take(itemsPerPage).ToListAsync(); int numPages; var totalResults = await items.CountAsync(); if (totalResults % itemsPerPage != 0) { numPages = (totalResults / itemsPerPage) + 1; } else { numPages = totalResults / itemsPerPage; } var paginatedResult = new PaginatedResult <AccessionSection> { Items = accs, NumberOfPages = numPages }; return(paginatedResult); } catch (ArgumentException) { return(BadRequest()); } }
public virtual void TestListColumns() { server.setResponseBody("../../../TestSDK/resources/listColumns.json"); PaginatedResult <Column> result = sheetColumnResourcesImpl.ListColumns(1234L, new List <ColumnInclusion> { ColumnInclusion.FILTERS }, null); Assert.True(result.TotalCount == 9); Assert.AreEqual(result.Data[2].Title, "Start"); Assert.IsTrue(result.Data[3].Filter != null); Assert.AreEqual(result.Data[3].Filter.Criteria[0].Operator, CriteriaOperator.GREATER_THAN); Assert.AreEqual(result.Data[3].Filter.Criteria[0].Value1, "2015-07-14"); Assert.IsTrue(result.Data[7].Filter == null); Assert.AreEqual(result.Data[7].Options.Count, 5); Assert.AreEqual(result.Data[7].Options[3], "At Risk"); }
/// <summary> /// Gets the SmartSheet templates /// </summary> /// <param name="refreshedToken">Smartsheet Token</param> /// <returns></returns> public Dictionary <string, string> GetTemplateSS(string refreshedToken = "") { Dictionary <string, string> templateSS = new Dictionary <string, string>(); Users userRecord = PXSelect < Users, Where <Users.pKID, Equal <Required <AccessInfo.userID> > > > .Select(this.Base, this.Base.Accessinfo.UserID); if (userRecord == null) { throw new PXException(SmartsheetConstants.Messages.ERROR_USER); } UsersSSExt userRecordSSExt = PXCache <Users> .GetExtension <UsersSSExt>(userRecord); try { Token token = new Token(); token.AccessToken = (String.IsNullOrEmpty(refreshedToken)) ? userRecordSSExt.UsrSmartsheetToken : refreshedToken; SmartsheetClient smartsheetClient = new SmartsheetBuilder().SetAccessToken(token.AccessToken).Build(); PaginatedResult <Template> templates = smartsheetClient.TemplateResources.ListPublicTemplates(null); if (templates.TotalCount > 0) { foreach (Template dataTemplate in templates.Data) { templateSS.Add(dataTemplate.Id.ToString(), dataTemplate.Name); } } return(templateSS); } catch (Exception e) { if (e.Message.Contains(SmartsheetConstants.SSConstants.EXPIRED_TOKEN_MESSAGE)) { MyProfileMaint profileMaintGraph = PXGraph.CreateInstance <MyProfileMaint>(); MyProfileMaintExt graphExtended = profileMaintGraph.GetExtension <MyProfileMaintExt>(); string updatedToken = graphExtended.RefreshSmartsheetToken(); return(GetTemplateSS(updatedToken)); } else { throw new PXException(e.Message); } } }
private static void ListWorkspaces(SmartsheetClient smartsheet, long workspaceId) { PaginatedResult <Workspace> workspaceResult = smartsheet.WorkspaceResources.ListWorkspaces(null); Assert.IsTrue(workspaceResult.Data.Count > 0); bool contains = false; foreach (Workspace ws in workspaceResult.Data) { if (ws.Id.Value == workspaceId) { contains = true; break; } } Assert.IsTrue(contains); }
private List <ChangeHistorySearchItem> ConvertEstablishmentChanges(PaginatedResult <EstablishmentChangeDto> changes, string estabName) { return(new List <ChangeHistorySearchItem>( changes.Items.Select(i => new ChangeHistorySearchItem { EstablishmentName = estabName, SuggesterName = i.OriginatorUserName, ApproverName = i.ApproverUserName, EffectiveDate = i.EffectiveDateUtc, RequestedDate = i.RequestedDateUtc, DateChanged = i.ChangedDateUtc, EstablishmentUrn = i.Urn, FieldName = i.Name, OldValue = i.OldValue, NewValue = i.NewValue }).ToList())); }
public async Task <PaginatedResult <TransactionBidVm> > Handle(GetAllTransactionBidQuery request, CancellationToken cancellationToken) { if (!(await _bidService.AnyByIdAsync(request.BidId))) { return(PaginatedResult <TransactionBidVm> .Empty(request.PageSize, request.PageNumber)); } return(await _dbContext.TransactionBids.AsQueryable() .Where(x => x.BidId == request.BidId) .OrderByDescending(x => x.Amount) .Select(x => new TransactionBidVm { Amount = x.Amount, Owner = _userService.GetUsername(new Guid(x.CreatedBy)) }) .ToPaginatedListAsync(request.PageNumber, request.PageSize)); }
public async override Task<IActionResult> ListFunctionsAsync([FromQuery]int page, [FromQuery][Range(1, 20)]int size, [FromQuery]bool includeRelations, [FromQuery][StringLength(255, MinimumLength = 0)]string filterName, [FromQuery]string orderBy) { List<KeyValuePair<string, string>> orderByKeyValueList = orderByHelper.ConvertCommaSeparateOrderByStringToKeyValuePairList(orderBy); // Validate only correct order by components were supplied. orderByHelper.ValidateOrderByListOnlyContainsCertainElements(orderByKeyValueList, new List<string> { "name" }); PaginatedResult<FunctionModel> paginatedResult = await functionService.GetPaginatedListAsync(page, size, includeRelations, filterName, orderByKeyValueList); // Generate a K-V pair of all the current applied filters sent to the controller so that pagination header URLs can include them. List<KeyValuePair<string, string>> currrentFilters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("includeRelations", includeRelations ? "true" : "false"), new KeyValuePair<string, string>("filterName", filterName) }; paginationHelper.AddPaginationHeaderMetaDataToResponse(paginatedResult, currrentFilters, orderBy, "ListFunctions", Url, Response); return Ok(mapper.Map<List<Function>>(paginatedResult.Results)); }
public void TestDiscussionResources() { string accessToken = ConfigurationManager.AppSettings["accessToken"]; SmartsheetClient smartsheet = new SmartsheetBuilder().SetAccessToken(accessToken).Build(); long sheetId = CreateSheet(smartsheet); Discussion discussionToCreate = new Discussion.CreateDiscussionBuilder("A discussion", new Comment.AddCommentBuilder("a comment").Build()).Build(); Discussion createdDiscussion = smartsheet.SheetResources.DiscussionResources.CreateDiscussion(sheetId, discussionToCreate); long createdDiscussionId = createdDiscussion.Id.Value; string path = "../../../IntegrationTestSDK/TestFile.txt"; Discussion createdDiscussionWithFile = smartsheet.SheetResources.DiscussionResources.CreateDiscussionWithAttachment(sheetId, discussionToCreate, path, null); Assert.IsTrue(createdDiscussionWithFile.Comments[0].Attachments[0].Name == "TestFile.txt"); PaginatedResult <Discussion> discussions = smartsheet.SheetResources.DiscussionResources.ListDiscussions(sheetId, new DiscussionInclusion[] { DiscussionInclusion.COMMENTS, DiscussionInclusion.ATTACHMENTS }, null); Assert.IsTrue(discussions.TotalCount == 2); Assert.IsTrue(discussions.Data.Count == 2); Assert.IsTrue(discussions.Data[0].Id.Value == createdDiscussion.Id.Value || discussions.Data[0].Id.Value == createdDiscussionWithFile.Id.Value); Assert.IsTrue(discussions.Data[1].Id.Value == createdDiscussion.Id.Value || discussions.Data[1].Id.Value == createdDiscussionWithFile.Id.Value); Discussion getDiscussionWithFile = smartsheet.SheetResources.DiscussionResources.GetDiscussion(sheetId, createdDiscussionWithFile.Id.Value); Assert.IsTrue(getDiscussionWithFile.Title == "A discussion"); Assert.IsTrue(getDiscussionWithFile.Comments.Count == 1); Assert.IsTrue(getDiscussionWithFile.Comments[0].Attachments.Count == 1); Assert.IsTrue(getDiscussionWithFile.Comments[0].Attachments[0].Name == "TestFile.txt"); Row row = new Row.AddRowBuilder(true, null, null, null, null).Build(); IList <Row> rows = smartsheet.SheetResources.RowResources.AddRows(sheetId, new Row[] { row }); Assert.IsTrue(rows.Count == 1); Assert.IsTrue(rows[0].Id.HasValue); long rowId = rows[0].Id.Value; Comment comment = new Comment.AddCommentBuilder("a comment!").Build(); Discussion discussionToCreateOnRow = new Discussion.CreateDiscussionBuilder("discussion on row", comment).Build(); Discussion discussionCreatedOnRow = smartsheet.SheetResources.RowResources.DiscussionResources.CreateDiscussionWithAttachment(sheetId, rowId, discussionToCreateOnRow, path, null); PaginatedResult <Discussion> discussionsOnRow = smartsheet.SheetResources.RowResources.DiscussionResources .ListDiscussions(sheetId, rowId, new DiscussionInclusion[] { DiscussionInclusion.COMMENTS }, null); Assert.IsTrue(discussionsOnRow.Data.Count == 1); Assert.IsTrue(discussionsOnRow.Data[0].Title == "discussion on row"); Assert.IsTrue(discussionsOnRow.Data[0].Comments[0].Text == "a comment!"); }
public async Task PresenceExample() { var options = new ClientOptions("{{API_KEY}}") { ClientId = "bob" }; var realtime = new AblyRealtime(options); var channel = realtime.Channels.Get("{{RANDOM_CHANNEL_NAME}}"); channel.Presence.Subscribe(member => Console.WriteLine("Member " + member.ClientId + " : " + member.Action)); await channel.Presence.EnterAsync(null); /* Subscribe to presence enter and update events */ channel.Presence.Subscribe(member => { switch (member.Action) { case PresenceAction.Enter: case PresenceAction.Update: { Console.WriteLine(member.Data); // => travelling North break; } } }); /* Enter this client with data and update once entered */ await channel.Presence.EnterAsync("not moving"); await channel.Presence.EnterAsync("travelling North"); IEnumerable <PresenceMessage> presence = await channel.Presence.GetAsync(); Console.WriteLine($"There are {presence.Count()} members on this channel"); Console.WriteLine($"The first member has client ID: {presence.First().ClientId}"); PaginatedResult <PresenceMessage> resultPage = await channel.Presence.HistoryAsync(untilAttach : true); Console.WriteLine(resultPage.Items.Count + " presence events received in first page"); if (resultPage.HasNext) { PaginatedResult <PresenceMessage> nextPage = await resultPage.NextAsync(); Console.WriteLine(nextPage.Items.Count + " presence events received in 2nd page"); } }
private static void ListGroups(SmartsheetClient smartsheet) { PaginatedResult <Group> groups = smartsheet.GroupResources.ListGroups(null); // Don't actually know that there is only one group if its a test account // Assert.IsTrue(groups.Data.Count == 1); bool found = false; foreach (Group group in groups.Data) { if (group.Name == "a group") { found = true; break; } } Assert.IsTrue(found); }
public async Task ListUsersAsync_WithNoInputs_ReturnsList() { // Arrange var inList = new List <UserModel>(); inList.Add(new UserModel { FirstName = "Test Users 1", Id = Guid.NewGuid().ToString() }); inList.Add(new UserModel { FirstName = "Test Users 2", Id = Guid.NewGuid().ToString() }); inList.Add(new UserModel { FirstName = "Test Users 3", Id = Guid.NewGuid().ToString() }); PaginatedResult <UserModel> paginatedResult = new PaginatedResult <UserModel> { CurrentPage = 1, PageCount = 1, PageSize = 3, Results = inList }; userService.GetPaginatedListAsync(Arg.Any <int>(), Arg.Any <int>(), Arg.Any <bool>(), Arg.Any <string>(), Arg.Any <string>(), Arg.Any <List <KeyValuePair <string, string> > >()).Returns(paginatedResult); var controller = new UserController(userService, profileService, paginationHelper, orderByHelper, mapper); // Act IActionResult actionResult = await controller.ListUsersAsync(false, 1, 10, string.Empty, string.Empty, string.Empty); // Assert var okResult = actionResult as OkObjectResult; Assert.NotNull(okResult); var outList = okResult.Value as List <User>; Assert.NotNull(outList); for (var i = 0; i < outList.Count; i++) { Assert.Equal(outList[i].Uuid.ToString(), inList[i].Id); Assert.Equal(outList[i].Name, inList[i].FirstName); } }
public static async Task Test() { ConsoleColor.DarkGreen.WriteLine("Creating sandbox app.."); ConsoleColor.DarkGreen.WriteLine("Creating REST client.."); // Create REST client using that key AblyRest ably = new AblyRest(new ClientOptions() { AuthUrl = new Uri("https://www.ably.io/ably-auth/token-request/demos"), Tls = false }); ConsoleColor.DarkGreen.WriteLine("Publishing a message.."); // Verify we can publish IRestChannel channel = ably.Channels.Get("persisted:presence_fixtures"); var tsPublish = DateTimeOffset.UtcNow; await channel.PublishAsync("test", true); ConsoleColor.DarkGreen.WriteLine("Getting the history.."); PaginatedResult <Message> history = await channel.HistoryAsync(); if (history.Items.Count <= 0) { throw new ApplicationException("Message lost: not on the history"); } Message msg = history.Items.First(); var tsNow = DateTimeOffset.UtcNow; var tsHistory = msg.Timestamp.Value; if (tsHistory < tsPublish) { throw new ApplicationException("Timestamp's too early. Please ensure your PC's time is correct, use e.g. time.nist.gov server."); } if (tsHistory > tsNow) { throw new ApplicationException("Timestamp's too late, Please ensure your PC's time is correct, use e.g. time.nist.gov server."); } ConsoleColor.DarkGreen.WriteLine("Got the history"); }
public static PaginatedResult <ProductModel> GetPaginatedProducts(SearchRequestModel searchCriteria) { var sessionContext = DependencyResolver.Current.GetService <ISessionContext>(); searchCriteria.CurrentPage = searchCriteria.CurrentPage == 0 ? 1 : searchCriteria.CurrentPage; searchCriteria.PageSize = searchCriteria.PageSize == 0 ? Convert.ToInt32(ConfigKeys.PageSize) : searchCriteria.PageSize; searchCriteria.SortBy = string.IsNullOrWhiteSpace(searchCriteria.SortBy) ? sessionContext?.CurrentSiteConfig?.SearchSettings?.DefaultSortBy : searchCriteria.SortBy; var productApi = DependencyResolver.Current.GetService <IProductApi>(); var response = productApi.GetProducts(searchCriteria); var result = new PaginatedResult <ProductModel>(); if (response != null && response.Result != null) { result = response.Result; } result.SearchCriteria = searchCriteria; if (result.Filters == null) { return(result); } var validFilters = result.Filters.GroupBy(c => new { c.Name }).Select(c => c.First()).ToList(); result.Filters = validFilters; // result.Filters = validFilters.Where(p => !validFilters.Any(p2 => p2.Name == p.Name && p.Items.Count == 0)).ToList(); if (result.Filters != null) { foreach (var filter in result.Filters) { foreach (var itm in filter.Items) { if (filter.Name != null && filter.Name.ToLower() == Constants.PRICE_FILTER && itm.From != null) { itm.PriceFilter = ((int)Convert.ToDecimal(itm.From)); } if (searchCriteria.Filters != null) { itm.IsSelected = searchCriteria.Filters.Any(x => x.Key == filter.Key && x.Value == itm.Name); } } filter.Items = filter.Items.GroupBy(x => x.Name).Select(x => x.FirstOrDefault()).ToList(); filter.Items = filter.Items.OrderByDescending(x => x.IsSelected).ThenBy(x => x.DisplayOrder).ThenBy(x => x.Name).ToList(); } } return(result); }
public async Task ListTermsOfServicesAsync_WithNoInputs_ReturnsList() { // Arrange var inList = new List <TermsOfServiceModel> { new TermsOfServiceModel { AgreementName = "Test TermsOfServices 1", Id = Guid.NewGuid() }, new TermsOfServiceModel { AgreementName = "Test TermsOfServices 2", Id = Guid.NewGuid() }, new TermsOfServiceModel { AgreementName = "Test TermsOfServices 3", Id = Guid.NewGuid() } }; PaginatedResult <TermsOfServiceModel> paginatedResult = new PaginatedResult <TermsOfServiceModel> { CurrentPage = 1, PageCount = 1, PageSize = 3, Results = inList }; termsOfServiceService.GetPaginatedListAsync(Arg.Any <int>(), Arg.Any <int>(), Arg.Any <bool>(), Arg.Any <string>(), Arg.Any <List <KeyValuePair <string, string> > >()).Returns(paginatedResult); var controller = new TermsOfServiceController(termsOfServiceService, orderByHelper, paginationHelper, mapper); // Act IActionResult actionResult = await controller.ListTermsOfServicesAsync(0, 0, true, string.Empty, string.Empty); // Assert var okResult = actionResult as OkObjectResult; Assert.NotNull(okResult); var outList = okResult.Value as List <TermsOfServiceListItem>; Assert.NotNull(outList); for (var i = 0; i < outList.Count; i++) { Assert.Equal(outList[i].Uuid, inList[i].Id); Assert.Equal(outList[i].AgreementName, inList[i].AgreementName); } }
protected PaginatedResult <T> CreateResponse(ISmartSearchQueryRequest request, QueryResult <T> qr) { PaginatedResult <T> retVal = new PaginatedResult <T>() { Data = new List <T>() }; retVal.Data = qr.Data; retVal.TotalItems = qr.Statistics.TotalResults; retVal.TotalPages = retVal.TotalItems / request.PageSize; if ((retVal.TotalItems % request.PageSize) > 0) { retVal.TotalPages += 1; } retVal.PageSize = request.PageSize; retVal.CurrentPage = request.CurrentPage; return(retVal); }
public virtual void TestListShares() { server.setResponseBody("../../../TestSDK/resources/listShares.json"); PaginatedResult<Share> result = shareResourcesImpl.ListShares(2906571706525572L, new PaginationParameters(false, 100, 1)); Assert.True(result.Data.Count == 2, "The number of shares returned is incorrect."); Assert.AreEqual("*****@*****.**", result.Data[0].Email, "Email attribute of the share is incorrect."); Assert.AreEqual(null, result.Data[1].Email, "Email attribute of the share is incorrect."); Assert.IsTrue(AccessLevel.OWNER == result.Data[0].AccessLevel); Assert.IsTrue(ShareType.USER == result.Data[0].Type); Assert.IsTrue(2331373580117892 == result.Data[1].GroupId); Assert.IsTrue(ShareType.GROUP == result.Data[1].Type); Assert.IsTrue("AQAISF82FOeE" == result.Data[1].Id); Assert.IsTrue(AccessLevel.ADMIN == result.Data[1].AccessLevel); }
public IActionResult GetNotesPaginated(int pid, int page = 0, int pageSize = 10) { var notes = _dataService.GetNotes(pid, page, pageSize, out var totalResults); var result = new PaginatedResult <Note> { TotalResults = totalResults, ShowingResults = "Showing results " + (page * pageSize + 1) + "-" + (page + 1) * pageSize + ".", PreviousPage = page > 0 ? Url.Link(nameof(GetNotes), new { page = page - 1, pageSize }) : null, NextPage = (page + 1) * pageSize < totalResults ? Url.Link(nameof(GetNotes), new { page = page + 1, pageSize }) : null, Results = notes }; return(Ok(result)); }
/// <summary> /// Fetches multiple media entries /// </summary> /// <param name="companyId">The company id to query against</param> /// <param name="page">The current page number</param> /// <param name="count">The page size</param> /// <returns>Returns a result containing an optional list of items</returns> public async Task <Result <Maybe <PaginatedResult <MediaEntry> > > > FetchCountedCompanyMediaEntries(int companyId, int page, int count) { try { const string cquery = @"select count(*) from ( select i.imageid as id from ""Image"" i where i.companyId = @CompanyId union all select d.documentid as id from ""Document"" d where d.companyId = @CompanyId order by id ) total"; const string query = @"select i.imageid as id, i.companyid as companyid, i.imagekey as key, i.imagetitle as title, CAST(1 as int) as mediatype from ""Image"" i where i.companyId = @CompanyId union all select d.documentid as id, d.companyid as companyid, d.documentkey as key, d.documenttitle as title, CAST(2 as int) as mediatype from ""Document"" d where d.companyId = @CompanyId order by id limit 20 offset 0"; using var con = new Npgsql.NpgsqlConnection(settings.Connection.DatabaseConnectionString); using var obj = await con.QueryMultipleAsync($"{cquery}; {query}", new { Limit = count, Offset = page *count, CompanyId = companyId }).ConfigureAwait(false); var totalCount = obj.Read <int>().Single(); var data = obj.Read <MediaEntry>().ToList(); var paginatedData = new PaginatedResult <MediaEntry> { Data = data ?? new List <MediaEntry>(), Count = totalCount }; return(Result.Ok(Maybe <PaginatedResult <MediaEntry> > .From(paginatedData))); } catch (Exception ex) { return(Result.Fail <Maybe <PaginatedResult <MediaEntry> > >(ex.ToString())); } }
public async Task <PaginatedResult <ContractorForList> > Handle(GetContractorsListQuery request, CancellationToken cancellationToken) { var contractorsQuery = _dbContext.Contractors .Include(x => x.Location) .Include(x => x.RepairServices) .ThenInclude(x => x.Opinions) .Include(x => x.RepairServices) .ThenInclude(x => x.SubCategory) .Include(x => x.RepairServices) .ThenInclude(x => x.SubCategory.Category) .Include(x => x.Image) .Include(x => x.SubscriptionStatus) .AsNoTracking(); if (request.ContractorsListFilter.SubcategoryId.HasValue) { contractorsQuery = contractorsQuery.Where(x => x.RepairServices.Any(y => y.SubCategoryId == request.ContractorsListFilter.SubcategoryId.Value)); } if (!string.IsNullOrEmpty(request.ContractorsListFilter.PlaceId)) { contractorsQuery = contractorsQuery.Where(x => x.Location.PlaceId == request.ContractorsListFilter.PlaceId); } if (!string.IsNullOrEmpty(request.ContractorsListFilter.NameSearchString)) { var searchString = request.ContractorsListFilter.NameSearchString.ToLower(); contractorsQuery = contractorsQuery.Where(x => x.FirstName.ToLower().Contains(searchString) || x.LastName.ToLower().Contains(searchString)); } var paginatedEntities = new PaginatedResult <Contractor>(contractorsQuery, request.PagingParams.PageNumber, request.PagingParams.PageSize); return(new PaginatedResult <ContractorForList> { PageNumber = paginatedEntities.PageNumber, PageSize = paginatedEntities.PageSize, TotalItems = paginatedEntities.TotalItems, TotalPages = paginatedEntities.TotalPages, Result = _mapper.Map <List <ContractorForList> >(paginatedEntities.Result) }); }
/// <inheritdoc/> public async Task <PaginatedResult <T> > GetPaginatedResultAsync <T>(Expression <Func <T, bool> > predicate = null, IList <ISort> sort = null, int page = 0, int resultsPerPage = 10, IDbConnection connection = null, IDbTransaction transaction = null) where T : class { if (connection == null) { using (connection = await _factory.CreateAsync()) { return(PaginatedResult <T> .Create( await connection.CountAsync(predicate, transaction, _commandTimeout), await connection.GetPageAsync(predicate, sort, page, resultsPerPage, transaction, _commandTimeout))); } } else { return(PaginatedResult <T> .Create( await connection.CountAsync(predicate, transaction, _commandTimeout), await connection.GetPageAsync(predicate, sort, page, resultsPerPage, transaction, _commandTimeout))); } }
public virtual void TestListAttachments() { server.setResponseBody("../../../TestSDK/resources/listAttachments.json"); PaginatedResult <Attachment> result = sheetAttachmentResource.ListAttachments(56545654, null); Assert.IsTrue(result.Data[0].AttachmentType == AttachmentType.FILE); Assert.IsTrue(result.Data[0].MimeType == "image/png"); Assert.IsTrue(result.Data[0].Id == 4583173393803140); Assert.IsTrue(result.Data[0].ParentType == AttachmentParentType.SHEET); Assert.IsTrue(result.Data[0].Name == "att3.png"); Assert.IsTrue(result.Data[0].ParentId == 341847495283); Assert.IsTrue(result.Data[1].AttachmentType == AttachmentType.FILE); Assert.IsTrue(result.Data[1].MimeType == "image/png"); Assert.IsTrue(result.Data[1].Id == 4583173393803140); Assert.IsTrue(result.Data[1].ParentType == AttachmentParentType.ROW); Assert.IsTrue(result.Data[1].Name == "att4.png"); Assert.IsTrue(result.Data[1].ParentId == 684956754834557); }
public OperationResult <PaginatedResult <EventDto> > Filter(EventFilter filter) { var predicate = _filterBuilder.Build(filter); var query = _repository.Get(predicate); var total = query.Count(); if (filter.IsPaged) { query = query .OrderBy(c => c.Id) .Skip(filter.Skip) .Take(filter.Take); } var events = query.ProjectTo <EventDto>().ToList(); var result = new PaginatedResult <EventDto>(events, total); return(OperationResult.Success(result)); }
public async Task <PaginatedResult <LineTotalAndOrderQtySumPerDayDto, LineTotalAndOrderQtySumPerTimePeriodDto> > GetLineTotalAndOrderQuantitySumPerDay ( DateTime startDate, DateTime endDate, PaginationData paginationData ) { var startData = _purchaseOrderDetailRepository.All(); var dataInDateRange = startData .Where ( x => x.DueDate >= startDate.Date && x.DueDate <= endDate.Date ).Select(x => new { x.DueDate, x.LineTotal, x.OrderQty }); var groupedByDayWithSum = dataInDateRange.GroupBy(x => x.DueDate) .Select ( grp => new LineTotalAndOrderQtySumPerDayDto { Date = grp.Key, LineTotalSum = grp.Sum(a => a.LineTotal) ?? 0, OrderQtySum = grp.Sum(b => b.OrderQty) } ); var paginated = await Paginate(groupedByDayWithSum, paginationData, x => x.Date); var result = new PaginatedResult <LineTotalAndOrderQtySumPerDayDto, LineTotalAndOrderQtySumPerTimePeriodDto> { PaginationData = paginated.PaginationData, Result = paginated.Result, AdditionalData = new LineTotalAndOrderQtySumPerTimePeriodDto() { LineTotalSumPerPeriod = paginated.Result.Sum(x => x.LineTotalSum), OrderQtySumPerPeriod = paginated.Result.Sum(x => x.OrderQtySum) } }; return(result); }
public void TestCellResources() { string accessToken = ConfigurationManager.AppSettings["accessToken"]; SmartsheetClient smartsheet = new SmartsheetBuilder().SetAccessToken(accessToken).Build(); long sheetId = CreateSheet(smartsheet); PaginatedResult <Column> columnsResult = smartsheet.SheetResources.ColumnResources.ListColumns(sheetId, null, null); long columnId = columnsResult.Data[0].Id.Value; Cell[] cellsToAdd = new Cell[] { new Cell.AddCellBuilder(columnId, true).SetValue("hello").SetStrict(false).Build() }; long rowId = AddRows(smartsheet, sheetId, columnId, cellsToAdd); PaginatedResult <CellHistory> histories = smartsheet.SheetResources.RowResources.CellResources.GetCellHistory(sheetId, rowId, columnId, new CellInclusion[] { CellInclusion.COLUMN_TYPE }, null); Assert.IsTrue(histories.Data[0].ColumnType == ColumnType.TEXT_NUMBER); Assert.IsTrue(histories.Data.Count == 1); Assert.IsTrue(histories.Data[0].ColumnId == columnId); }
public async Task <PaginatedResult <ProdutoViewModel> > Handle(GetListaProdutosQuery request, CancellationToken cancellationToken) { var paginatedResult = await _produtoRepository .FindAllPaginatedAsync(new PaginationOptions(request.PageIndex, request.PageSize, request.Sort)); PaginatedResult <ProdutoViewModel> result = new PaginatedResult <ProdutoViewModel>( paginatedResult.Data.Select(x => new ProdutoViewModel { Id = x.Id, Descricao = x.Descricao, Valor = x.Valor }), paginatedResult.DataLenght, paginatedResult.PageIndex, paginatedResult.PageSize, paginatedResult.TotalPages); return(result); }
/// <summary> /// /// </summary> /// <param name="idchannel"></param> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public PaginatedResult <Video> Get(int idchannel, DateTime start) { string fQuery = @" SELECT TOP 1 [V].* FROM [Video] AS [V] WHERE [V].[IdChannel] = @idchannel AND [V].[CreatedAt] >= @start ORDER BY [V].[CreatedAt] ASC;"; var res = base.Context.QueryFirstOrDefault <Video>(fQuery, new { idchannel, start }); string qNext = @"SELECT TOP 1 * FROM [Video] WHERE [IdChannel] = @idchannel AND [Id] > @id ORDER BY [Id] ASC;"; string qPrev = @"SELECT TOP 1 * FROM [Video] WHERE [IdChannel] = @idchannel AND [Id] < @id ORDER BY [Id] DESC;"; if (res != null) { Video nVideo = base.Context.QueryFirstOrDefault <Video>(qNext, new { idchannel, res.Id }); Video pVideo = base.Context.QueryFirstOrDefault <Video>(qPrev, new { idchannel, res.Id }); var retorno = new PaginatedResult <Video>(); retorno.Video = res; if (nVideo != null) { retorno.next = nVideo.Id; } if (pVideo != null) { retorno.prev = pVideo.Id; } Channel ch = base.Context.Get <Channel>(idchannel); retorno.Url = $"{this.url}{ch.Folder}/{retorno.Video.FilePath}/{retorno.Video.FileName}"; return(retorno); } else { return(new PaginatedResult <Video>()); } }
public UserListInfo(int pageIndex, int pageSize, PaginatedResult<User> results) : this() { this.Users = new PaginatedInfo<User>(pageIndex, pageSize, results); }