
MS Graph .NET (Geliştiriciler için Nasıl Çalışır)
MS Graph .NET, Azure Active Directory (Azure AD) ekosisteminin önemli bir parçası olan Microsoft Graph API ile etkileşimler için bir veri erişim aracıdır. Microsoft Graph, Microsoft 365 içinde veri ve zekaya açılan bir kapıdır. Geliştiricilerin çeşitli Microsoft hizmetleri üzerinde veri erişimi, yönetimi ve analizi yapmasına olanak tanır. Microsoft Graph istemci kütüphanesi, API ile etkileşim kurmayı kolaylaştıran bir dizi yöntem sunarak bu süreci basitleştirir.
IronPDF, .NET uygulamaları için PDF belgeleri oluşturma kütüphanesidir. HTML'yi PDF'ye dönüştürür, bu da raporlar, faturalar ve belgeleri otomatik olarak oluşturmak için kullanışlıdır. IronPDF .NET uygulamalarıyla iyi çalışır ve PDF oluşturma için basit bir yaklaşım sunar.
MS Graph .NET ve IronPDF'nin birleşimi, geliştiricilere Microsoft 365 verilerini manipüle edebilen ve PDF belgeleri üretebilen uygulamalar oluşturma imkanı sağlar. Bu kombinasyon, Microsoft hizmetlerinden veri almayı gerektiren ve bu verileri standart bir belge formatında sunmayı gerektiren iş uygulamaları geliştirmek için güçlüdür.
MS Graph .NET ile Başlarken
.NET Projelerinde MS Graph .NET Kurulumu
MS Graph .NET'i etkili bir şekilde kullanmak için, özellikle .NET Core projelerinde kullanıcı kimlikleri ile çalışırken, .NET projenizi ayarlamak ilk adımdır. İşte adımlar:
- NuGet Paket Yöneticisi'ni açın.
- Microsoft.Graph arayın.
- Microsoft.Graph paketini yükleyin.

Bu işlem projeye MS Graph .NET'i ekler. Şimdi, bununla kodlamaya başlamaya hazırsınız.
Temel Kod Örneği
Diyelim ki, mevcut kullanıcının profil bilgilerini almak istiyorsunuz. İşte basit bir kod örneği:
// 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}!")Bu kod örneği, Azure AD kimlik doğrulaması için bir istemci sırrı kullanarak GraphServiceClient'in yeni bir örneğini oluşturmayı göstermektedir. Kimlik doğrulamada istemci kimlik bilgilerini kullanır. Daha sonra, mevcut kullanıcının gösterilen adını alır. Bunu takiben, MS Graph .NET ve kimlik doğrulama sağlayıcı yapılandırmalarınızın projeye eklendiğinden emin olun.
MS Graph .NET Özellikleri
Kullanıcı Epostalarını Alın
Bir kullanıcının Microsoft hesabı postasında epostaları almak için Mail.Read izni kullanırsınız. En son e-postaların nasıl listeye alınacağı şu şekilde:
// 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 messageBu kod, kullanıcının gelen kutusundaki en son 10 e-postanın konularını listeler.
Bir Eposta Gönder
Bir e-posta göndermek, bir Mesaj nesnesi oluşturmayı ve gönderimini içerir:
// 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()Bu, basit bir metin gövdesine sahip bir e-posta gönderir.
Takvim Olaylarını Yönetmek
Kullanıcının takvimine bir etkinlik eklemek için:
// 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])Bu kod, takvime yeni bir etkinlik planlar.
OneDrive Dosyalarına Erişim
Kullanıcının OneDrive kökünden dosyaları listelemek için:
// 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 fileBu kod, OneDrive'ın kök dizinindeki dosyaların adlarını yazdırır.
Takımlarla Çalışmak
Kullanıcının bir parçası olduğu takımların listesini almak için:
// 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 teamBu, kullanıcının bir parçası olduğu Takımların adlarını listeler.
Bu özelliklerin her biri, MS Graph .NET'in gücünü ve çok yönlülüğünü gösterir. Uygulamalarınıza Microsoft 365 hizmetlerini nasıl entegre edebileceğinizi gösterir.
MS Graph .NET'i IronPDF ile Entegre Etme

PDF'lerle .NET uygulamalarınızda çalışmak istiyorsanız, IronPDF Kütüphanesi .NET Geliştiricileri İçin sağlam bir seçimdir. Bu kütüphane, uygulamalarınıza başka PDF araçları veya yazılımlara ihtiyaç duymadan PDF dosyalarını okuma, oluşturma ve manipüle etme yeteneği kazandırır.
Kullanım Durumu: IronPDF'i MS Graph .NET ile Birleştirmek
Microsoft 365'ten belgeler almak, örneğin raporlar veya faturalar, ve bunları PDF'lere dönüştürmek gereken bir uygulama oluşturduğunuzu hayal edin. MS Graph .NET, OneDrive veya SharePoint'te saklanan dosyalar da dahil olmak üzere Microsoft 365 kaynaklarıyla etkileşime geçmenizi sağlar. IronPDF ardından bu belgeleri alarak PDF'lere dönüştürmede kullanılabilir. Bu kombinasyon, özellikle otomatik rapor oluşturma veya e-postaların ve eklerin PDF formatında arşivlenmesi için kullanışlıdır.
Kod Örneği: MS Graph'tan PDF'e
Basit bir örneği inceleyelim. MS Graph .NET kullanarak OneDrive'dan bir belge alacağız ve ardından IronPDF kullanarak bu belgeyi PDF'e dönüştüreceğiz. MSGraph ile kimlik doğrulamanızı zaten ayarladığınızı varsayıyorum; diğer durumda, başlamak için Microsoft'un sitesinde yeterince dokümantasyon var.
// 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 ClassBu kodda dikkat edilmesi gereken birkaç şey:
- OneDrive'da saklanan bir dosyaya erişmek için MSGraph kullanıyoruz. Bu, Graph API aracılığıyla elde edebileceğiniz öğenin kimliğine ihtiyacınız olacak.
- Bu örnek için dosya akışını bir dizeye dönüştürüyoruz. Bu, HTML belgeleri için iyi çalışır. İkili dosyalarla (Word belgeleri gibi) çalışıyorsanız, bu dosyaları PDF'lere dönüştürmek için farklı bir yöntem kullanmak isteyebilirsiniz.
- IronPDF'ten RenderHtmlAsPdf yöntemi burada bir HTML dizesinden PDF oluşturmak için kullanılır. Kaynak belgeniz HTML değilse, IronPDF diğer formatlarla çalışmak için de yöntemler sunar.
Unutmayın, bu basitleştirilmiş bir örnek. Gerçek dünyadaki bir uygulamada, kimlik doğrulamayı daha sağlam bir şekilde ele almanız, hataları yönetmeniz ve potansiyel olarak farklı dosya formatlarıyla daha zarif bir şekilde baş etmeniz gerekir. Ama bu, MSGraph ve IronPDF'i .NET projelerinize entegre etmek için iyi bir başlangıç noktası sunmalıdır.
Sonuç
C# uygulamalarınıza Microsoft 365 yeteneklerini entegre etmeyi isteyen geliştiriciler için MS Graph .NET SDK önemli bir araçtır. Başlamak için MS Graph .NET SDK Lisanslama ve Fiyatlandırma Bilgilerini $999'de inceleyin.

Jacob Mellor, Iron Software'de Baş Teknoloji Yöneticisidir ve C# PDF teknolojisinde öncü bir mühendisdir. Iron Software'ın ana kod tabanının ilk geliştiricisi olarak, CEO Cameron Rimington ile birlikte şirketin ürün mimarisini 50'den fazla kişilik bir şirkete dönüştürmüştür ve NASA, Tesla ve dünya genelindeki devlet kurumlarına hizmet etmektedir.
İlgili Makaleler


