.NET 幫助

MS Graph .NET(它對開發人員的運作方式)

MS Graph .NET 是與 Microsoft Graph API 互動的訪問數據工具,是Azure Active Directory(Azure AD)生態系統的重要組成部分。 Microsoft Graph 是進入 Microsoft 365 中資料和智慧的入口。它允許開發者跨越各種 Microsoft 服務存取、管理和分析資料。 Microsoft Graph 用戶端程式庫通過提供一組方法來簡化這一過程,使與 API 的互動更加容易。

IronPDF 是用於在 .NET 應用程式中生成 PDF 文件的庫。 它將 HTML 轉換為 PDF,使其在自動生成報告、發票和文檔時非常有用。 IronPDF 與 .NET 應用程式配合良好,提供簡單直接的 PDF 生成方法。

結合 MS Graph .NET 和 IronPDF 能讓開發者創建應用程式,這些應用程式可以操作 Microsoft 365 資料並生成 PDF 文件。 這種組合對於開發需要從 Microsoft 服務獲取數據並需要以標準化文件格式呈現該數據的商業應用程序來說非常強大。

開始使用 MS Graph .NET

在 .NET 專案中設置 MS Graph .NET

要有效地使用 MS Graph .NET,尤其是在 .NET Core 專案中處理使用者 ID時,設定您的 .NET 專案是第一步。以下是步驟:

  1. 打開 NuGet 套件管理器。

  2. 搜尋Microsoft.Graph

  3. 安裝Microsoft.Graph套件。

    MS Graph .NET(對開發者的運作方式):圖 1

    此過程將 MS Graph .NET 添加到您的專案中。 現在,您已準備好開始使用它進行編碼。

基本代碼範例

假設您想檢索當前使用者的個人資料資訊。 這是簡單的程式碼範例:

var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new [] { "User.Read" };
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var user = await graphClient.Me
    .Request()
    .GetAsync();
Console.WriteLine($"Hello, {user.DisplayName}!");
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new [] { "User.Read" };
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var user = await graphClient.Me
    .Request()
    .GetAsync();
Console.WriteLine($"Hello, {user.DisplayName}!");
Dim clientId = "Your_Application_Id"
Dim tenantId = "Your_Tenant_Id"
Dim clientSecret = "Your_Client_Secret"
Dim scopes = { "User.Read" }
Dim options = New TokenCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}
Dim clientSecretCredential As New ClientSecretCredential(tenantId, clientId, clientSecret, options)
Dim graphClient = New GraphServiceClient(clientSecretCredential, scopes)
Dim user = Await graphClient.Me.Request().GetAsync()
Console.WriteLine($"Hello, {user.DisplayName}!")
$vbLabelText   $csharpLabel

以下程式碼片段展示了如何利用客戶端密鑰為 Azure AD 身份驗證創建一個新的 GraphServiceClient 實例。 它使用客戶端憑證進行身份驗證。 然後,它會檢索當前用戶的顯示名稱。 遵循以下代碼片段,確保將 MS Graph .NET 和您的身份驗證提供者配置添加到您的專案中。

MS Graph .NET 的功能

檢索用戶電子郵件

要從使用者的 Microsoft 帳戶信箱中檢索電子郵件,您需要使用Mail.Read許可。 以下是列出最新電子郵件的方法:

var messages = await graphClient.Me.Messages
    .Request()
    .Top(10) // Retrieves the top 10 messages
    .GetAsync();
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10) // Retrieves the top 10 messages
    .GetAsync();
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
Dim messages = Await graphClient.Me.Messages.Request().Top(10).GetAsync()
For Each message In messages
	Console.WriteLine($"Subject: {message.Subject}")
Next message
$vbLabelText   $csharpLabel

此代碼列出了用戶收件箱中的前10封電子郵件的主題。

發送電子郵件

發送電子郵件涉及創建一個Message對象並發送它:

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"
            }
        }
    }
};
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
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"
            }
        }
    }
};
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
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"}
		}
	}
}
Await graphClient.Me.SendMail(message, Nothing).Request().PostAsync()
$vbLabelText   $csharpLabel

這會發送一封包含簡單文本內容的電子郵件。

管理日曆事件

