Zum Fußzeileninhalt springen
.NET HILFE

MS Graph .NET (Funktionsweise für Entwickler)

MS Graph .NET serves as an access data tool for interactions with the Microsoft Graph API, a central piece of the Azure Active Directory (Azure AD) ecosystem. Microsoft Graph is a gateway to data and intelligence in Microsoft 365. It allows developers to access, manage, and analyze data across various Microsoft services. The Microsoft Graph client library simplifies this process by providing a set of methods to interact with the API easily.

IronPDF is a library for generating PDF documents in .NET applications. It converts HTML to PDF, making it useful for creating reports, invoices, and documentation automatically. IronPDF works well with .NET applications, offering a straightforward approach to PDF generation.

Combining MS Graph .NET and IronPDF allows developers to create applications that can manipulate Microsoft 365 data and produce PDF documents. This combination is powerful for developing business applications that require data from Microsoft services and need to present that data in a standardized document format.

Getting Started with MS Graph .NET

Setting Up MS Graph .NET in .NET Projects

To use MS Graph .NET effectively, especially when working with user IDs in .NET Core projects, setting up your .NET project is the first step. Here are the steps:

  1. Open the NuGet Package Manager.
  2. Search for Microsoft.Graph.
  3. Install the Microsoft.Graph package.

MS Graph .NET (How It Works For Developers): Figure 1

This process adds MS Graph .NET to your project. Now, you're ready to start coding with it.

A Basic Code Example

Let's say you want to retrieve the current user's profile information. Here is a simple code example:

// Required namespaces
using Azure.Identity;
using Microsoft.Graph;

// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };

// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// Fetching current user's profile information
var user = await graphClient.Me
    .Request()
    .GetAsync();

// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");
// Required namespaces
using Azure.Identity;
using Microsoft.Graph;

// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };

// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// Fetching current user's profile information
var user = await graphClient.Me
    .Request()
    .GetAsync();

// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");
' Required namespaces
Imports Azure.Identity
Imports Microsoft.Graph

' Defining necessary credentials and scope
Private clientId = "Your_Application_Id"
Private tenantId = "Your_Tenant_Id"
Private clientSecret = "Your_Client_Secret"
Private scopes = { "User.Read" }

' Configuring TokenCredentialOptions for Azure Public Cloud
Private options = New TokenCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}

' Authenticating using client credentials
Private clientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)

' Creating a new instance of GraphServiceClient
Private graphClient = New GraphServiceClient(clientSecretCredential, scopes)

' Fetching current user's profile information
Private user = await graphClient.Me.Request().GetAsync()

' Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!")
$vbLabelText   $csharpLabel

This code snippet demonstrates creating a new instance of GraphServiceClient, utilizing a client secret for Azure AD authentication. It uses client credentials to authenticate. Then, it retrieves the current user's display name. Following this, make sure that MS Graph .NET, alongside your authentication provider configurations, is added to your project.

Features of MS Graph .NET

Retrieve User Emails

To retrieve emails from a user's Microsoft account mailbox, you use the Mail.Read permission. Here is how you can list the most recent emails:

// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10)
    .GetAsync();

// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10)
    .GetAsync();

// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
' Retrieving the top 10 messages from the user's mailbox
Dim messages = Await graphClient.Me.Messages.Request().Top(10).GetAsync()

' Iterating through the messages and printing their subjects
For Each message In messages
	Console.WriteLine($"Subject: {message.Subject}")
Next message
$vbLabelText   $csharpLabel

This code lists the subjects of the top 10 emails in the user's inbox.

Send an Email

Sending an email involves creating a Message object and sending it:

// Creating a message to be sent
var message = new Message
{
    Subject = "Hello from MS Graph .NET",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "Hello, this is a test email."
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "recipient@example.com"
            }
        }
    }
};

// Sending the email
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
// Creating a message to be sent
var message = new Message
{
    Subject = "Hello from MS Graph .NET",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "Hello, this is a test email."
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "recipient@example.com"
            }
        }
    }
};

