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

Hi All,
Let’s continue our Microsoft Graph show. In last article we discussed about Azure Access Token, we require for calling Graph APIs.
If you missed the previous articles, here are those, 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 3 – Azure Access Token: to call Graph APIs from CSOM
We are discussing one use case – listing all O365 groups. We have prerequisites are in place:
- We choose development environment – Visual Studio 2017 + CSOM SDK
- We have registered App in Azure AD
- We have Azure App Id and generated client secret key
- We have configured permissions for above created app to use Graph APIs for fetching Office 365 groups – we have granted “Read All” permissions for groups
- In last article we discussed how to get “Azure Access Token”
Now time to call actual GRAPH API and see the result.
Following are the detailed steps:
Start the Visual Studio 2017, create console application, let’s say “knowledge-junction” as

Figure 1: Office 365 – Microsoft Graph – Console Application – to fetch all Office 365 groups
Install require packages using NuGet manager
Open the NuGet manager as

Figure 2: Office 365 – Microsoft Graph – Installing required packages for calling Graph APIs
We will require following packages:
- Microsoft Graph – Microsoft.Graph – client library allows to call us Office 365, Azure AD, and other Microsoft Services through single unified developer experience as

Figure 3: Office 365 – Microsoft Graph – Installing “Microsoft.Graph” client library
Click on “Install” button and please make sure the package installed successfully. We can make sure from OutPut window. And also verify in references section in Solution Explorer as

Figure 4: Office 365 – Microsoft Graph – references are added for ‘Microsoft Graph” package
- Microsoft Identity Client Active Directory – Contains the binaries of the Active Directory Authentication library (ADAL). ADAL provides easy to use authentication functionality for .NET based client by taking advantage of Windows Server Active Directory and Azure Active Directory.

Figure 5: Office 365 – Microsoft Graph – Installing “Microsoft Identity Model Client Active Directory” package
Click on “Install” button and please make sure the package installed successfully. We can make sure from OutPut window. And verify in references section in Solution Explorer as

Figure 6: Office 365 – Microsoft Graph – references are added for “Microsoft.IndentityModel.Clients.ActiveDirectory” assembly
Once we have required packages are in place, we can call “Microsoft Graph” APIs.
We need to override the method – AuthenticateRequestAsync(HttpRequestMessage request) from IAuthenticationProvider interface – which adds the “Azure Access Token” to header of HttpRequestMessage request object. We discussed this in our last article.
To achieve this we will add new class in our solution which will be derived from IAuthenticationProvider as
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http;
using System.Threading.Tasks;
namespace knowledge_junction
{
class AuthenticationProvider : IAuthenticationProvider
{
/// <summary>
/// Method to set the access token to HttpRequestMessage header
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
//Azure App ID
string clientId = "";
string clientSecretKey = "";
string authority = "https://login.windows.net/<OUR TENANT ID>";
AuthenticationContext authenticationContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);
AuthenticationResult authResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/", clientCredential);
//Setting the token in header of HttpRequestMessage object
request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
}//AuthenticateRequestAsync
}//cs
}//ns

Figure 7: Office 365 – Microsoft Graph – Overriding “AuthenticateRequestAsync” method from IAuthenticationProvider
Next step is to create instance of GraphServiceClient, this class is part of “Microsoft Graph” library as
GraphServiceClient graphServiceClient = new GraphServiceClient(new AuthenticationProvider());
Once we have instance of GraphServiceClient instance ready we can fetch groups as
IGraphServiceGroupsCollectionPage graphServiceGroupsCollectionPage = await graphServiceClient.Groups.Request().GetAsync();
IList<Group> groups = new List<Group>();
groups = graphServiceGroupsCollectionPage.CurrentPage;
Complete code:
IGraphServiceGroupsCollectionPage graphServiceGroupsCollectionPage = null;
IList<Group> groups = new List<Group>();
Task.Run(async () =>
{
try
{
graphServiceGroupsCollectionPage = await graphServiceClient.Groups.Request().GetAsync();
groups = graphServiceGroupsCollectionPage.CurrentPage;
}
catch (Exception _ex)
{
Console.Write(_ex.Message);
}
}).Wait();
Once we have all groups, we can iterate through those and write to console / .CSV file / Mail to admin as
foreach (Group group in groups)
{
Console.WriteLine(group.DisplayName);
}

Figure 8: Office 365 – Microsoft Graph – CodeBase to fetch all Office 365 groups using CSOM
References:
Intro to the Microsoft Graph .NET Client Library
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

3 Responses
[…] last article “Office 365 – Microsoft Graph – Part 4 – Fetching all Office 365 groups using CSOM- Codebase” we went through the CSOM code base to fetch all Office 365 groups. We had simple use case and […]
[…] CSOMOffice 365 – Microsoft Graph – Part 3 – Azure Access Token: to call Graph APIs from CSOMOffice 365 – Microsoft Graph – Part 4 – Fetching all Office 365 groups using CSOM- CodebaseOffice 365 – Microsoft Graph – Part 5 – Fetching Office 365 group owners using CSOM – […]
… [Trackback]
[…] Informations on that Topic: knowledge-junction.com/2018/12/25/office-365-microsoft-graph-part-4-fetching-all-office-365-groups-using-csom-codebase/ […]