public async Task AddGroupsAndUsersAsync(GraphServiceClient graphService, string graphAccessToken) { List <string> newUsers = new List <string>(); #region Create AD Group var groupsDict = new Dictionary <string, Graph.Group>(); XmlNode groupItems = sampleData.SelectSingleNode("//List[@name='AD Groups']"); foreach (XmlNode item in groupItems.ChildNodes) { string displayName = item.Attributes["DisplayName"].Value; string description = item.Attributes["Description"].Value; string mailNickname = item.Attributes["MailNickname"].Value; var group = await GraphServiceExtension.GetGroupByDisplayNameAsync(graphService, displayName); if (group == null) { group = await GraphServiceExtension.AddGroupAsync(graphService, mailNickname, displayName, description); } groupsDict.Add(displayName, group as Graph.Group); } #endregion #region Create AD Users XmlNode userItems = sampleData.SelectSingleNode("//List[@name='AD Users']"); foreach (XmlNode item in userItems) { string displayName = item.Attributes["DisplayName"].Value; string userPrincipalName = item.Attributes["PrincipalName"].Value; string password = item.Attributes["Password"].Value; string ownGroupDisplayName = item.Attributes["GroupsDisplayName"].Value; string jobTitle = item.Attributes["JobTitle"].Value; string companyName = item.Attributes["CompanyName"].Value; string officeLocation = item.Attributes["OfficeLocation"].Value; string mobilePhone = item.Attributes["MobilePhone"].Value; string businessPhone = item.Attributes["BusinessPhone"].Value; var queryUser = (await graphService.Users.Request().Filter(string.Format("displayName eq '{0}'", displayName)).GetAsync()).CurrentPage;//await GraphServiceExtension.GetFirstUserAsync(graphService, i => i.DisplayName == displayName); Graph.User user = queryUser.Count > 0 ? queryUser[0] : null; if (user == null) { List <string> bp = new List <string>(); bp.Add(businessPhone); user = new Graph.User { DisplayName = displayName, UserPrincipalName = userPrincipalName + "@" + AppSettings.DemoSiteCollectionOwner.Split('@')[1], PasswordProfile = new PasswordProfile { Password = password, ForceChangePasswordNextSignIn = false }, UsageLocation = "US", AccountEnabled = true, MailNickname = userPrincipalName, JobTitle = jobTitle, Department = companyName, OfficeLocation = officeLocation, BusinessPhones = bp }; user = await graphService.Users.Request().AddAsync(user); await GraphServiceExtension.AssignLicenseAsync(graphService, user as Graph.User); } if (groupsDict.ContainsKey(ownGroupDisplayName) && (await GraphServiceExtension.GetGroupMembersAsync(graphService, ownGroupDisplayName)) .Where(i => i.UserPrincipalName == user.UserPrincipalName).Count() == 0) { try { await graphService.Groups[groupsDict[ownGroupDisplayName].Id].Members.References.Request().AddAsync(user); } catch { } } newUsers.Add(user.UserPrincipalName); } #endregion AddUsersToSPGroup(newUsers); }
public async Task <ActionResult> AddInspectorExecute(AddInspectorViewModel viewModel) { // Acquire all the fixed resources we'll need. var graphService = await AuthenticationHelper.GetGraphServiceAsync(AADAppSettings.GraphResourceUrl); User candidate = await graphService.Users[viewModel.SelectedCandidate].Request().GetAsync(); Group inspectors = await graphService.GetGroupByDisplayNameAsync("Inspectors"); Group gettingStarted = await graphService.GetGroupByDisplayNameAsync("GettingStarted"); Plan gettingStartedPlan = await PlanService.GetPlanAsync(gettingStarted); Bucket bucket = await PlanService.GetBucketByNameAsync(gettingStartedPlan, "Unstarted"); // Add the user to the GettingStarted group where newcomers share onboarding tasks try { await graphService.Groups[gettingStarted.Id].Members.References.Request().AddAsync(candidate); } catch { // Assume failure means it's already in the group - as it often is during demos! } // Iterate over the 'NewHireTasks' sharepoint list with the new preview API. var site = await SharePointService.GetSiteByPathAsync("/sites/SuiteLevelAppDemo"); NewHireTaskListitem[] listitems = await SharePointService.GetListItemsFromSiteList <NewHireTaskListitem>(site, "NewHireTasks"); foreach (NewHireTaskListitem listItem in listitems) { try { // Make a Planner task in the 'GettingStarted' group for each task in the NewHireTasks list. PlannerTask created = await PlanService.CreateTaskAsync(new PlannerTask { title = listItem.Title, assignedTo = candidate.Id, percentComplete = 0, planId = bucket.planId, bucketId = bucket.id, }); await PlanService.UpdateTaskDescriptionAsync(created, listItem.Description); } catch { // Move on to the next if anything goes wrong. continue; } } // Make sure new user has all the licenses they need. await GraphServiceExtension.AssignLicenseAsync(graphService, candidate); // Add the user to the Inspector's group await graphService.Groups[inspectors.Id].Members.References.Request().AddAsync(candidate); return(View(viewModel)); }
public async Task <Graph.Group> CreateUnifiedGroupForPropertyAsync(GraphServiceClient graphService, string graphAccessToken, ListItem propertyItem, IEnumerable <Graph.User> members) { var propertyTitle = propertyItem["Title"] as string; var propertyOwnerName = propertyItem["sl_owner"] as string; var querypropertyOwners = (await graphService.Users.Request().Filter(string.Format("displayName eq '{0}'", propertyOwnerName)).GetAsync()).CurrentPage; var propertyOwner = querypropertyOwners.Count > 0 ? querypropertyOwners[0] : null; if (propertyOwner == null) { return(null); } // Create Office 365 Group string groupId = string.Empty; dynamic groupJSON = new JObject(); groupJSON.displayName = propertyTitle; groupJSON.mailNickname = propertyTitle.Replace(" ", ""); groupJSON.securityEnabled = false; groupJSON.mailEnabled = true; groupJSON.description = "Property Group"; groupJSON.groupTypes = new JArray("Unified"); HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}groups", AADAppSettings.GraphResourceUrl)); message.Content = new StringContent(groupJSON.ToString(), System.Text.Encoding.UTF8, "application/json"); message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphAccessToken); using (HttpClient client = new HttpClient()) { var responseMessage = await client.SendAsync(message); if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created) { throw new System.Web.Http.HttpResponseException(responseMessage.StatusCode); } var payload = await responseMessage.Content.ReadAsStringAsync(); groupId = JObject.Parse(payload)["id"].ToString(); } var group = await graphService.Groups[groupId].Request().GetAsync() as Graph.Group; // Add users to Office 365 Group var groupMembers = new HashSet <Graph.User>(members); var groupOwners = new HashSet <Graph.User>(); var adminUserName = _currentUserName; var queryAdmins = (await graphService.Users.Request().Filter(string.Format("mail eq '{0}'", adminUserName)).GetAsync()).CurrentPage; var admin = queryAdmins.Count > 0 ? queryAdmins[0] : null; if (admin != null) { groupMembers.Add(admin); groupOwners.Add(admin); } if (propertyOwner != null) { groupMembers.Add(propertyOwner); groupOwners.Add(propertyOwner); } foreach (var user in groupMembers.OfType <Graph.User>()) { try { await GraphServiceExtension.AddUserToGroupMembersAsync(graphService, group, user, graphAccessToken); } catch { } } foreach (var user in groupOwners.OfType <Graph.User>()) { try { await GraphServiceExtension.AddUserToGroupOwnersAsync(graphService, group, user, graphAccessToken); } catch { } } return(group); }