// Sending the email
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
' Creating a message to be sent
Dim message As New Message With {
	.Subject = "Hello from MS Graph .NET",
	.Body = New ItemBody With {
		.ContentType = BodyType.Text,
		.Content = "Hello, this is a test email."
	},
	.ToRecipients = New List(Of Recipient)() From {
		New Recipient With {
			.EmailAddress = New EmailAddress With {.Address = "recipient@example.com"}
		}
	}
}

' Sending the email
Await graphClient.Me.SendMail(message, Nothing).Request().PostAsync()
$vbLabelText   $csharpLabel

This sends an email with a simple text body.

Managing Calendar Events

To add an event to the user's calendar:

// Creating a calendar event
var @event = new Event
{
    Subject = "Team Meeting",
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = "Discuss project updates."
    },
    Start = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T12:00:00",
        TimeZone = "Pacific Standard Time"
    },
    End = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T14:00:00",
        TimeZone = "Pacific Standard Time"
    },
    Location = new Location
    {
        DisplayName = "Conference Room 1"
    }
};

// Adding the event to the user's calendar
await graphClient.Me.Events
    .Request()
    .AddAsync(@event);
// Creating a calendar event
var @event = new Event
{
    Subject = "Team Meeting",
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = "Discuss project updates."
    },
    Start = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T12:00:00",
        TimeZone = "Pacific Standard Time"
    },
    End = new DateTimeTimeZone
    {
        DateTime = "2024-04-15T14:00:00",
        TimeZone = "Pacific Standard Time"
    },
    Location = new Location
    {
        DisplayName = "Conference Room 1"
    }
};

// Adding the event to the user's calendar
await graphClient.Me.Events
    .Request()
    .AddAsync(@event);
' Creating a calendar event
Dim [event] As [Event] = New [Event] With {
	.Subject = "Team Meeting",
	.Body = New ItemBody With {
		.ContentType = BodyType.Html,
		.Content = "Discuss project updates."
	},
	.Start = New DateTimeTimeZone With {
		.DateTime = "2024-04-15T12:00:00",
		.TimeZone = "Pacific Standard Time"
	},
	.End = New DateTimeTimeZone With {
		.DateTime = "2024-04-15T14:00:00",
		.TimeZone = "Pacific Standard Time"
	},
	.Location = New Location With {.DisplayName = "Conference Room 1"}
}

' Adding the event to the user's calendar
Await graphClient.Me.Events.Request().AddAsync([event])
$vbLabelText   $csharpLabel

This code schedules a new event in the calendar.

Accessing OneDrive Files

To list files from the root of the user's OneDrive:

// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();

// Printing each file's name
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();

// Printing each file's name
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
' Retrieving files from the root OneDrive folder
Dim files = Await graphClient.Me.Drive.Root.Children.Request().GetAsync()

' Printing each file's name
For Each file In files
	Console.WriteLine(file.Name)
Next file
$vbLabelText   $csharpLabel

This code prints the names of the files in the root directory of OneDrive.

Working with Teams

To retrieve the list of teams the user is part of:

// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();

// Printing each team's display name
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();

// Printing each team's display name
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
' Retrieving teams that the user is part of
Dim teams = Await graphClient.Me.JoinedTeams.Request().GetAsync()

' Printing each team's display name
For Each team In teams
	Console.WriteLine($"Team name: {team.DisplayName}")
Next team
$vbLabelText   $csharpLabel

This lists the names of the Teams that the user is a part of.

Each of these features demonstrates the power and versatility of MS Graph .NET. They show how you can integrate Microsoft 365 services into your applications.

Integrating MS Graph .NET with IronPDF

MS Graph .NET (How It Works For Developers): Figure 2

If you're looking to work with PDFs in your .NET applications, the IronPDF Library for .NET Developers is a solid choice. It's a library that gives your apps the ability to read, create, and manipulate PDF files without needing any other external PDF tools or software.

Use Case: Merging IronPDF with MS Graph .NET

