public async Async.Task GroupCreateExtension() { // Get a groups collection. We'll use the first entry to add the extension. Results in a call to the service. IGraphServiceGroupsCollectionPage groupPage = await graphClient.Groups.Request().GetAsync(); // Create the extension property. OpenTypeExtension newExtension = new OpenTypeExtension(); newExtension.ExtensionName = "com.contoso.trackingKey"; newExtension.AdditionalData = new Dictionary <string, object>(); newExtension.AdditionalData.Add("trackingKeyMajor", "ABC"); newExtension.AdditionalData.Add("trackingKeyMinor", "123"); try { // Add an extension to the group. Results in a call to the service. var extension = await graphClient.Groups[groupPage[0].Id].Extensions.Request().AddAsync(newExtension); // Delete the extension. Results in a call to the service. await graphClient.Groups[groupPage[0].Id].Extensions["com.contoso.trackingKey"].Request().DeleteAsync(); } catch (ServiceException e) { Assert.True(false, e.Error.ToString()); } }
public IEnumerable <List <Group> > GetDistributionGroups(CancellationToken token) { // We will let Graph filter what it can, but functionality seems to be limited for now. // https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options IGraphServiceGroupsCollectionPage page = null; try { page = client.Groups.Request() .Filter("securityEnabled eq false") // Non-security groups .GetAsync(token).Result; } catch (Exception ex) { HandleException(ex, null, messageOnlyExceptions, ""); } while (page != null) { yield return(page.ToList()); if (page.NextPageRequest == null) { break; } page = page.NextPageRequest.GetAsync(token).Result; } }
public IEnumerable <List <Group> > GetMailEnabledSecurityGroups(CancellationToken token) { // We will let Graph filter what it can, but functionality seems to be limited for now. // https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options // Get all security groups // mailEnabled is not available for filtering // See https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#group-entity for details IGraphServiceGroupsCollectionPage page = null; try { page = client.Groups.Request() .Filter("securityEnabled eq true") .GetAsync(token).Result; } catch (Exception ex) { HandleException(ex, null, messageOnlyExceptions, ""); } while (page != null) { yield return(page.ToList()); if (page.NextPageRequest == null) { break; } page = page.NextPageRequest.GetAsync(token).Result; } }
private async Task <Group> GetGroupAsync(GraphServiceClient graphClient) { IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request() .Filter($"startswith(displayName,'{_configuration["GroupName"]}')") .GetAsync(); Group group; bool firstIteration = true; do { if (!firstIteration) { groups = await groups.NextPageRequest .Filter($"startswith(displayName,'{_configuration["GroupName"]}')") .GetAsync(); } firstIteration = false; group = groups.FirstOrDefault(g => g.DisplayName.Equals(_configuration["GroupName"], StringComparison.InvariantCultureIgnoreCase)); } while (group == null && groups?.NextPageRequest != null); return(group); }
public async Task FindGroup_Should_ThrowException_IfResultIsNull() { IGraphServiceGroupsCollectionPage collectionPage = null; _mockGroupsCollectionRequest.Setup(x => x.GetAsync()).Returns(Task.FromResult(collectionPage)); await Assert.ThrowsAsync <EntityNotFoundException>(() => _remoteGraphService.FindGroupAsync(string.Empty)); }
private List <Group> AddGroupToCollection(List <Group> groupsCollection, IGraphServiceGroupsCollectionPage groupsCollectionPage) { foreach (var group in groupsCollectionPage) { groupsCollection.Add(group); } return(groupsCollection); }
public async Task <NeoQueryData> CollectDataAsync() { NeoQueryData querydata = new NeoQueryData(); List <object> propertylist = new List <object>(); try { IGraphServiceGroupsCollectionPage page = await Connector.Instance.Client.Groups.Request().GetAsync(); while (page != null) { foreach (Group group in page.CurrentPage) { string grouptype = group.SecurityEnabled.Value ? "Security" : "Distribution"; bool dynamic = false; foreach (string type in group.GroupTypes) { switch (type) { case "DynamicMembership": dynamic = true; break; case "Unified": this.O365GroupIDs.Add(group.Id); grouptype = "Microsoft365"; break; default: break; } } propertylist.Add(new { ID = group.Id, Dynamic = dynamic, Name = group.DisplayName, Description = group.Description, MailEnabled = group.MailEnabled, Mail = group.Mail, Type = grouptype, OnPremSid = group.OnPremisesSecurityIdentifier }); this.GroupIDs.Add(group.Id); } page = await page.NextPageRequest?.GetAsync(); } } catch { } querydata.Properties = propertylist; return(querydata); }
private static void AddTeamsToTable(IGraphServiceGroupsCollectionPage deltaCollection) { var options = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }; Parallel.ForEach(deltaCollection, options, async team => { await AddTeamToTable(team); }); }
private async Task ConfigurePreconsentAsync(IGraphServiceClient client, string appId) { ServicePrincipal servicePrincipal = await GetServicePrincipalAsync(client, appId).ConfigureAwait(false);; IGraphServiceGroupsCollectionPage groups = await client.Groups.Request().Filter("DisplayName+eq+'AdminAgents'").GetAsync().ConfigureAwait(false); if (groups.Count <= 0) { WriteWarning("Unable to locate the AdminAgents group in Azure AD, so pre-consent configuration was not able to be completed."); return; } await client.Groups[groups[0].Id].Members.References.Request().AddAsync(servicePrincipal).ConfigureAwait(false); }
private async Task <PrincipalsViewModel> MapGroups(IGraphServiceGroupsCollectionPage source) { PrincipalsViewModel result = new PrincipalsViewModel(); if (source != null) { foreach (var g in source) { result.Principals.Add(await MapGroup(g)); } } return(result); }
public static string IndexFiles(IGraphServiceClient client, string downloadDirectory, string collectionName, ILogger log) { Dictionary <string, Dictionary <string, string> > allFiles = new Dictionary <string, Dictionary <string, string> >(); int count = 0; log.LogInformation("Call to the Microsoft Graph in order to access the files in SharePoint."); IGraphServiceGroupsCollectionPage groups = client.Groups.Request().GetAsync().Result; foreach (Group group in groups) { IDriveItemChildrenCollectionPage driveItems = client.Groups[group.Id].Drive.Root.Children.Request().GetAsync().Result; foreach (DriveItem item in driveItems) { string itemId = item.ETag.Replace("\"{", "").Replace("},2\"", ""); Stream content = client.Groups[group.Id].Drive.Items[itemId].Content.Request().GetAsync().Result; //save file in folder to index it from there log.LogInformation("Download file " + item.Name); var fileStream = System.IO.File.Create(downloadDirectory + "/" + item.Name); content.Seek(0, SeekOrigin.Begin); content.CopyTo(fileStream); fileStream.Close(); //save values for file that need to be added log.LogInformation("Extract information for file " + item.Name); Dictionary <string, string> data = new Dictionary <string, string>(); data.Add("fileURL", item.WebUrl); data.Add("fileCreator", item.CreatedBy.User.DisplayName); allFiles.Add(item.Name, data); count++; if (count % 10 == 0) { log.LogInformation("Send request for 10 files and delete them from the local file system."); string json = prepareJSONBody(collectionName, allFiles); SendIndexingRequest(json, downloadDirectory, collectionName); foreach (string fileName in allFiles.Keys) { System.IO.File.Delete(downloadDirectory + "/" + fileName); } allFiles.Clear(); } } } return("Successfully indexed."); }
/// <summary> /// For the signed-in user, displays on the standard output the groups the user is a member of /// </summary> /// <param name="graph">Graph</param> private static async Task DisplayGroupIdsForAllGroupsInMyOrg(IGraphServiceClient graph) { // All the groups in my organization var allGroupsRequest = graph.Groups.Request(); while (allGroupsRequest != null) { IGraphServiceGroupsCollectionPage allGroups = await allGroupsRequest.GetAsync(); foreach (Group group in allGroups) { Console.WriteLine(group.Id); } allGroupsRequest = allGroups.NextPageRequest; } }
public static async Task <string> getGroupUid(string gn) { GraphServiceClient gsc = await AuthenticationHelper.GetGraphServiceClientAsUser(); IGraphServiceGroupsCollectionPage igcp = await gsc.Groups.Request().Filter("displayName eq '" + gn + "'").GetAsync(); IList <Group> gl = igcp.CurrentPage; if (gl.Count != 1) { return(null); } Group g = gl.First(); return(g.AdditionalData["objectId"].ToString()); }
public async Task <Group> FindGroupByDisplayNameOrMail(string value, CancellationToken token) { try { IGraphServiceGroupsCollectionPage groups = await client.Groups.Request() .Filter($"displayName eq '{value}' or mail eq '{value}'") .GetAsync(token); return(groups.FirstOrDefault()); } catch (Exception ex) { Trace.WriteLine(ex, $"Error locating group by displayName or mail using value {value}."); } return(null); }
/// <summary> /// Load 1 or more Groups members from Azure and create in memory groups for them /// </summary> /// <param name="azureGraph"></param> /// <param name="thisGroupAsSet"></param> /// <param name="groupToRetrieve"></param> /// <returns></returns> private async Task GenerateGroupsMembersList_ProcessGroups( GraphServiceClient azureGraph, IGraphServiceGroupsCollectionPage thisGroupAsSet, ProvisionConfigExternalDirectorySync.ISynchronizeGroupToGroup groupToRetrieve) { //Degenerate case: No data here... if ((thisGroupAsSet == null) || (thisGroupAsSet.CurrentPage.Count < 1)) { return; } //============================================================================================ //Get all the groups from the current page of Azure results, and then get any subsequent pages //============================================================================================ do { //Process a;l the groups on this results page var currentPage = thisGroupAsSet.CurrentPage; var currentPage_ItemCount = currentPage.Count; //---------------------------------------------------------------------- //Loop through all the Azure Groups in the current returned page //---------------------------------------------------------------------- for (var idxGroup = 0; idxGroup < currentPage_ItemCount; idxGroup++) { await GenerateGroupsMembersList_ProcessSingleGroup(azureGraph, currentPage[idxGroup], groupToRetrieve); } //----------------------------------------------------------------------- //Advance to the next page (if there is one) //----------------------------------------------------------------------- var requestNextPage = thisGroupAsSet.NextPageRequest; if (requestNextPage != null) { thisGroupAsSet = await requestNextPage.GetAsync(); } else { thisGroupAsSet = null; } } while (thisGroupAsSet != null); //Until we have no more Azure Group Pages to look through }
// Get groups. // This snippet requires an admin work account. public async Task<List<ResultsItem>> GetGroups(GraphServiceClient graphClient) { List<ResultsItem> items = new List<ResultsItem>(); // Get groups. IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request().GetAsync(); if (groups?.Count > 0) { foreach (Group group in groups) { items.Add(new ResultsItem { Display = group.DisplayName, Id = group.Id }); } } return items; }
// Get Office 365 (unified) groups. // This snippet requires an admin work account. public async Task <List <ResultsItem> > GetUnifiedGroups(GraphServiceClient graphClient) { List <ResultsItem> items = new List <ResultsItem>(); // Get unified groups. IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request().Filter("groupTypes/any(a:a%20eq%20'unified')").GetAsync(); if (groups?.Count > 0) { foreach (Group group in groups) { items.Add(new ResultsItem { Display = group.DisplayName, Id = group.Id }); } } return(items); }
// Get groups. // This snippet requires an admin work account. public async Task <List <ResultsItem> > GetGroups() { List <ResultsItem> items = new List <ResultsItem>(); // Get groups. IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request(requestOptions) .WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()) .GetAsync(); if (groups?.Count > 0) { foreach (Group group in groups) { items.Add(new ResultsItem { Display = group.DisplayName, Id = group.Id }); } } return(items); }
public async Task <ApplicationGroup> GetGroup(string azureAdObjectId, string userObjectId) { var graphClient = GetAuthenticatedClient(userObjectId); List <ApplicationGroup> items = new List <ApplicationGroup>(); // Get groups by ID - TODO IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request().GetAsync(); if (groups?.Count > 0) { foreach (Group group in groups) { items.Add(new ApplicationGroup { DisplayName = group.DisplayName, AzureAdObjectIdentifier = group.Id }); } } return(items.FirstOrDefault()); }
public IEnumerable <List <Group> > GetGroups(CancellationToken token) { IGraphServiceGroupsCollectionPage page = null; try { page = client.Groups.Request().GetAsync(token).Result; } catch (Exception ex) { HandleException(ex, null, messageOnlyExceptions, ""); } while (page != null) { yield return(page.ToList()); if (page.NextPageRequest == null) { break; } page = page.NextPageRequest.GetAsync(token).Result; } }
public IEnumerable <List <Group> > GetSpecialGroups(string groupType, CancellationToken token) { IGraphServiceGroupsCollectionPage page = null; try { page = client.Groups.Request().GetAsync(token).Result; } catch (Exception ex) { HandleException(ex, null, messageOnlyExceptions, ""); } while (page != null) { yield return(page.Where(x => x.GroupTypes.Contains(groupType, StringComparer.InvariantCultureIgnoreCase)).ToList()); if (page.NextPageRequest == null) { break; } page = page.NextPageRequest.GetAsync(token).Result; } }
public async Async.Task GroupCreateTeam() { try { // Get a groups collection. We'll use the first entry to add the team. Results in a call to the service. IGraphServiceGroupsCollectionPage groupPage = await graphClient.Groups.Request().GetAsync(); // Create a team with settings. Team team = new Team() { MemberSettings = new TeamMemberSettings() { AllowCreateUpdateChannels = true } }; // Add a team to the group. Results in a call to the service. await graphClient.Groups[groupPage[8].Id].Team.Request().PutAsync(team); } catch (ServiceException e) { Assert.True(false, e.Error.ToString()); } }
static async Task <string> GetUniqueMailAlias(CreateGroupRequest request) { string name = string.IsNullOrEmpty(request.Alias) ? request.Name : request.Alias; string prefix = request.Prefix; string suffix = request.Suffix; string mailNickname = ReRemoveIllegalChars.Replace(name, "").ToLower(); prefix = ReRemoveIllegalChars.Replace(prefix + "", "").ToLower(); suffix = ReRemoveIllegalChars.Replace(suffix + "", "").ToLower(); string prefixSeparator = string.Empty; if (!string.IsNullOrWhiteSpace(prefix) && request.UsePrefixInMailAlias) { prefixSeparator = string.IsNullOrWhiteSpace(request.PrefixSeparator) ? "-" : request.PrefixSeparator; } string suffixSeparator = string.Empty; if (!string.IsNullOrWhiteSpace(suffix) && request.UseSuffixInMailAlias) { suffixSeparator = string.IsNullOrWhiteSpace(request.SuffixSeparator) ? "-" : request.SuffixSeparator; } int maxCharsInEmail = 40 - prefix.Length - prefixSeparator.Length - suffixSeparator.Length - suffix.Length; if (mailNickname.Length > maxCharsInEmail) { mailNickname = mailNickname.Substring(0, maxCharsInEmail); } mailNickname = $"{prefix}{prefixSeparator}{mailNickname}{suffixSeparator}{suffix}"; if (string.IsNullOrWhiteSpace(mailNickname)) { mailNickname = new Random().Next(0, 9).ToString(); } GraphServiceClient client = ConnectADAL.GetGraphClient(); while (true) { IGraphServiceGroupsCollectionPage groupExist = await client.Groups.Request() .Filter($"groupTypes/any(grp: grp eq 'Unified') and MailNickname eq '{mailNickname}'").Top(1) .GetAsync(); if (groupExist.Count > 0) { string number = new Random().Next(0, 9).ToString(); if (string.IsNullOrWhiteSpace(suffixSeparator + suffix)) { mailNickname += new Random().Next(0, 9).ToString(); } else { int suffixIdx = mailNickname.IndexOf(suffixSeparator + suffix); mailNickname = mailNickname.Insert(suffixIdx, number); } } else { break; } } return(mailNickname); }
/// <summary> /// /// </summary> /// <param name="graphClient"></param> /// <param name="emailID"></param> /// <param name="groupName"></param> /// <returns>Return value represents returnStatus, message, userObjectID, groupID respectively</returns> public async Task <Tuple <bool, string, string, string> > AssociateUserWithAGroup(GraphServiceClient graphClient, string emailID, string groupName) { bool ActionStatus = false; string message = string.Empty; string groupid = "", userObjectID = ""; if (graphClient == null || string.IsNullOrEmpty(emailID) || string.IsNullOrEmpty(groupName)) { return(new Tuple <bool, string, string, string>(ActionStatus, "Invalid input", null, null)); } try { IGraphServiceUsersCollectionPage _usersFilteredId = await graphClient.Users.Request().Filter($"Mail eq '" + emailID + "' or UserPrincipalName eq '" + emailID + "'").GetAsync(); userObjectID = _usersFilteredId.Select(a => a.Id).SingleOrDefault().ToString(); if (!string.IsNullOrEmpty(userObjectID)) { //find group Id by groupname IGraphServiceGroupsCollectionPage groupsCollectionPage = graphClient.Groups.Request().Filter($"DisplayName eq '" + groupName + "'").GetAsync().Result; if (groupsCollectionPage != null) { groupid = groupsCollectionPage.Select(a => a.Id).SingleOrDefault().ToString(); if (groupid != null) { //check if the user is already associated var associatedmember = await graphClient.Groups[groupid].Members.Request().GetAsync(); if (associatedmember.Where(a => a.Id == userObjectID).FirstOrDefault() == null) { Microsoft.Graph.User userToAdd = await graphClient.Users[userObjectID].Request().GetAsync(); await graphClient.Groups[groupid].Members.References.Request().AddAsync(userToAdd); ActionStatus = true; message = "User association with group was successful"; } else { message = "User already associated with the group"; } } else { message = "Invalid group"; } } else { message = "Invalid group"; } } else { message = "Invalid user"; } } catch (Exception ex) { message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : ""); } return(new Tuple <bool, string, string, string>(ActionStatus, message, userObjectID, groupid)); }
private async Task<PrincipalsViewModel> MapGroups(IGraphServiceGroupsCollectionPage source) { PrincipalsViewModel result = new PrincipalsViewModel(); if (source != null) { foreach (var g in source) { result.Principals.Add(await MapGroup(g)); } } return result; }
/// <summary> /// Gets all members from group and applies roles /// </summary> /// <param name="graphServiceClient"></param> /// <param name="groupId"></param> /// <param name="roleId"></param> /// <param name="groups"></param> /// <returns></returns> private async static Task <List <string> > GetMembersfromGroup(GraphServiceClient graphServiceClient, string groupId, string roleName, IGraphServiceGroupsCollectionPage groups, IGraphServiceDirectoryRolesCollectionPage directoryRole, IGraphServiceDirectoryRoleTemplatesCollectionPage directoryRoleTemplate) { List <string> groupRoles = new List <string>(); try { string roleId = await GetRoleByName(graphServiceClient : graphServiceClient, roleName : roleName, directoryRole : directoryRole, directoryRoleTemplate : directoryRoleTemplate); if (!string.IsNullOrEmpty(roleId)) { TableBatchOperation batchOperation = new TableBatchOperation(); do { foreach (var group in groups) { List <string> members = new List <string>(); GroupRoleEntity groupRoleEntity = new GroupRoleEntity(); var users = await graphServiceClient.Groups[group.Id].Members.Request().GetAsync(); var groupInfo = await graphServiceClient.Groups[group.Id].Request().GetAsync(); var groupName = groupInfo.DisplayName; if (group.Id == groupId) { do { Console.WriteLine($"\n{group.Id}, {group.DisplayName}"); Console.WriteLine("------"); foreach (var user in users) { members.Add(user.Id); try { await graphServiceClient.DirectoryRoles[roleId].Members.References.Request().AddAsync(user); Console.WriteLine($"Assigning role to: {user.Id}"); groupRoles.Add($"Group: {groupName} - Role: {roleName} - UserId: {user.Id}"); } catch { Console.WriteLine($"{user.Id} already contains role {roleId}"); } } }while (users.NextPageRequest != null && (users = await users.NextPageRequest.GetAsync()).Count > 0); groupRoleEntity = await StorageHelper.CreateTableEntry(graphServiceClient, group.Id, roleId, members); Console.WriteLine("CreateTableEntry workedS"); if (groupRoleEntity != null) { batchOperation.InsertOrMerge(groupRoleEntity); } } } }while (groups.NextPageRequest != null && (groups = await groups.NextPageRequest.GetAsync()).Count > 0); if (batchOperation != null) { await StorageHelper.TableBatchOperation(graphServiceClient, batchOperation); } } return(groupRoles); } catch (ArgumentException ex) { string errorMsg = "Get members from group method failure."; string exMsg = ex.Message; await ErrorHandling.ErrorEvent(errorMsg, exMsg); } return(null); }