Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ DO-NOT-MERGE-YET] Update to the Graph SDK v5 #859

Draft
wants to merge 9 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 38 additions & 15 deletions src/lib/PnP.Framework/Graph/GraphUtility.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Models.ODataErrors;
using Microsoft.Kiota.Abstractions.Authentication;
using PnP.Framework.Diagnostics;
using System;
using System.Net.Http.Headers;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace PnP.Framework.Graph
{
public class TokenProvider : IAccessTokenProvider
{
public Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = default,
CancellationToken cancellationToken = default)
{
var token = AccessToken;
// get the token and return it in your own way
return Task.FromResult(token);
}
public string AccessToken { get; set; }
public AllowedHostsValidator AllowedHostsValidator { get; }
}

/// <summary>
/// Utility class to perform Graph operations.
/// </summary>
Expand All @@ -30,18 +47,24 @@ public static GraphServiceClient CreateGraphClient(string accessToken, int retry
// Creates a new GraphServiceClient instance using a custom PnPHttpProvider
// which natively supports retry logic for throttled requests
// Default are 10 retries with a base delay of 500ms
var result = new GraphServiceClient(baseUrl, new DelegateAuthenticationProvider(
async (requestMessage) =>
{
await Task.Run(() =>
{
if (!string.IsNullOrEmpty(accessToken))
{
// Configure the HTTP bearer Authorization Header
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
}
});
}), new PnPHttpProvider(retryCount, delay));
//var result = new GraphServiceClient(baseUrl, new DelegateAuthenticationProvider(
// async (requestMessage) =>
// {
// await Task.Run(() =>
// {
// if (!string.IsNullOrEmpty(accessToken))
// {
// // Configure the HTTP bearer Authorization Header
// requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
// }
// });
// }), new PnPHttpProvider(retryCount, delay));

var tokenProvider = new TokenProvider();
tokenProvider.AccessToken = accessToken;

var authenticationProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
var result = new GraphServiceClient(authenticationProvider, baseUrl);

return (result);
}
Expand Down Expand Up @@ -86,9 +109,9 @@ public static Invitation InviteGuestUser(string accessToken, string guestUserEma

// Create the graph client and send the invitation.
GraphServiceClient graphClient = CreateGraphClient(accessToken, azureEnvironment: azureEnvironment);
inviteUserResponse = graphClient.Invitations.Request().AddAsync(invite).Result;
inviteUserResponse = graphClient.Invitations.PostAsync(invite).Result;
}
catch (ServiceException ex)
catch (ODataError ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
Expand Down
426 changes: 190 additions & 236 deletions src/lib/PnP.Framework/Graph/GroupsUtility.cs

Large diffs are not rendered by default.

92 changes: 46 additions & 46 deletions src/lib/PnP.Framework/Graph/PnPHttpProvider.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,52 @@
using Microsoft.Graph;
using PnP.Framework.Utilities;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
//using Microsoft.Graph;
//using PnP.Framework.Utilities;
//using System;
//using System.Net.Http;
//using System.Threading;
//using System.Threading.Tasks;

namespace PnP.Framework.Graph
{
///<summary>
/// Class that deals with PnPHttpProvider methods
///</summary>
public class PnPHttpProvider : HttpProvider, IHttpProvider
{
private readonly string _userAgent;
private readonly PnPHttpRetryHandler _retryHandler;
//namespace PnP.Framework.Graph
//{
// ///<summary>
// /// Class that deals with PnPHttpProvider methods
// ///</summary>
// public class PnPHttpProvider : HttpProvider, IHttpProvider
// {
// private readonly string _userAgent;
// private readonly PnPHttpRetryHandler _retryHandler;

/// <summary>
/// Constructor for the PnPHttpProvider class
/// </summary>
/// <param name="retryCount">Maximum retry Count</param>
/// <param name="delay">Delay Time</param>
/// <param name="userAgent">User-Agent string to set</param>
public PnPHttpProvider(int retryCount = 10, int delay = 500, string userAgent = null) : base()
{
if (retryCount <= 0)
throw new ArgumentException("Provide a retry count greater than zero.");
// /// <summary>
// /// Constructor for the PnPHttpProvider class
// /// </summary>
// /// <param name="retryCount">Maximum retry Count</param>
// /// <param name="delay">Delay Time</param>
// /// <param name="userAgent">User-Agent string to set</param>
// public PnPHttpProvider(int retryCount = 10, int delay = 500, string userAgent = null) : base()
// {
// if (retryCount <= 0)
// throw new ArgumentException("Provide a retry count greater than zero.");

if (delay <= 0)
throw new ArgumentException("Provide a delay greater than zero.");
// if (delay <= 0)
// throw new ArgumentException("Provide a delay greater than zero.");

this._userAgent = userAgent;
this._retryHandler = new PnPHttpRetryHandler(retryCount, delay);
}
// this._userAgent = userAgent;
// this._retryHandler = new PnPHttpRetryHandler(retryCount, delay);
// }

/// <summary>
/// Custom implementation of the IHttpProvider.SendAsync method to handle retry logic
/// </summary>
/// <param name="request">The HTTP Request Message</param>
/// <param name="completionOption">The completion option</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The result of the asynchronous request</returns>
/// <remarks>See here for further details: https://graph.microsoft.io/en-us/docs/overview/errors</remarks>
async Task<HttpResponseMessage> IHttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
// Add the PnP User Agent string
request.Headers.UserAgent.TryParseAdd(string.IsNullOrEmpty(_userAgent) ? $"{PnPCoreUtilities.PnPCoreUserAgent}" : _userAgent);
// /// <summary>
// /// Custom implementation of the IHttpProvider.SendAsync method to handle retry logic
// /// </summary>
// /// <param name="request">The HTTP Request Message</param>
// /// <param name="completionOption">The completion option</param>
// /// <param name="cancellationToken">The cancellation token</param>
// /// <returns>The result of the asynchronous request</returns>
// /// <remarks>See here for further details: https://graph.microsoft.io/en-us/docs/overview/errors</remarks>
// async Task<HttpResponseMessage> IHttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
// {
// // Add the PnP User Agent string
// request.Headers.UserAgent.TryParseAdd(string.IsNullOrEmpty(_userAgent) ? $"{PnPCoreUtilities.PnPCoreUserAgent}" : _userAgent);

return await _retryHandler.SendRetryAsync(request, (r) => base.SendAsync(r, completionOption, cancellationToken), cancellationToken);
}
}
}
// return await _retryHandler.SendRetryAsync(request, (r) => base.SendAsync(r, completionOption, cancellationToken), cancellationToken);
// }
// }
//}
64 changes: 21 additions & 43 deletions src/lib/PnP.Framework/Graph/SubscriptionsUtility.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Models.ODataErrors;
using PnP.Framework.Diagnostics;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -33,7 +35,6 @@ public static Model.Subscription GetSubscription(string accessToken, Guid subscr
var graphClient = GraphUtility.CreateGraphClient(accessToken, retryCount, delay, azureEnvironment: azureEnvironment);

var subscription = await graphClient.Subscriptions[subscriptionId.ToString()]
.Request()
.GetAsync();

var subscriptionModel = MapGraphEntityToModel(subscription);
Expand All @@ -42,7 +43,7 @@ public static Model.Subscription GetSubscription(string accessToken, Guid subscr

return result;
}
catch (ServiceException ex)
catch (ODataError ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
Expand Down Expand Up @@ -76,42 +77,22 @@ public static Model.Subscription GetSubscription(string accessToken, Guid subscr

var graphClient = GraphUtility.CreateGraphClient(accessToken, retryCount, delay, azureEnvironment: azureEnvironment);

var pagedSubscriptions = await graphClient.Subscriptions
.Request()
.GetAsync();

int pageCount = 0;
int currentIndex = 0;
var pagedSubscriptions = await graphClient.Subscriptions
.GetAsync();

while (true)
var pageIterator = PageIterator<Subscription, SubscriptionCollectionResponse>.CreatePageIterator(graphClient, pagedSubscriptions, (subscription) =>
{
pageCount++;

foreach (var s in pagedSubscriptions)
{
currentIndex++;

if (currentIndex >= startIndex)
{
var subscription = MapGraphEntityToModel(s);
subscriptions.Add(subscription);
}
}

if (pagedSubscriptions.NextPageRequest != null && currentIndex < endIndex)
{
pagedSubscriptions = await pagedSubscriptions.NextPageRequest.GetAsync();
}
else
{
break;
}
}
var subscriptionModel = MapGraphEntityToModel(subscription);
subscriptions.Add(subscriptionModel);
return true;
});

await pageIterator.IterateAsync();

return subscriptions;
}).GetAwaiter().GetResult();
}
catch (ServiceException ex)
catch (ODataError ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
Expand Down Expand Up @@ -165,9 +146,8 @@ public static Model.Subscription CreateSubscription(Enums.GraphSubscriptionChang
ClientState = clientState
};

var subscription = await graphClient.Subscriptions
.Request()
.AddAsync(newSubscription);
var subscription = await graphClient.Subscriptions
.PostAsync(newSubscription);

if (subscription == null)
{
Expand All @@ -179,7 +159,7 @@ public static Model.Subscription CreateSubscription(Enums.GraphSubscriptionChang

}).GetAwaiter().GetResult();
}
catch (ServiceException ex)
catch (ODataError ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
Expand Down Expand Up @@ -219,9 +199,8 @@ public static Model.Subscription UpdateSubscription(string subscriptionId, DateT
ExpirationDateTime = expirationDateTime
};

var subscription = await graphClient.Subscriptions[subscriptionId]
.Request()
.UpdateAsync(updatedSubscription);
var subscription = await graphClient.Subscriptions[subscriptionId]
.PatchAsync(updatedSubscription);

if (subscription == null)
{
Expand All @@ -233,7 +212,7 @@ public static Model.Subscription UpdateSubscription(string subscriptionId, DateT

}).GetAwaiter().GetResult();
}
catch (ServiceException ex)
catch (ODataError ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
Expand Down Expand Up @@ -263,13 +242,12 @@ public static void DeleteSubscription(string subscriptionId,
{
var graphClient = GraphUtility.CreateGraphClient(accessToken, retryCount, delay);

await graphClient.Subscriptions[subscriptionId]
.Request()
await graphClient.Subscriptions[subscriptionId]
.DeleteAsync();

}).GetAwaiter().GetResult();
}
catch (ServiceException ex)
catch (ODataError ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
Expand Down
Loading