Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft Graph only returning the first 100 Users

I have the below code which returns all users based on a filter. The problem is it only returns 100 users but I know there are a lot more.

private List<User> GetUsersFromGraph()
{
    if (_graphAPIConnectionDetails == null) ReadParametersFromXML();
    if (graphServiceClient == null) graphServiceClient = CreateGraphServiceClient();

    var users = graphServiceClient
        .Users
        .Request()
        .Filter(_graphAPIConnectionDetails.UserFilter)
        .Select(_graphAPIConnectionDetails.UserAttributes)
        .GetAsync()
        .Result
        .ToList<User>();

    return users;
}

the method returns only 100 user objects. My Azure portal admin reports there should be closer to 60,000.

like image 388
gtrivedi Avatar asked Dec 10 '22 02:12

gtrivedi


1 Answers

Most of the endpoints in Microsoft Graph return data in pages, this includes /users.

In order to retrieve the rest of the results you need to look through the pages:

private async Task<List<User>> GetUsersFromGraph()
{
    if (_graphAPIConnectionDetails == null) ReadParametersFromXML();
    if (graphServiceClient == null) graphServiceClient = CreateGraphServiceClient();

    // Create a bucket to hold the users
    List<User> users = new List<User>();

    // Get the first page
    IGraphServiceUsersCollectionPage usersPage = await graphClient
        .Users
        .Request()
        .Filter("filter string")
        .Select("property string")
        .GetAsync();

    // Add the first page of results to the user list
    users.AddRange(usersPage.CurrentPage);

    // Fetch each page and add those results to the list
    while (usersPage.NextPageRequest != null)
    {
        usersPage = await usersPage.NextPageRequest.GetAsync();
        users.AddRange(usersPage.CurrentPage);
    }

    return users;
}

One super important note here, this method is the lest performant way to retrieve data from Graph (or any REST API really). Your app will be sitting there for a long time while it downloads all this data. The proper methodology here is to fetch each page and process just that page before fetching additional data.

like image 179
Marc LaFleur Avatar answered Dec 23 '22 03:12

Marc LaFleur