在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
MS Graph .NET作为与微软图形应用程序接口交互的访问数据工具,该应用程序接口是Azure Active Directory的核心部分。(Azure AD)生态系统 Microsoft Graph 是 Microsoft 365 中数据和智能的入口。它允许开发人员跨各种 Microsoft 服务访问、管理和分析数据。 Microsoft Graph 客户端库提供了一系列方法,可轻松与 API 进行交互,从而简化了这一过程。
IronPDF是一个用于在 .NET 应用程序中生成 PDF 文档的库。 它将 HTML 转换为 PDF此外,译文还必须能自动生成报告、发票和文档。 IronPDF for .NET 可与 .NET 应用程序很好地配合使用,提供了一种直接生成 PDF 的方法。
结合MS Graph .NET和IronPDF,开发人员可以创建能够操作Microsoft 365数据并生成PDF文档的应用程序。 这种组合对于开发需要从微软服务获取数据并需要以标准化文档格式呈现数据的业务应用程序来说非常强大。
要有效使用 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}!")
本代码片段演示了创建 GraphServiceClient 的新实例,并利用客户端秘密进行 Azure AD 身份验证。 它使用客户端凭据进行身份验证。 然后,它会检索当前用户的显示名称。 按照以下代码片段,确保将 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 设置了身份验证; 如果没有,微软网站上有大量的文档可帮助您入门。
// 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 美元。