Skip to content

Instantly share code, notes, and snippets.

@AsishP
Created August 9, 2018 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AsishP/7700fa38119628f5ef5d3bdfd2fb024e to your computer and use it in GitHub Desktop.
Save AsishP/7700fa38119628f5ef5d3bdfd2fb024e to your computer and use it in GitHub Desktop.
using OfficeDevPnP.Core.Framework.Graph;
using Microsoft.Graph;
using Microsoft.SharePoint.Client;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
var authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = null;
string token = "";
Task authtask = Task.Run(async () => authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId, clientCred));
authtask.Wait();
//List of Owner Emails
List<string> Owners = new List<string>();
if (authenticationResult != null)
{
token = authenticationResult.AccessToken;
var group = UnifiedGroupsUtility.ListUnifiedGroups(token, mailNickname: alias).Where(result => result.MailNickname.ToLower().Equals(alias.ToLower())).First();
if (group != null)
{
string groupId = group.GroupId;
if (Owners.Count > 0)
try
{
Task runTask = Task.Run(async() => await updateGroupOwner(token, groupId, assetOwners));
runTask.Wait();
}
catch(Exception ex)
{
log.Info("Exception while adding owners " + ex.Message);
}
}
}
private async Task updateGroupOwner(string token, string groupId, List<string> assetOwners)
{
GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async (requestMessage) =>
{
if (!String.IsNullOrEmpty(token))
{
// Configure the HTTP bearer Authorization Header
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}
}), new PnPHttpProvider(10, 500));
var groupToUpdate = await graphClient.Groups[groupId].Request().GetAsync();
foreach (var o in Owners)
{
var ownerQuery = await graphClient.Users
.Request()
.Filter($"userPrincipalName eq '{o}'")
.GetAsync();
var owner = ownerQuery.FirstOrDefault();
if (owner != null)
{
try
{
// And if any, add it to the collection of group's owners and members
await graphClient.Groups[groupToUpdate.Id].Members.References.Request().AddAsync(owner);
await graphClient.Groups[groupToUpdate.Id].Owners.References.Request().AddAsync(owner);
}
catch (ServiceException ex)
{
if (ex.Error.Code == "Request_BadRequest" &&
ex.Error.Message.Contains("added object references already exist"))
{
// Skip any already existing owner
}
else
{
throw ex;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment