MS Graph .NET (jak to działa dla programistów)
MS Graph .NET służy jako narzędzie dostępu do danych umożliwiające interakcję z interfejsem API Microsoft Graph, który stanowi centralny element ekosystemu Azure Active Directory (Azure AD). Microsoft Graph to brama do danych i analiz w Microsoft 365. Umożliwia programistom dostęp do danych w różnych usługach Microsoft, zarządzanie nimi i analizowanie ich. Biblioteka kliencka Microsoft Graph upraszcza ten proces, udostępniając zestaw metod umożliwiających łatwą interakcję z API.
IronPDF to biblioteka służąca do generowania dokumentów PDF w aplikacjach .NET. Konwertuje HTML na PDF, dzięki czemu przydaje się do automatycznego tworzenia raportów, faktur i dokumentacji. IronPDF dobrze współpracuje z aplikacjami .NET, oferując proste podejście do generowania plików PDF.
Połączenie MS Graph .NET i IronPDF pozwala programistom tworzyć aplikacje, które mogą przetwarzać dane z Microsoft 365 i generować dokumenty PDF. To połączenie jest potężnym narzędziem do tworzenia aplikacji biznesowych, które wymagają danych z usług Microsoftu i muszą przedstawiać te dane w standardowym formacie dokumentów.
Pierwsze kroki z MS Graph .NET
Konfiguracja MS Graph .NET w projektach .NET
Aby efektywnie korzystać z MS Graph .NET, zwłaszcza podczas pracy z identyfikatorami użytkowników w projektach .NET Core, pierwszym krokiem jest skonfigurowanie projektu .NET. Oto kolejne kroki:
- Otwórz menedżera pakietów NuGet.
- Wyszukaj Microsoft.Graph.
- Zainstaluj pakiet Microsoft.Graph.

Ten proces dodaje MS Graph .NET do Twojego projektu. Teraz jesteś gotowy, aby rozpocząć programowanie z jego użyciem.
Podstawowy przykład kodu
Załóżmy, że chcesz pobrać informacje o profilu bieżącego użytkownika. Oto prosty przykład kodu:
// 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
Imports Azure.Identity
Imports Microsoft.Graph
' Defining necessary credentials and scope
Private clientId = "Your_Application_Id"
Private tenantId = "Your_Tenant_Id"
Private clientSecret = "Your_Client_Secret"
Private scopes = { "User.Read" }
' Configuring TokenCredentialOptions for Azure Public Cloud
Private options = New TokenCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}
' Authenticating using client credentials
Private clientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)
' Creating a new instance of GraphServiceClient
Private graphClient = New GraphServiceClient(clientSecretCredential, scopes)
' Fetching current user's profile information
Private user = await graphClient.Me.Request().GetAsync()
' Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!")' Required namespaces
Imports Azure.Identity
Imports Microsoft.Graph
' Defining necessary credentials and scope
Private clientId = "Your_Application_Id"
Private tenantId = "Your_Tenant_Id"
Private clientSecret = "Your_Client_Secret"
Private scopes = { "User.Read" }
' Configuring TokenCredentialOptions for Azure Public Cloud
Private options = New TokenCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}
' Authenticating using client credentials
Private clientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)
' Creating a new instance of GraphServiceClient
Private graphClient = New GraphServiceClient(clientSecretCredential, scopes)
' Fetching current user's profile information
Private user = await graphClient.Me.Request().GetAsync()
' Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!")Ten fragment kodu demonstruje tworzenie nowej instancji GraphServiceClient, wykorzystując klucz klienta do uwierzytelniania w Azure AD. Do uwierzytelniania wykorzystuje poświadczenia klienta. Następnie pobiera nazwę wyświetlaną bieżącego użytkownika. Następnie upewnij się, że MS Graph .NET, wraz z konfiguracjami dostawcy uwierzytelniania, został dodany do Twojego projektu.
Funkcje MS Graph .NET
Pobieranie adresów e-mail użytkowników
Aby pobrać wiadomości e-mail ze skrzynki pocztowej konta Microsoft użytkownika, należy użyć uprawnienia Mail.Read. Oto jak można wyświetlić listę najnowszych wiadomości e-mail:
// 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}");
}' Retrieving the top 10 messages from the user's mailbox
Dim messages = Await graphClient.Me.Messages.Request().Top(10).GetAsync()
' Iterating through the messages and printing their subjects
For Each message In messages
Console.WriteLine($"Subject: {message.Subject}")
Next message' Retrieving the top 10 messages from the user's mailbox
Dim messages = Await graphClient.Me.Messages.Request().Top(10).GetAsync()
' Iterating through the messages and printing their subjects
For Each message In messages
Console.WriteLine($"Subject: {message.Subject}")
Next messageTen kod wyświetla tematy 10 najpopularniejszych wiadomości e-mail w skrzynce odbiorczej użytkownika.
Wyślij e-mail
Wysyłanie wiadomości e-mail polega na utworzeniu obiektu Message i wysłaniu go:
// 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();' Creating a message to be sent
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"}
}
}
}
' Sending the email
Await graphClient.Me.SendMail(message, Nothing).Request().PostAsync()' Creating a message to be sent
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"}
}
}
}
' Sending the email
Await graphClient.Me.SendMail(message, Nothing).Request().PostAsync()Wysyła wiadomość e-mail z prostą treścią.
Zarządzanie wydarzeniami w kalendarzu
Aby dodać wydarzenie do kalendarza użytkownika:
// 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);' Creating a calendar 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"}
}
' Adding the event to the user's calendar
Await graphClient.Me.Events.Request().AddAsync([event])' Creating a calendar 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"}
}
' Adding the event to the user's calendar
Await graphClient.Me.Events.Request().AddAsync([event])Ten kod planuje nowe wydarzenie w kalendarzu.
Dostęp do plików OneDrive
Aby wyświetlić listę plików z katalogu głównego konta OneDrive użytkownika:
// 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);
}' Retrieving files from the root OneDrive folder
Dim files = Await graphClient.Me.Drive.Root.Children.Request().GetAsync()
' Printing each file's name
For Each file In files
Console.WriteLine(file.Name)
Next file' Retrieving files from the root OneDrive folder
Dim files = Await graphClient.Me.Drive.Root.Children.Request().GetAsync()
' Printing each file's name
For Each file In files
Console.WriteLine(file.Name)
Next fileTen kod PRINTuje nazwy plików znajdujących się w katalogu głównym OneDrive.
Współpraca z zespołami
Aby pobrać listę zespołów, do których należy użytkownik:
// 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}");
}' Retrieving teams that the user is part of
Dim teams = Await graphClient.Me.JoinedTeams.Request().GetAsync()
' Printing each team's display name
For Each team In teams
Console.WriteLine($"Team name: {team.DisplayName}")
Next team' Retrieving teams that the user is part of
Dim teams = Await graphClient.Me.JoinedTeams.Request().GetAsync()
' Printing each team's display name
For Each team In teams
Console.WriteLine($"Team name: {team.DisplayName}")
Next teamPoniżej znajduje się lista nazw zespołów, do których należy użytkownik.
Każda z tych funkcji pokazuje moc i wszechstronność MS Graph .NET. Pokazują one, w jaki sposób można zintegrować usługi Microsoft 365 z własnymi aplikacjami.
Integracja MS Graph .NET z IronPDF

