.NET ヘルプ

MS Graph .NET(開発者向けの仕組み)

更新済み 4月 29, 2024
共有:

MS Graph .NET Microsoft Graph APIとのやり取りのためのアクセスデータツールとして機能し、Azure Active Directoryの中心的な役割を果たします。 (アジュール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を検索してください。

    1. 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#

以下のコードスニペットは、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
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サービスを統合する方法を示しています。

IronPDFを使用したMSGraph .NETの統合

MS Graph .NET (開発者向けの仕組み):図2

あなたの.NETアプリケーションでPDFを扱う場合、 IronPDF は堅実な選択です。このライブラリを使用すると、アプリが他の外部のPDFツールやソフトウェアを必要とせずに、PDFファイルを読み込み、作成し、操作することができます。

ユースケース: IronPDF と MSGraph .NET の統合

アプリケーションを構築していると想像してください。そのアプリケーションでは、Microsoft 365 からレポートや請求書などのドキュメントを取得し、それらをPDFに変換する必要があります。 MSGraph .NETは、OneDriveやSharePointに保存されているファイルを含むMicrosoft 365リソースとのやり取りを可能にします。 IronPDF を使用して、これらのドキュメントを PDF に変換することができます。 この組み合わせは、特に自動レポート生成やPDF形式でのメールと添付ファイルのアーカイブに便利で、簡単に配布できます。

コード例: MSGraphからPDFへ

簡単な例を見てみましょう。 OneDriveからMSGraph .NETを使用してドキュメントを取得し、そのドキュメントを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
VB   C#

以下のコードでいくつか注意する点があります:

  • 私たちは、MSGraphを使用してOneDriveに保存されているファイルにアクセスしています。Graph APIを通じて取得できるアイテムのIDが必要です。
  • この例では、ファイルストリームを文字列に変換します。 これはHTMLドキュメントにうまく機能します。 バイナリファイルを扱う場合 (Word ドキュメントのように)異なる方法を使用してこれらのファイルをPDFに変換する必要があります。

  • IronPDFのRenderHtmlAsPdfメソッドは、HTML文字列からPDFを作成するために使用されます。 ソースドキュメントがHTMLでない場合でも、IronPDFは他の形式で作業するためのメソッドを提供します。

    これは簡略化された例であることを覚えておいてください。 実際のアプリケーションでは、認証をより強固に処理し、エラーを管理し、さまざまなファイル形式により優雅に対応する必要があります。 ですが、これはMSGraphとIronPDFを.NETプロジェクトに統合するための良い出発点となるでしょう。

結論

MS Graph .NET(開発者向けの動作方法):図3

C#アプリケーションにMicrosoft 365の機能を統合したい開発者にとって、MS Graph .NET SDKは不可欠なツールです。 始めに、以下を探索してください 公式ドキュメント $749から開始。

< 以前
Livecharts C#(開発者向けの動作方法)
次へ >
C# 参照(開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >