푸터 콘텐츠로 바로가기
.NET 도움말

MS Graph .NET (How It Works For Developers)

MS Graph .NET serves as an access data tool for interactions with the Microsoft Graph API, a central piece of the Azure Active Directory (Azure AD) ecosystem. Microsoft Graph is a gateway to data and intelligence in Microsoft 365. It allows developers to access, manage, and analyze data across various Microsoft services. The Microsoft Graph client library simplifies this process by providing a set of methods to interact with the API easily.

IronPDF is a library for generating PDF documents in .NET applications. It converts HTML to PDF, making it useful for creating reports, invoices, and documentation automatically. IronPDF works well with .NET applications, offering a straightforward approach to PDF generation.

Combining MS Graph .NET and IronPDF allows developers to create applications that can manipulate Microsoft 365 data and produce PDF documents. This combination is powerful for developing business applications that require data from Microsoft services and need to present that data in a standardized document format.

Getting Started with MS Graph .NET

Setting Up MS Graph .NET in .NET Projects

To use MS Graph .NET effectively, especially when working with user IDs in .NET Core projects, setting up your .NET project is the first step. Here are the steps:

  1. Open the NuGet Package Manager.
  2. Search for Microsoft.Graph.
  3. Install the Microsoft.Graph package.

MS Graph .NET (How It Works For Developers): Figure 1

This process adds MS Graph .NET to your project. Now, you're ready to start coding with it.

A Basic Code Example

Let's say you want to retrieve the current user's profile information. Here is a simple code example:

// Required namespaces
using Azure.Identity;
using Microsoft.Graph;

// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };

// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// Fetching current user's profile information
var user = await graphClient.Me
    .Request()
    .GetAsync();

// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");
// Required namespaces
using Azure.Identity;
using Microsoft.Graph;

// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };

// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// Fetching current user's profile information
var user = await graphClient.Me
    .Request()
    .GetAsync();

// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");
$vbLabelText   $csharpLabel

This code snippet demonstrates creating a new instance of GraphServiceClient, utilizing a client secret for Azure AD authentication. It uses client credentials to authenticate. Then, it retrieves the current user's display name. Following this, make sure that MS Graph .NET, alongside your authentication provider configurations, is added to your project.

Features of MS Graph .NET

Retrieve User Emails

To retrieve emails from a user's Microsoft account mailbox, you use the Mail.Read permission. Here is how you can list the most recent emails:

// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10)
    .GetAsync();

// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
    .Request()
    .Top(10)
    .GetAsync();

// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
    Console.WriteLine($"Subject: {message.Subject}");
}
$vbLabelText   $csharpLabel

This code lists the subjects of the top 10 emails in the user's inbox.

Send an Email

Sending an email involves creating a Message object and sending it:

// Creating a message to be sent
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"
            }
        }
    }
};

// Sending the email
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
// Creating a message to be sent
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"
            }
        }
    }
};

// Sending the email
await graphClient.Me.SendMail(message, null)
    .Request()
    .PostAsync();
$vbLabelText   $csharpLabel

This sends an email with a simple text body.

Managing Calendar Events

To add an event to the user's calendar:

// Creating a calendar 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"
    }
};

// Adding the event to the user's calendar
await graphClient.Me.Events
    .Request()
    .AddAsync(@event);
// Creating a calendar 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"
    }
};

// Adding the event to the user's calendar
await graphClient.Me.Events
    .Request()
    .AddAsync(@event);
$vbLabelText   $csharpLabel

This code schedules a new event in the calendar.

Accessing OneDrive Files

To list files from the root of the user's OneDrive:

// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();

// Printing each file's name
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
    .Request()
    .GetAsync();

// Printing each file's name
foreach (var file in files)
{
    Console.WriteLine(file.Name);
}
$vbLabelText   $csharpLabel

This code prints the names of the files in the root directory of OneDrive.

Working with Teams

To retrieve the list of teams the user is part of:

// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();

// Printing each team's display name
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
    .Request()
    .GetAsync();

// Printing each team's display name
foreach (var team in teams)
{
    Console.WriteLine($"Team name: {team.DisplayName}");
}
$vbLabelText   $csharpLabel

This lists the names of the Teams that the user is a part of.

Each of these features demonstrates the power and versatility of MS Graph .NET. They show how you can integrate Microsoft 365 services into your applications.

Integrating MS Graph .NET with IronPDF

MS Graph .NET (How It Works For Developers): Figure 2

If you're looking to work with PDFs in your .NET applications, the IronPDF Library for .NET Developers is a solid choice. It's a library that gives your apps the ability to read, create, and manipulate PDF files without needing any other external PDF tools or software.

Use Case: Merging IronPDF with MS Graph .NET

Imagine you're building an application that needs to fetch documents from Microsoft 365, say reports or invoices, and convert them into PDFs. MS Graph .NET allows you to interact with Microsoft 365 resources, including files stored in OneDrive or SharePoint. IronPDF can then be used to take these documents and convert them into PDFs. This combination is especially useful for automated report generation or archiving emails and attachments in a PDF format for easy distribution.

Code Example: From MS Graph to PDF

Let's walk through a simple example. We're going to fetch a document from OneDrive using MS Graph .NET and then convert that document to a PDF using IronPDF. I'll assume you've already set up your authentication with MSGraph; if not, there's plenty of documentation on Microsoft's site to get you started.

// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Setting up the GraphServiceClient with a DelegateAuthenticationProvider
        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");
    }

    // Method to convert a Stream to a String
    static string StreamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }

    // Method to obtain the access token
    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;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Setting up the GraphServiceClient with a DelegateAuthenticationProvider
        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");
    }

    // Method to convert a Stream to a String
    static string StreamToString(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }

    // Method to obtain the access token
    static async Task<string> GetAccessTokenAsync()
    {
        // Implement your authentication logic here to return the access token
        return "your_access_token";
    }
}
$vbLabelText   $csharpLabel

A few things to note in this code:

  • We're using MSGraph to access a file stored in OneDrive. You'll need the item's ID, which you can obtain through the Graph API.
  • We convert the file stream to a string for this example. This works well for HTML documents. If you're dealing with binary files (like Word documents), you'll want to use a different method to convert these files to PDFs.
  • The RenderHtmlAsPdf method from IronPDF is used here to create a PDF from an HTML string. If your source document is not HTML, IronPDF offers methods to work with other formats as well.

Remember, this is a simplified example. In a real-world application, you'd need to handle authentication more robustly, manage errors, and potentially deal with different file formats more gracefully. But this should give you a good starting point for integrating MSGraph and IronPDF in your .NET projects.

Conclusion

MS Graph .NET (How It Works For Developers): Figure 3

For developers looking to integrate Microsoft 365 capabilities into their C# applications, the MS Graph .NET SDK is an essential tool. Start by exploring the MS Graph .NET SDK Licensing and Pricing Information starting at $799.

자주 묻는 질문

MS Graph .NET은 개발자가 Microsoft 365 데이터에 액세스하는 데 어떻게 도움이 되나요?

MS Graph .NET은 개발자가 Azure Active Directory 에코시스템의 일부인 Microsoft Graph API를 통해 Microsoft 365 데이터에 액세스하고 관리할 수 있는 게이트웨이 역할을 합니다. 이 도구는 데이터 상호 작용 프로세스를 간소화하는 방법을 제공합니다.

개발자가 Microsoft 365 데이터를 사용하여 .NET에서 PDF 문서를 생성하려면 어떻게 해야 하나요?

개발자는 IronPDF를 사용하여 HTML 및 기타 문서 형식을 PDF로 변환하고 MS Graph .NET을 통해 액세스한 데이터를 활용하여 .NET 애플리케이션에서 PDF 문서를 생성할 수 있습니다.

프로젝트에서 MS Graph .NET을 사용하려면 무엇이 필요하나요?

MS Graph .NET을 사용하려면 NuGet 패키지 관리자를 통해 Microsoft.Graph 패키지를 설치하고 클라이언트 자격 증명을 사용하여 인증을 설정하여 Microsoft 365 서비스와 상호 작용하도록 설정해야 합니다.

개발자가 MS Graph .NET을 사용하여 이메일을 보내려면 어떻게 해야 하나요?

개발자는 원하는 콘텐츠와 수신자 세부 정보가 포함된 '메시지' 개체를 생성한 다음 '그래프서비스클라이언트'의 'SendMail' 메서드를 활용하여 MS Graph .NET을 사용하여 이메일을 보낼 수 있습니다.

MS Graph .NET에서 Microsoft 365 계정에서 일정 이벤트를 관리할 수 있나요?

예, MS Graph .NET에서는 `Event` 개체를 만들고 `Me.Events.Request().AddAsync(event)`와 같은 메서드를 사용하여 사용자의 캘린더에 이벤트를 추가함으로써 캘린더 이벤트를 관리할 수 있습니다.

.NET 애플리케이션에서 OneDrive 문서를 PDF로 변환하려면 어떻게 하나요?

OneDrive 문서를 PDF로 변환하려면 MS Graph .NET을 사용하여 문서를 가져온 다음 IronPDF를 사용하여 문서 콘텐츠를 PDF 형식으로 변환할 수 있습니다.

MS Graph .NET과 IronPDF를 통합할 때 고려해야 할 사항은 무엇인가요?

MS Graph .NET과 IronPDF를 통합할 때는 강력한 인증, 오류 처리, 다양한 파일 형식의 호환성을 고려하여 원활한 변환 및 데이터 관리를 보장해야 합니다.

MS Graph .NET과 IronPDF를 함께 사용하면 어떤 실용적인 용도로 사용할 수 있나요?

MS Graph .NET과 IronPDF를 함께 사용하면 PDF 보고서 생성, 이메일을 PDF로 보관하거나 Microsoft 365 데이터에서 표준화된 비즈니스 문서를 만드는 등의 애플리케이션을 사용할 수 있습니다.

MS Graph .NET은 어떻게 .NET 애플리케이션의 효율성을 향상시킬 수 있나요?

MS Graph .NET은 Microsoft 365 서비스에 대한 간소화된 액세스를 제공하여 개발자가 최소한의 코드로 데이터를 검색, 관리 및 조작할 수 있도록 함으로써 효율성을 개선하여 생산성과 애플리케이션 기능을 향상시킵니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.