.NET 幫助

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

發佈 2024年4月29日
分享:

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

設置 MS Graph .NET 在 .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}!")
VB   C#

以下程式碼片段展示了如何創建一個新的 GraphServiceClient 實例,使用用戶端密鑰進行 Azure AD 認證。它使用客戶端憑證進行身份驗證。然後,它檢索當前用戶的顯示名稱。在以下代碼片段中,確保 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
VB   C#

此代碼列出了用戶收件箱中的前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()
VB   C#

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

管理日曆事件

要將事件添加到使用者的日曆:

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])
VB   C#

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

訪問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
VB   C#

此代碼列印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
VB   C#

這列出了用戶所屬的團隊名稱。

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

將 MSGraph .NET 集成到 IronPDF

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

如果您想在您的 .NET 應用程序中使用 PDF, IronPDF 是一個穩固的選擇。它是一個庫,使您的應用程序能夠讀取、創建和操作 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 的身份驗證;如果沒有,微軟的網站上有大量文檔可以讓您入門。

// 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
VB   C#

請注意此程式碼中的幾點事項:

  • 我們使用MSGraph來存取存儲在OneDrive中的文件。您需要獲取文件的ID,可以通過Graph API獲得。
  • 在此示例中,我們將文件流轉換為字串。這對於HTML文件很有效。如果您處理的是二進位文件 (像 Word 文件),您將希望使用不同的方法將這些文件轉換為PDF。
  • 這裡使用IronPDF的 RenderHtmlAsPdf 方法來從HTML字符串創建PDF。如果您的源文檔不是HTML,IronPDF還提供了處理其他格式的方法。

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

結論

MS Graph .NET(開發人員如何運作):圖3

對於希望將 Microsoft 365 功能整合到其C#應用程式中的開發人員來說,MS Graph .NET SDK 是一個必不可少的工具。首先探索 官方文件 起價 $749。

< 上一頁
Livecharts C#(它如何為開發者工作)
下一個 >
C# 參考(這對開發人員的工作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >