Microsoft 365 – Governance implementation – Exporting Site Collections with Microsoft Graph in a .NET Core Application

“We love life, not because we are used to living but because we are used to loving.”

Greetings, fellow developers! Prepare to unravel the magic of Microsoft Graph API and .NET Core as we delve into the intricacies of fetching and exporting site collections. This tutorial serves as your compass through the vast landscape of Microsoft 365 integration, promising not just functionality but a journey toward mastery. Ready to embark on this coding adventure? Let’s get started!

Key Takeaways from this article

  • Learn to fetch and export site collections step-by-step
  • Covers essential prerequisites, including Microsoft 365 account, Microsoft Entra ID access, and .NET Core SDK
  • Detailed guide on setting up permissions for Microsoft Graph API in the Microsoft Entra ID admin center
  • Real-world use case: Site Collection Explorer application
  • Solve the problem of efficiently accessing and exporting site collection data for analysis
  • Tangible benefits: Enhanced user experience, data analysis, and time-saving through automation
  • Code breakdown for exploring and displaying site collections within the application
  • Event handler definitions, authentication, and error handling explained
  • Export functionality with conversion to a Data Transfer Object (DTO) for structured data representation

Prerequisites

Before diving into the implementation, ensure the following prerequisites are in place:

  • Microsoft 365 Account: We need a Microsoft 365 account to register our application in the Azure portal.
  • Microsoft Entra ID admin center Access: Access to the Microsoft Entra ID admin center is necessary to register the application and obtain authentication credentials.
  • .NET Core SDK: Make sure we have the latest version of the .NET Core SDK installed on our development machine.

Real-World Use Case: Site Collection Explorer

In our development journey, we are creating a Site Collection Explorer application using .NET Core. The goal is to provide users with the ability to explore and export site collections seamlessly. Microsoft Graph API becomes instrumental in achieving this objective.

Scenario:

Problem: Users struggle to efficiently access information about site collections and lack a convenient way to export this data for analysis.

Solution with Microsoft Graph:

  • Explore Site Collections:
    • Utilize Microsoft Graph to fetch a page of site collections.
  • Export to Excel:
    • Convert Microsoft.Graph.Models.Site to a custom SiteDto (Data Transfer Object).
    • Export the site collections, including details like ID and Display Name, to an Excel file.

Tangible Benefits:

  • Enhanced User Experience:
    • Users can easily explore and visualize site collections within the application.
  • Data Analysis and Reporting:
    • The export feature facilitates data analysis and reporting by providing data in a structured Excel format.
  • Time-Saving:
    • Automation through Microsoft Graph reduces manual efforts, saving time for users.

Permissions Required for Microsoft Graph API Integration

  • Before your .NET Core application can seamlessly interact with Microsoft Graph API, it needs the appropriate permissions.
  • This ensures that your application can access the required resources and perform specific actions. Grant the following permissions in the Microsoft Entra ID admin center to enable comprehensive functionality:

Grant Permissions

Navigate to our registered application in the Microsoft Entra ID portal and grant the necessary permissions. If you are unsure how to do this, refer to below guide for step-by-step instructions – https://knowledge-junction.in/2024/01/18/microsoft-entra-registering-new-application-and-assigning-permissions-to-access-microsoft-graph-apis/

Permissions Overview:

  • Delegated Permissions:
    • Sites.Read.All: Allows the application to read items in all site collections on behalf of a signed-in user.
  • Application Permissions:
    • Sites.Read.All: Allows the application to read items in all site collections without a signed-in user.

Why These Permissions?

Sites.Read.All:

  • This permission is crucial for accessing site collections. It enables your application to read data from all site collections, providing the necessary information for exploration and export.

Note:

  • Always follow the principle of least privilege. Only grant the permissions that are essential for your application’s functionalities.
  • Document the permissions thoroughly to understand their implications and ensure compliance with security best practices.

Exploring Site Collections

Let’s break down the code responsible for fetching and displaying site collections within our application.

private async void OnGetSiteCollectionsClick(object sender, RoutedEventArgs e)
{
try
{
// Get the authenticated Graph client
var graphClient = await _graphService.GetAuthenticatedGraphClient();// Fetch a page of site collections
    var siteCollection = await graphClient.Sites.GetAsync();

    var siteCollections = siteCollection?.Value;

    // Display the site collections
    foreach (var site in siteCollections)
    {
        // Access the LastModifiedDateTime property
        DateTimeOffset lastModifiedDateTime = site.LastModifiedDateTime ?? DateTimeOffset.MinValue;
        ResultTextBox.Text += $"ID: {site.Id}, Last Modified: {lastModifiedDateTime.UtcDateTime}, Display Name: {site.DisplayName}\n";
    }
}
catch (Exception ex)
{
    ResultTextBox.Text = $"Error: {ex.Message}";
}

}


Line-by-Line Explanation:


Event Handler Definition:

private async void OnGetSiteCollectionsClick(object sender, RoutedEventArgs e)

  • This method is an event handler triggered when a specific UI element, like a button, is clicked. The async void signature indicates that it can perform asynchronous operations.

Authentication and Graph Client Initialization:


var graphClient = await _graphService.GetAuthenticatedGraphClient();

  • This line obtains an authenticated instance of the Graph client using the _graphService.GetAuthenticatedGraphClient() method. The await keyword ensures that authentication completes before proceeding.

Fetching Site Collections:

var siteCollection = await graphClient.Sites.GetAsync();
var siteCollections = siteCollection?.Value;

  • These lines fetch a page of site collections using the GetAsync method of the Graph client. The siteCollections variable contains the list of site collections.

Displaying Site Collection Information:

foreach (var site in siteCollections)
{
// Access the LastModifiedDateTime property
DateTimeOffset lastModifiedDateTime = site.LastModifiedDateTime ?? DateTimeOffset.MinValue;
ResultTextBox.Text += $"ID: {site.Id}, Last Modified: {lastModifiedDateTime.UtcDateTime}, Display Name: {site.DisplayName}\n";
}

  • This loop iterates through each site in the collection, retrieves information such as ID, Last Modified date, and Display Name, and appends it to the ResultTextBox.

Error Handling:

} catch (Exception ex) {
ResultTextBox.Text = $"Error: {ex.Message}";
}

  • In case of any exceptions during the process, an error message is displayed in the ResultTextBox.

Exporting Site Collections to Excel

Now, let’s delve into the functionality that allows us to export site collections to an Excel file. This part of our application aims to provide users with a convenient way to save and analyze information from Microsoft Graph.

private async void OnExportToExcelClick(object sender, RoutedEventArgs e)
{
try
{
// Get the authenticated Graph client
var graphClient = await _graphService.GetAuthenticatedGraphClient();    
   // Fetch a page of site collections
    var siteCollection = await graphClient.Sites.GetAsync();
    var siteCollections = siteCollection?.Value;

    // Convert Microsoft.Graph.Models.Site to SiteDto
    var siteDtos = siteCollections.Select(site => new SiteDto
    {
        Id = site.Id,
        DisplayName = site.DisplayName,
        // Add other properties as needed
    });

    // Export site collections to Excel
    ExportToExcel(siteDtos, "SiteCollections");
}
catch (Exception ex)
{
    ResultTextBox.Text = $"Error: {ex.Message}";
}
}

Line-by-Line Explanation:

Event Handler Definition:

private async void OnExportToExcelClick(object sender, RoutedEventArgs e)

  • This method serves as the event handler triggered when the “Export to Excel” button is clicked. The async void signature indicates asynchronous operations.

Authentication and Graph Client Initialization:

var graphClient = await _graphService.GetAuthenticatedGraphClient();

  • Obtains an authenticated instance of the Graph client using the _graphService.GetAuthenticatedGraphClient() method. The await keyword ensures authentication completion before proceeding.

Fetching Site Collections:

var siteCollection = await graphClient.Sites.GetAsync();
var siteCollections = siteCollection?.Value;

  • Fetches a page of site collections using the GetAsync method of the Graph client.

Conversion to DTO (Data Transfer Object):

var siteDtos = siteCollections.Select(site => new SiteDto
{
Id = site.Id,
DisplayName = site.DisplayName,
// Add other properties as needed
});

  • Converts each site in the collection to a SiteDto object, likely representing a simplified version of the original site object with specific properties needed for Excel export.

Export to Excel:

ExportToExcel(siteDtos, "SiteCollections");

  • Calls a method ExportToExcel with the collection of SiteDto objects (siteDtos) and a string identifier (“SiteCollections”) to export the data to an Excel file.

Error Handling:

} catch (Exception ex) {
ResultTextBox.Text = $"Error: {ex.Message}";
}

  • In case of any exceptions during the process, an error message is displayed in the ResultTextBox.

SiteDto: A Data Transfer Object (DTO)

  • The SiteDto class represents a Data Transfer Object tailored for our site collection data. It includes properties such as Id and DisplayName, providing a structured format for the data we wish to export to Excel.

// SiteDto Class Definition
public class SiteDto
{
public string Id { get; set; }
public string DisplayName { get; set; }
// Add other properties as needed
}

SiteDto Class Definition:

public class SiteDto
{
public string Id { get; set; }
public string DisplayName { get; set; }
// Add other properties as needed
}

  • Defines the SiteDto class with properties like Id and DisplayName. This class serves as a structured representation of site data for export.

Event Handler Definition:

private async void OnExportToExcelClick(object sender, RoutedEventArgs e)

  • Defines the event handler triggered when the “Export to Excel” button is clicked. The method signature is async void to allow asynchronous operations.

The remainder of the code handles the authentication, fetching of site collections, conversion to SiteDto objects, and the actual export to Excel. It showcases a streamlined approach to exporting data, emphasizing clarity and maintainability.

We have very good / detailed articles on Microsoft Graph. Kindly please have a look. – https://knowledge-junction.in/category/technology-articles/m365/microsoft-graph/

Conclusion

In this tutorial, we’ve explored the integration of Microsoft Graph API in a .NET Core application to fetch and export site collections. The real-world use case of a Site Collection Explorer demonstrates the practical application of these functionalities. Whether it’s exploring site collections or exporting them to Excel, Microsoft Graph API empowers developers to create feature-rich applications that leverage the capabilities of Microsoft 365.

Also get my article updates on my social media handles.

Twitter – https://twitter.com/PrajyotYawalkar?t=oovP0r9FnDtz5nNSJGKO0Q&s=09

LinkedIn – https://www.linkedin.com/in/prajyot-yawalkar-093716224/

Have a wonderful day.

Thanks for reading.

You may also like...

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