Office 365 – Microsoft Graph – Part 8 – Getting all users of our tenant 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:
- Install necessary packages:
- Microsoft Graph
- Microsoft Identity Client Active DirectoryInstall following required packages:
- Get the Azure Access Token
- 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” - Next step is to create instance of GraphServiceClient, this class is part of Microsoft Graph library
- 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;
}
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
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”
Thanks a lot Dennis for noticing this. This happen by mistake. Now corrected the links. Thanks once again.
Dont think this is accurate: usersResultPage = await usersResultPages.NextPageRequest.GetAsync();
Should be usersResultPages?
Its variable, declared on line 9. It can be anything. Let me know if I understood it incorrectly.
Yes, the code snipped doesnt work, usersResultPage is not used in the foreach loop, it’s usersResultPages.
Thanks tho, easy example on how to use the nextpage feature.
(Line 30)