將事件添加到用戶的日曆:

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"
    }
};
await graphClient.Me.Events
    .Request()
    .AddAsync(@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"
    }
};
await graphClient.Me.Events
    .Request()
    .AddAsync(@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"}
}
Await graphClient.Me.Events.Request().AddAsync([event])
$vbLabelText   $csharpLabel

此程式碼在日曆中排定一個新事件。

存取 OneDrive 檔案

要列出用戶 OneDrive 根目錄中的檔案:

var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
Dim files = Await graphClient.Me.Drive.Root.Children.Request().GetAsync()
For Each file In files
	Console.WriteLine(file.Name)
Next file
$vbLabelText   $csharpLabel

此代碼列印OneDrive根目錄中的文件名。

團隊合作

要獲取用戶所屬團隊的列表:

var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
Dim teams = Await graphClient.Me.JoinedTeams.Request().GetAsync()
For Each team In teams
	Console.WriteLine($"Team name: {team.DisplayName}")
Next team
$vbLabelText   $csharpLabel

這列出使用者所屬團隊的名稱。

這些功能中的每一個都展示了MS Graph .NET的強大和多功能性。 他們展示如何將 Microsoft 365 服務整合到您的應用程式中。

將 MSGraph .NET 與 IronPDF 整合

MS Graph .NET(它如何為開發者工作):圖2

如果您希望在 .NET 應用程式中使用 PDF,IronPDF Library for .NET Developers 是一個穩固的選擇。這是一個讓您的應用程式可以在不需要其他外部 PDF 工具或軟體的情況下讀取、創建和操作 PDF 檔案的程式庫。

使用案例:將 IronPDF 與 MSGraph .NET 合併

想像一下,您正在構建一個應用程式,需要從 Microsoft 365 獲取文檔,比如報告或發票,並將它們轉換為 PDF。 MSGraph .NET 允許您與 Microsoft 365 資源互動,包括存儲在 OneDrive 或 SharePoint 的檔案。 然後可以使用 IronPDF 將這些文件轉換為 PDF。 這種組合特別適用於自動生成報告或將電子郵件及附件歸檔為 PDF 格式以便於分發。

程式碼範例:從 MSGraph 到 PDF

讓我們通過一個簡單的例子來講解。 我們將使用 MSGraph .NET 從 OneDrive 提取文件,然後使用 IronPDF 將該文件轉換為 PDF。 我假設你已經設置了與 MSGraph 的身份驗證; 如果沒有,Microsoft 的網站上有許多文件可以幫助您開始。

// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
class Program
{
    static async Task Main(string [] args)
    {
        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");
    }
    static string streamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
    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;
class Program
{
    static async Task Main(string [] args)
    {
        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");
    }
    static string streamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
    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
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		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
	Private Shared Function streamToString(ByVal stream As Stream) As String
		Using reader = New StreamReader(stream)
			Return reader.ReadToEnd()
		End Using
	End Function
	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

在此程式碼中需要注意的幾點:

  • 我們正在使用 MSGraph 訪問存儲在 OneDrive 中的文件。您需要通過 Graph API 獲取項目 ID。
  • 在此範例中,我們將檔案流轉換為字串。 這非常適用於 HTML 文件。 如果您正在處理二進位檔案(如 Word 文件),您將需要使用不同的方法將這些檔案轉換為 PDF。
  • 這裡使用 IronPDF 的 RenderHtmlAsPdf 方法來從 HTML 字串創建 PDF。 如果您的源文件不是 HTML,IronPDF 也提供了處理其他格式的方法。

    請記住,這是一個簡化的範例。 在實際應用中,您需要更強地處理身份驗證,管理錯誤,並可能更優雅地處理不同的文件格式。 但這應該能為您在 .NET 專案中整合 MSGraph 和 IronPDF 提供一個良好的起點。

結論

MS Graph .NET(開發者如何使用它):圖 3

對於想要將 Microsoft 365 功能整合到其 C# 應用程式中的開發人員而言,MS Graph .NET SDK 是一款必不可少的工具。 從探索 MS Graph .NET SDK 授權與定價資訊 開始,價格從 $749 起。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Livecharts C#(它如何為開發者工作)
下一個 >
C# 參考(這對開發人員的工作方式)