.NET 帮助

MS Graph .NET(开发人员如何使用)

发布 2024年四月29日
分享:

MS Graph .NET 作为与微软图形应用程序接口交互的访问数据工具,该应用程序接口是Azure Active Directory的核心部分。 (Azure AD) 生态系统。Microsoft Graph 是 Microsoft 365 中数据和智能的入口。它允许开发人员跨各种 Microsoft 服务访问、管理和分析数据。Microsoft Graph 客户端库通过提供一套方法来轻松与 API 交互,从而简化了这一过程。

IronPDF 是一个用于在 .NET 应用程序中生成 PDF 文档的库。它 将 HTML 转换为 PDF因此,IronPDF 可用于自动创建报告、发票和文档。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}!")
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 也提供了处理其他格式文件的方法。

请记住,这只是一个简化的示例。在实际应用中,您需要更稳健地处理身份验证、管理错误,并有可能更优雅地处理不同的文件格式。但这应该能为您在 .NET 项目中集成 MSGraph 和 IronPDF 提供一个良好的起点。

结论

MS Graph .NET(如何为开发人员工作):图 3

对于希望将 Microsoft 365 功能集成到其 C# 应用程序中的开发人员来说,MS Graph .NET SDK 是必不可少的工具。从探索 官方文件 起价 749 美元。

< 前一页
Livecharts C#(它如何为开发人员工作)
下一步 >
C# 参考(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >