Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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:
This process adds MS Graph .NET to your project. Now, you're ready to start coding with it.
Let's say you want to retrieve the current user's profile information. Here is a simple code example:
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}!")
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 the following code snippets make sure that MS Graph .NET, alongside your authentication provider configurations, is added to your project.
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:
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
This code lists the subjects of the top 10 emails in the user's inbox.
Sending an email involves creating a Message object and sending it:
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()
This sends an email with a simple text body.
To add an event to the user's calendar:
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])
This code schedules a new event in the calendar.
To list files from the root of the user's 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
This code prints the names of the files in the root directory of OneDrive.
To retrieve the list of teams the user is part of:
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
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.
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.
Imagine you're building an application that needs to fetch documents from Microsoft 365, say reports or invoices, and convert them into PDFs. MSGraph .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.
Let's walk through a simple example. We're going to fetch a document from OneDrive using MSGraph .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;
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
A few things to note in this code:
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.
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 $749.
9 .NET API products for your office documents