Jeśli chcesz pracować z plikami PDF w swoich aplikacjach .NET, biblioteka IronPDF for .NET jest doskonałym wyborem. Jest to biblioteka, która zapewnia Twoim aplikacjom możliwość odczytu, tworzenia i manipulowania plikami PDF bez konieczności korzystania z innych zewnętrznych narzędzi lub oprogramowania do obsługi plików PDF.
Przykład zastosowania: Połączenie IronPDF z MS Graph .NET
Wyobraź sobie, że tworzysz aplikację, która musi pobierać dokumenty z Microsoft 365, na przykład raporty lub faktury, i konwertować je do formatu PDF. MS Graph .NET umożliwia interakcję z zasobami Microsoft 365, w tym z plikami przechowywanymi w OneDrive lub SharePoint. Następnie można użyć IronPDF do konwersji tych dokumentów do formatu PDF. To połączenie jest szczególnie przydatne do automatycznego generowania raportów lub archiwizacji wiadomości e-mail i załączników w formacie PDF w celu łatwej dystrybucji.
Przykład kodu: Z MS Graph do PDF
Przeanalizujmy prosty przykład. Pobierzemy dokument z OneDrive przy użyciu MS Graph .NET, a następnie przekonwertujemy go do formatu PDF za pomocą IronPDF. Zakładam, że skonfigurowałeś już uwierzytelnianie w MSGraph; Jeśli nie, na stronie Microsoftu znajdziesz mnóstwo dokumentacji, która pomoże Ci zacząć.
// 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";
}
}' Simplified example, ensure to handle exceptions and errors appropriately.
Imports Microsoft.Graph
Imports IronPdf
Imports System.IO
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Setting up the GraphServiceClient with a DelegateAuthenticationProvider
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
' Method to convert a Stream to a String
Private Shared Function StreamToString(ByVal stream As Stream) As String
Using reader = New StreamReader(stream)
Return reader.ReadToEnd()
End Using
End Function
' Method to obtain the access token
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' Simplified example, ensure to handle exceptions and errors appropriately.
Imports Microsoft.Graph
Imports IronPdf
Imports System.IO
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Setting up the GraphServiceClient with a DelegateAuthenticationProvider
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
' Method to convert a Stream to a String
Private Shared Function StreamToString(ByVal stream As Stream) As String
Using reader = New StreamReader(stream)
Return reader.ReadToEnd()
End Using
End Function
' Method to obtain the access token
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 ClassKilka kwestii, na które należy zwrócić uwagę w tym kodzie:
- Używamy MSGraph, aby uzyskać dostęp do pliku przechowywanego w OneDrive. Potrzebny będzie identyfikator elementu, który można uzyskać za pośrednictwem interfejsu API Graph.
- W tym przykładzie konwertujemy strumień plików na ciąg znaków. Działa to dobrze w przypadku dokumentów HTML. Jeśli masz do czynienia z plikami binarnymi (takimi jak dokumenty WORD), warto użyć innej metody konwersji tych plików do formatu PDF.
- Metoda RenderHtmlAsPdf z biblioteki IronPDF służy tutaj do tworzenia pliku PDF na podstawie ciągu znaków HTML. Jeśli dokument źródłowy nie jest w formacie HTML, IronPDF oferuje również metody pracy z innymi formatami.
Pamiętaj, że jest to uproszczony przykład. W rzeczywistym zastosowaniu konieczne byłoby bardziej solidne podejście do uwierzytelniania, zarządzanie błędami oraz potencjalnie bardziej płynna obsługa różnych formatów plików. Powinno to jednak stanowić dobry punkt wyjścia do integracji MSGraph i IronPDF w projektach .NET.
Wnioski
Dla programistów pragnących zintegrować możliwości Microsoft 365 ze swoimi aplikacjami C#, MS Graph .NET SDK jest niezbędnym narzędziem. Rozpocznij od eksploracji Informacji o licencjonowaniu i cenach MS Graph .NET SDK zaczynając od $999.
Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczącą ponad 50 osób, obsługującą NASA, Teslę i światowe agencje rządowe.
Powiązane artykuły