Imagine you're building an application that needs to fetch documents from Microsoft 365, say reports or invoices, and convert them into PDFs. MS Graph .NET allows you to interact with Microsoft 365 resources, including files stored in OneDrive or SharePoint. IronPDF can then be used to take these documents and convert them into PDFs. This combination is especially useful for automated report generation or archiving emails and attachments in a PDF format for easy distribution.

Code Example: From MS Graph to PDF

Let's walk through a simple example. We're going to fetch a document from OneDrive using MS Graph .NET and then convert that document to a PDF using IronPDF. I'll assume you've already set up your authentication with MSGraph; if not, there's plenty of documentation on Microsoft's site to get you started.

// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Setting up the GraphServiceClient with a DelegateAuthenticationProvider
        var graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    // Insert code to acquire token
                    string accessToken = await GetAccessTokenAsync();
                    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                }));

        // Replace 'itemId' with the ID of your document in OneDrive
        var stream = await graphClient.Me.Drive.Items["itemId"].Content.Request().GetAsync();

        // IronPDF setup to convert the fetched file to PDF
        var renderer = new HtmlToPdf();
        var pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream));

        // Save the PDF to a file
        pdfDocument.SaveAs("YourDocument.pdf");
    }

    // Method to convert a Stream to a String
    static string StreamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }

    // Method to obtain the access token
    static async Task<string> GetAccessTokenAsync()
    {
        // Implement your authentication logic here to return the access token
        return "your_access_token";
    }
}
// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Setting up the GraphServiceClient with a DelegateAuthenticationProvider
        var graphClient = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    // Insert code to acquire token
                    string accessToken = await GetAccessTokenAsync();
                    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                }));

        // Replace 'itemId' with the ID of your document in OneDrive
        var stream = await graphClient.Me.Drive.Items["itemId"].Content.Request().GetAsync();

        // IronPDF setup to convert the fetched file to PDF
        var renderer = new HtmlToPdf();
        var pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream));

        // Save the PDF to a file
        pdfDocument.SaveAs("YourDocument.pdf");
    }

    // Method to convert a Stream to a String
    static string StreamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }

    // Method to obtain the access token
    static async Task<string> GetAccessTokenAsync()
    {
        // Implement your authentication logic here to return the access token
        return "your_access_token";
    }
}
' Simplified example, ensure to handle exceptions and errors appropriately.
Imports Microsoft.Graph
Imports IronPdf
Imports System.IO
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Setting up the GraphServiceClient with a DelegateAuthenticationProvider
		Dim graphClient = New GraphServiceClient(New DelegateAuthenticationProvider(Async Sub(requestMessage)
					' Insert code to acquire token
					Dim accessToken As String = Await GetAccessTokenAsync()
					requestMessage.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken)
		End Sub))

		' Replace 'itemId' with the ID of your document in OneDrive
		Dim stream = Await graphClient.Me.Drive.Items("itemId").Content.Request().GetAsync()

		' IronPDF setup to convert the fetched file to PDF
		Dim renderer = New HtmlToPdf()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream))

		' Save the PDF to a file
		pdfDocument.SaveAs("YourDocument.pdf")
	End Function

	' Method to convert a Stream to a String
	Private Shared Function StreamToString(ByVal stream As Stream) As String
		Using reader = New StreamReader(stream)
			Return reader.ReadToEnd()
		End Using
	End Function

	' Method to obtain the access token
	Private Shared Async Function GetAccessTokenAsync() As Task(Of String)
		' Implement your authentication logic here to return the access token
		Return "your_access_token"
	End Function
End Class
$vbLabelText   $csharpLabel

A few things to note in this code:

  • We're using MSGraph to access a file stored in OneDrive. You'll need the item's ID, which you can obtain through the Graph API.
  • We convert the file stream to a string for this example. This works well for HTML documents. If you're dealing with binary files (like Word documents), you'll want to use a different method to convert these files to PDFs.
  • The RenderHtmlAsPdf method from IronPDF is used here to create a PDF from an HTML string. If your source document is not HTML, IronPDF offers methods to work with other formats as well.

