Morten_564834
Morten_564834

Reputation: 1667

Graph paging example

Based on the Reference doc, can anyone give a short example of how to actually implement a GetAllUsers method client-side using pagination?

Upvotes: 0

Views: 139

Answers (1)

Morten_564834
Morten_564834

Reputation: 1667

Ok so far I implemented it in this recursive way, seems to work. Can probably be simplified, and better error handling etc. But feedback is welcome ! :)

 public async Task<IEnumerable<User>> ListAdGroupMembersAsync(string groupObjectId, ICollection<User> currentPage = null, string nextLink = null, bool start = true )
        {
            var token = await GetToken();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Value);

            // Starting
            string endpoint;
            if (nextLink == null && start)
            {
                currentPage = new Collection<User>();
                endpoint = $"https://graph.microsoft.com/v1.0/groups/{groupObjectId}/members?$top=200&$select=displayName,userPrincipalName,id";
            }
            // Next page
            else if (nextLink != null)
            {
                endpoint = nextLink;
            }
            // ending
            else
            {
                return currentPage;
            }
            try
            {
                var users = await _httpClient.GetFromJsonAsync<Users>(endpoint).ConfigureAwait(false);
                currentPage.AddRange(users.value);
                return await ListAdGroupMembersAsync(groupObjectId, currentPage, users.NextLink, false).ConfigureAwait(false);
            }
            catch (HttpRequestException ex)
            {
                Console.Error.WriteLine("ListAdGroupMembersAsync failed. Users could not be retrieved. Error: " + ex.Message);
            }
            return null;
        }

Model:

using Json = System.Text.Json.Serialization.JsonPropertyNameAttribute;
public class User
    {
        public string Id { get; set; }
        public string DisplayName { get; set; }
        public string UserPrincipalName { get; set; }
    }

    public class Users
    {
        public ICollection<User> value { get; set; }

        [Json("@odata.nextlink")]
        public string NextLink { get; set; }
    }

Upvotes: 1

Related Questions