Paging with "ActiveRecord for Azure" – The missing Skip()

To get the first N of entities matching your query is really simple with the Data Services Client - you just call the Take() method on your query. But to get the next page of matches is a little more cumbersome since Skip() isn't supported. The Azure Tables way of doing this is to add the NextPartitionKey and NextRowKey HTTP-Headers to your request. That also requires you to extract those headers from the first response in order to be able to send them with the next request. It's not hard to implement this but wouldn't it be easier to just use Skip()? My "ActiveRecord for Azure" sample brings this to the table.

First of - the ActiveRecord base class exposes a Paged method. Allowing you to easily get a paged list of the specific entity.

 [Fact]
public void it_returns_the_given_number_of_entities() {

    var pageSize = 5;

    var entities = FakeEntity.Paged(pageSize);

    Assert.Equal(pageSize, entities.Count());
}

Second, The PagedList contains a NextPageToken property containing the ContinuationToken for the text page (if there’s one).

 [Fact]
public void it_returns_a_page_token_for_the_next_page()
{
    var pageSize = 5;

    var entities = FakeEntity.Paged(pageSize);

    Assert.Equal("6@partition", entities.NextPageToken.Token);
}

Under the hood this is performed by my Skip method implemented as a IQueryable extensions – so the same code works for your unit tests and for “real” DataServiceQueries 

 public static IPagedList<TEntity> Paged(int pageSize, string pageToken) {
    return ActiveRecordContext.Current
        .CreateQuery<TEntity>()
        .Skip(pageToken)
        .Take(pageSize)
        .ToPagedList();
}

Using this in an application might look something like this

 public ActionResult Index(string page) {

    if(string.IsNullOrEmpty(page))
        return View(Task.Paged(PageSize)); 

    return View(Task.Paged(PageSize, page));
}

The “ActiveRecord for Azure” sample code is available here. A sample application using “ActiveRecord for Azure” is available here.