Remember, this is a simplified example. In a real-world application, you'd need to handle authentication more robustly, manage errors, and potentially deal with different file formats more gracefully. But this should give you a good starting point for integrating MSGraph and IronPDF in your .NET projects.

Conclusion

MS Graph .NET (How It Works For Developers): Figure 3

For developers looking to integrate Microsoft 365 capabilities into their C# applications, the MS Graph .NET SDK is an essential tool. Start by exploring the MS Graph .NET SDK Licensing and Pricing Information starting at $799.

Häufig gestellte Fragen

Wie hilft MS Graph .NET Entwicklern beim Zugriff auf Microsoft 365-Daten?

MS Graph .NET fungiert als Gateway für Entwickler, um über die Microsoft Graph-API, die Teil des Azure Active Directory-Ökosystems ist, auf Microsoft 365-Daten zuzugreifen und diese zu verwalten. Es bietet Methoden zur Rationalisierung des Dateninteraktionsprozesses.

Wie können Entwickler in .NET PDF-Dokumente mit Microsoft 365-Daten erzeugen?

Entwickler können IronPDF verwenden, um in .NET-Anwendungen PDF-Dokumente zu erstellen, indem sie HTML und andere Dokumentformate in PDFs konvertieren und Daten nutzen, die über MS Graph .NET abgerufen wurden.

Was wird benötigt, um mit der Nutzung von MS Graph .NET in einem Projekt zu beginnen?

Um mit der Nutzung von MS Graph .NET zu beginnen, müssen Sie das Microsoft.Graph-Paket über den NuGet-Paket-Manager installieren und eine Authentifizierung mittels Client-Anmeldeinformationen einrichten, um mit Microsoft 365-Diensten zu interagieren.

Wie kann ein Entwickler eine E-Mail mit MS Graph .NET senden?

Ein Entwickler kann eine E-Mail mit MS Graph .NET senden, indem er ein `Message`-Objekt mit dem gewünschten Inhalt und den Empfängerinformationen erstellt und dann die `SendMail`-Methode des `GraphServiceClient` verwendet.

Kann MS Graph .NET Kalendereinträge in einem Microsoft 365-Konto verwalten?

Ja, MS Graph .NET ermöglicht das Verwalten von Kalendereinträgen, indem `Event`-Objekte erstellt und Methoden wie `Me.Events.Request().AddAsync(event)` genutzt werden, um Ereignisse zum Kalender eines Benutzers hinzuzufügen.

Wie konvertieren Sie ein OneDrive-Dokument in einer .NET-Anwendung in ein PDF?

Um ein OneDrive-Dokument in ein PDF zu konvertieren, können Sie MS Graph .NET verwenden, um das Dokument abzurufen, und dann IronPDF einsetzen, um den Dokumentinhalt in ein PDF-Format zu konvertieren.

Welche Überlegungen sollten beim Integrieren von MS Graph .NET mit IronPDF angestellt werden?

Beim Integrieren von MS Graph .NET mit IronPDF sollten Sie robuste Authentifizierung, Fehlerbehandlung und die Kompatibilität verschiedener Dateiformate berücksichtigen, um eine nahtlose Konvertierung und Datenverwaltung zu gewährleisten.

Was sind einige praktische Anwendungen der gemeinsamen Nutzung von MS Graph .NET und IronPDF?

Die gemeinsame Nutzung von MS Graph .NET und IronPDF ermöglicht Anwendungen wie die Erstellung von PDF-Berichten, das Archivieren von E-Mails als PDFs oder das Erstellen standardisierter Geschäftsdokumente aus Microsoft 365-Daten.

Wie kann MS Graph .NET die Effizienz von .NET-Anwendungen verbessern?

MS Graph .NET verbessert die Effizienz, indem es einen rationalisierten Zugriff auf Microsoft 365-Dienste bietet und Entwicklern ermöglicht, Daten mit minimalem Code abzurufen, zu verwalten und zu manipulieren, was die Produktivität und Fähigkeit der Anwendung erhöht.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen