Office 365 – Microsoft Graph – Part 8 – Getting all users of our tenant using CSOM

Office 365 – Microsoft Graph – CodeBase to fetch all Office 365 users using CSOM
Office 365 – Microsoft Graph – CodeBase to fetch all Office 365 users using CSOM

Hi All,

In last article we discussed removing owner from Office 365 Group.

In this article we will discuss how to get all users of our Office 365 tenant programmatically using CSOM.

In case if you missed the previous articles in this Microsoft Graph series, here is the list, please have a look once

Office 365 – Microsoft Graph and Graph Explorer

Office 365 – Azure Active Directory – Registering/Creating new Azure App – detailed steps

Office 365 – Microsoft Graph beginning – Part 1

Office 365 – Microsoft Graph – Part 2 – Granting permission to Azure Apps to use Microsoft Graph APIs using CSOM

Office 365 – Microsoft Graph – Part 3 – Azure Access Token: to call Graph APIs from CSOM

Office 365 – Microsoft Graph – Part 4 – Fetching all Office 365 groups using CSOM- Codebase

Office 365 – Microsoft Graph – Part 5 – Fetching Office 365 group owners using CSOM – Codebase

Office 365 – Microsoft Graph – Part 6 – Adding Office 365 Group Owner using CSOM – Codebase

Office 365 – Microsoft Graph – Part 7 – Removing owner from Office 365 Group using CSOM – Codebase

In this article we will discuss how to get all users from my Office 365 tenant using Graph APIs using CSOM.

Lets begin our Graph show 🙂

Use case:

We have our Office 365 Intranet application.

We need to synchronize few properties of users from our Azure AD to SharePoint Online user profile properties. To achieve this we have written CSOM application. Here, we need to go through all the users, get their properties and then synchronize with Azure AD properties. For getting all the users we are using GRAPH Apis.

High Level Steps:

  1. Install necessary packages:
    • Microsoft Graph
    • Microsoft Identity Client Active DirectoryInstall following required packages:
  2. Get the Azure Access Token
  3. Add “Azure Access Token” to the header of HttpRequestMesaage request object – for this we need to override the method
     AuthenticateRequestAsync(HttpRequestMessage request) from IAuthenticationProvider interface –
    We discussed this in one of our previous article “Office 365 – Microsoft Graph – Part 3 – Azure Access Token: to call Graph APIs from CSOM
  4. Next step is to create instance of GraphServiceClient, this class is part of Microsoft Graph library
  5. Using GraphServiceClient, fetch all users

CodeBase: From above high level steps, we already discussed step 1-4 in previous articles. Here we will discuss the codebase for fetching all the users

We will create our custom class for representing user as

   /// <summary>
    /// class to represent user object
    /// </summary>
    public partial class AdUser
    {
        public string Email { get; set; }
        public string MobilePhone { get; set; }
        public string CompanyName { get; set; }
        public string UserPrincipalName { get; set; }
        public string OfficeLocation { get; set; }
        ....
        ....
        //Required remaining user properties
    }

Next using GraphServiceClient instance and fetch the users.

We get result in multiple collection of pages, on every page there are 100 users. So we need to iterate through all the pages and get the users. We have one method where we are passing the GraphServiceClient instance, looping through all the result pages and preparing a list of our custom user class as

public List<AdUser> GetAllADUsers(GraphServiceClient graphClient)
 {
            //Request for fetching all users with selected properties
            var request = graphClient.Users.Request(new Option[] {
               new QueryOption("$select", "MobilePhone,CompanyName,UserPrincipalName,OfficeLocation"),
                new HeaderOption("Content-Type", "application/json;charset=utf-8")
            });
            //Result returned in collection of pages. Every page has 100 users
            IGraphServiceUsersCollectionPage usersResultPages = null;
            List<AdUser> allUsers = new List<AdUser>();
            Task.Run(async () =>
            {
                usersResultPages = await request.GetAsync();
                int pageNumber = 0;
                //we will loop through each and every result page, prepeare our AdUser object
                while (usersResultPages != null && usersResultPages.Count > 0)
                {
                    //loop thorugh every user page
                    foreach (var userResultPage in usersResultPages)
                    {
                        AdUser adUser = new AdUser();
                        adUser.CompanyName = userResultPage.CompanyName;
                        adUser.MobilePhone = userResultPage.MobilePhone;
                        adUser.OfficeLocation = userResultPage.OfficeLocation;
                        adUser.UserPrincipalName = userResultPage.UserPrincipalName;
                        allUsers.Add(adUser);
                    }
                    //check if next result page is available
                    if (usersResultPages.NextPageRequest != null)
                        usersResultPage = await usersResultPages.NextPageRequest.GetAsync();
                    else
                        break;
                }
            }).Wait();
            return allUsers;
        }
Office 365 – Microsoft Graph – CodeBase to fetch all Office 365 users using CSOM

Figure 1: Office 365 – Microsoft Graph – CodeBase to fetch all Office 365 users using CSOM

Thanks for reading 🙂

Keep reading, share your thoughts, experiences. Feel free to contact us to discuss more. If you have any suggestion / feedback / doubt, you are most welcome.

Stay tuned on Knowledge-Junction, will come up with more such articles

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

7 Responses

  1. Hi. Some of your links to related entries in this series seems to point to a location on C:\ as in “file:///C:/Prasham/Blogs/Office%20365/Microsoft%20Graph/Office%20365%20%E2%80%93%20Microsoft%20Graph%20%E2%80%93%20Part%203%20%E2%80%93%20Azure%20Access%20Token:%20to%20call%20Graph%20APIs%20from%20CSOM”

  2. CSharpQuestion says:

    Dont think this is accurate: usersResultPage = await usersResultPages.NextPageRequest.GetAsync();

    Should be usersResultPages?

  3. CSharpQuestion says:

    (Line 30)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Microsoft 365

Subscribe now to keep reading and get access to the full archive.

Continue reading