在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
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 Core 專案中處理 使用者 ID 時,設置您的 .NET 專案是第一步。以下是步驟:
打開 NuGet 套件管理器。
搜尋 Microsoft.Graph。
安裝 Microsoft.Graph 套件。
此過程將 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}!")
以下程式碼片段展示了如何利用客戶端密鑰為 Azure AD 身份驗證創建一個新的 GraphServiceClient 實例。 它使用客戶端憑證進行身份驗證。 然後,它會檢索當前用戶的顯示名稱。 遵循以下代碼片段,確保將 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
此代碼列出了用戶收件箱中的前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()
這會發送一封包含簡單文本內容的電子郵件。
將事件添加到用戶的日曆:
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])
此程式碼在日曆中排定一個新事件。
要列出用戶 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
此代碼列印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
這列出使用者所屬團隊的名稱。
這些功能中的每一個都展示了MS Graph .NET的強大和多功能性。 他們展示如何將 Microsoft 365 服務整合到您的應用程式中。
如果您希望在您的 .NET 應用程序中使用 PDF,適用於 .NET 開發者的 IronPDF 函式庫是一個穩固的選擇。它是一個庫,使您的應用程序能夠讀取、創建和操作 PDF 文件,而無需任何其他外部 PDF 工具或軟件。
想像一下,您正在構建一個應用程式,需要從 Microsoft 365 獲取文檔,比如報告或發票,並將它們轉換為 PDF。 MSGraph .NET 允許您與 Microsoft 365 資源互動,包括存儲在 OneDrive 或 SharePoint 的檔案。 然後可以使用 IronPDF 將這些文件轉換為 PDF。 這種組合特別適用於自動生成報告或將電子郵件及附件歸檔為 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
在此程式碼中需要注意的幾點:
這裡使用 IronPDF 的 RenderHtmlAsPdf 方法從 HTML 字串創建 PDF。 如果您的源文件不是 HTML,IronPDF 也提供了處理其他格式的方法。
請記住,這是一個簡化的範例。 在實際應用中,您需要更強地處理身份驗證,管理錯誤,並可能更優雅地處理不同的文件格式。 但這應該能為您在 .NET 專案中整合 MSGraph 和 IronPDF 提供一個良好的起點。
對於想要將 Microsoft 365 功能整合到其 C# 應用程式中的開發人員而言,MS Graph .NET SDK 是一款必不可少的工具。 從探索开始MS Graph .NET SDK 授權和定價資訊起價 $749。