protected override void ExecuteCmdlet() { var url = PnPConnection.Current.Url; if (ParameterSpecified(nameof(Site))) { url = Site.Url; } var site = this.Tenant.GetSiteByUrl(url); if (!ParameterSpecified(nameof(Group))) { var groups = ClientContext.LoadQuery(site.RootWeb.SiteGroups.IncludeWithDefaultProperties(g => g.Users, g => g.Title, g => g.OwnerTitle, g => g.Owner.LoginName, g => g.LoginName)); ClientContext.ExecuteQueryRetry(); foreach (var group in groups) { var siteGroup = new SiteGroup(ClientContext, Tenant, group, site.RootWeb); WriteObject(siteGroup); } } else { var group = site.RootWeb.SiteGroups.GetByName(Group); ClientContext.Load(group, g => g.Users, g => g.Title, g => g.OwnerTitle, g => g.Owner.LoginName, g => g.LoginName); ClientContext.ExecuteQueryRetry(); var siteGroup = new SiteGroup(ClientContext, Tenant, group, site.RootWeb); WriteObject(siteGroup); } }
/// <summary> /// Does sanity checking and error logging on missing data in groups /// </summary> /// <param name="group"></param> private void SanityCheckGroup(SiteGroup group, XmlNode xmlNode) { if (string.IsNullOrWhiteSpace(group.Id)) { _onlineSession.StatusLog.AddError(group.Name + " is missing a group ID. Not returned from server! xml=" + xmlNode.OuterXml); } }
protected override void ExecuteCmdlet() { var url = PnPConnection.Current.Url; if (ParameterSpecified(nameof(Site))) { url = Site.Url; } var rootWeb = this.Tenant.GetSiteByUrl(url).RootWeb; var roleDefinitions = GetRoleDefinitions(rootWeb); var roleDefCollection = new RoleDefinitionBindingCollection(ClientContext); foreach (var permissionToAdd in PermissionLevels) { if (!roleDefinitions.Contains(permissionToAdd)) { throw new PSArgumentException($"Permission level {permissionToAdd} not defined in site"); } var existingRoleDef = rootWeb.RoleDefinitions.GetByName(permissionToAdd); roleDefCollection.Add(existingRoleDef); } var groupCI = new GroupCreationInformation(); groupCI.Title = Name; var group = rootWeb.SiteGroups.Add(groupCI); rootWeb.RoleAssignments.Add(group, roleDefCollection); ClientContext.Load(group, g => g.Title, g => g.LoginName, g => g.Users, g => g.Owner.LoginName, g => g.OwnerTitle); ClientContext.ExecuteQueryRetry(); var siteGroup = new SiteGroup(ClientContext, Tenant, group, rootWeb); WriteObject(siteGroup); }
public IHttpActionResult GetSiteList() { //ISiteService siteService = EngineContext.Current.Resolve<ISiteService>(); IAqiManager aqiManager = EngineContext.Current.Resolve <IAqiManager>(); IAqiGradeService gradeService = EngineContext.Current.Resolve <IAqiGradeService>(); var allSite = aqiManager.GetAllStation(); List <SiteGroup> gp = new List <SiteGroup>(); List <SiteModel> result = new List <SiteModel>(); foreach (var site in allSite) { SiteGroup g = gp.Where(p => p.GroupName == site.FirstPinyin).FirstOrDefault(); if (null == g) { g = new SiteGroup() { GroupName = site.FirstPinyin }; gp.Add(g); } SiteModel sm = new SiteModel(); sm.Id = site.StationCode; sm.Name = site.StationName; sm.Group = site.FirstPinyin; sm.Latitude = site.Latitude; sm.Longitude = site.Longitude; sm.Aqi = aqiManager.GetSiteCurrentAqi(site.StationCode)[0]; sm.Grade = gradeService.CalcGrade(sm.Aqi).Grade; g.Items.Add(sm); } return(Ok(gp.OrderBy(g => g.GroupName).ToList())); }
void item_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName != "IsChanged") { SiteGroup item = (SiteGroup)sender; item.IsChanged = true; } }
public async Task CanCreateNewAssociatedGroupsInNewScriptSite_AfterAsyncRename() { var newCommSiteUrl = string.Empty; var siteTitle = "Dummy"; ProvisioningTemplate template = new ProvisioningTemplate(); SiteGroup ownersGroup = new SiteGroup() { // this should map to existing group Title = siteTitle + " Owners", }; template.Security.SiteGroups.Add(ownersGroup); template.Security.AssociatedOwnerGroup = ownersGroup.Title; using (var clientContext = TestCommon.CreateClientContext()) { newCommSiteUrl = await CreateCommunicationSite(clientContext, siteTitle, true); } try { using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl)) { LoadAssociatedOwnerGroupsData(ctx); var oldOwnerGroupId = ctx.Web.AssociatedOwnerGroup.Id; var oldMemberGroupId = ctx.Web.AssociatedMemberGroup.Id; var oldVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id; var oldGroupCount = ctx.Web.SiteGroups.Count; var parser = new TokenParser(ctx.Web, template); // wait for async rename await WaitForAsyncGroupTitleChangeWithTimeout(ctx); // now provision - new site titles are in place new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); LoadAssociatedOwnerGroupsData(ctx); var newOwnerGroupId = ctx.Web.AssociatedOwnerGroup.Id; var newMemberGroupId = ctx.Web.AssociatedMemberGroup.Id; var newVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id; var newGroupCount = ctx.Web.SiteGroups.Count; Assert.AreEqual(oldOwnerGroupId, newOwnerGroupId, "Expected owners group to stay the same"); Assert.AreEqual(oldMemberGroupId, newMemberGroupId, "Expected members group to stay the same"); Assert.AreEqual(oldVisitorGroupId, newVisitorGroupId, "Expected visitors group to stay the same"); Assert.AreEqual(oldGroupCount, newGroupCount, "Expected no new groups to be created"); } } finally { using (var clientContext = TestCommon.CreateTenantClientContext()) { var tenant = new Tenant(clientContext); tenant.DeleteSiteCollection(newCommSiteUrl, false); } } }
void gvwSiteGroup_AddingNewDataItem(object sender, Telerik.Windows.Controls.GridView.GridViewAddingNewEventArgs e) { SiteGroup newItem = new SiteGroup(); newItem.CreatedBy = newItem.UpdatedBy = Globals.UserLogin.UserName; newItem.IsChanged = true; newItem.Sites = new List <Site>(); e.NewObject = newItem; }
void siteGroup_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName != "IsChanged") { SiteGroup item = (SiteGroup)sender; item.UpdatedBy = Globals.UserLogin.UserName; item.IsChanged = true; } }
void gvwSiteGroup_SelectionChanged(object sender, SelectionChangeEventArgs e) { if (gvwSiteGroup.SelectedItem != null) { SiteGroup sg = gvwSiteGroup.SelectedItem as SiteGroup; if (sg != null) { _selectedSiteGroup = sg.GroupName; gvwSites.ItemsSource = sg.Sites; } } }
public void CanProvisionNewAssociatedGroup() { ProvisioningTemplate template = new ProvisioningTemplate(); SiteGroup membersGroup = new SiteGroup() { Title = string.Format("Test_New MemberGroup_{0}", DateTime.Now.Ticks), }; string ownersGroupTitle = string.Format("Test_New OwnerGroup2_{0}", DateTime.Now.Ticks); template.Security.SiteGroups.Add(membersGroup); template.Security.AssociatedMemberGroup = membersGroup.Title; template.Security.AssociatedOwnerGroup = ownersGroupTitle; template.Security.AssociatedVisitorGroup = ""; using (var clientContext = TestCommon.CreateClientContext()) { Web web = clientContext.Web; var parser = new TokenParser(clientContext.Web, template); new ObjectSiteSecurity().ProvisionObjects(web, template, parser, new ProvisioningTemplateApplyingInformation()); } using (var clientContext = TestCommon.CreateClientContext()) { Web web = clientContext.Web; clientContext.Load(web, w => w.AssociatedOwnerGroup.Title, w => w.AssociatedMemberGroup.Title, w => w.AssociatedVisitorGroup); clientContext.ExecuteQuery(); if (!web.AssociatedOwnerGroup.ServerObjectIsNull()) { web.AssociatedOwnerGroup.EnsureProperty(g => g.Title); } if (!web.AssociatedMemberGroup.ServerObjectIsNull()) { web.AssociatedMemberGroup.EnsureProperty(g => g.Title); } if (!web.AssociatedVisitorGroup.ServerObjectIsNull()) { web.AssociatedVisitorGroup.EnsureProperty(g => g.Title); } Assert.AreNotEqual(ownersGroupTitle, web.AssociatedOwnerGroup.Title, "Associated owner group ID mismatch."); Assert.AreEqual(membersGroup.Title, web.AssociatedMemberGroup.Title, "Associated member group ID mismatch."); //Assert.IsTrue(web.AssociatedVisitorGroup.ServerObjectIsNull()); } }
void btnSave_Click(object sender, RoutedEventArgs e) { if (gvwSiteGroup.SelectedItem != null) { SiteGroup sg = gvwSiteGroup.SelectedItem as SiteGroup; if (sg != null) { _selectedSiteGroup = sg.GroupName; } } List <SiteGroup> saveList = (List <SiteGroup>)gvwSiteGroup.ItemsSource; //Check valid data : Name should not be duplicated if (saveList != null && saveList.Count > 0) { for (int i = 0; i < saveList.Count - 1; i++) { SiteGroup firstItem = saveList[i]; for (int j = i + 1; j < saveList.Count; j++) { SiteGroup secondItem = saveList[j]; if (firstItem.GroupName == secondItem.GroupName) { MessageBox.Show(ResourceHelper.GetReourceValue("SiteGroupAdminPage_DuplicatedName"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK); return; } } } } //Get delete items : foreach (SiteGroup oldItem in _originalItemSource) { bool isDeleted = true; foreach (SiteGroup saveItem in saveList) { if (saveItem.SiteGroupId == oldItem.SiteGroupId) { isDeleted = false; break; } } if (isDeleted) { oldItem.IsDeleted = true; saveList.Add(oldItem); } } Globals.IsBusy = true; DataServiceHelper.SaveSiteGroupsAsync(saveList, SaveSiteGroupCompleted); }
/// <summary> /// Process a single group (exporting its members) /// </summary> /// <param name="thisGroup"></param> private void GenerateGroupsMembersList_FromTableauSite_ProcessSingleGroup(SiteGroup thisGroup) { //Get or create the group manager that will record the users in the group var thisGroupManager = this.SetManagerForGroups.GetManagerForGroup_CreateIfNeeded( thisGroup.Name, AttemptParseGrantLicenseText(thisGroup.GrantLicenseMode), thisGroup.SiteMinimumRoleOrNull ); //Add each user to the group foreach (var thisUserInGroup in thisGroup.Users) { thisGroupManager.AddUser(thisUserInGroup.Name); } }
void gvwSites_Deleting(object sender, GridViewDeletingEventArgs e) { MessageBoxResult result = MessageBox.Show(ResourceHelper.GetReourceValue("Common_ConfirmDeleteNoParam"), ResourceHelper.GetReourceValue("Common_ConfirmationRequired"), MessageBoxButton.OKCancel); if (result == MessageBoxResult.Cancel) { e.Cancel = true; } else { SiteGroup sg = gvwSiteGroup.SelectedItem as SiteGroup; if (sg != null) { sg.IsChanged = true; } } }
void uiSiteGroups_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if (uiSiteGroups.SelectedItem != null && Convert.ToInt32(uiSiteGroups.SelectedValue) > 0) { SiteGroup selectedSiteGroup = (SiteGroup)uiSiteGroups.SelectedItem; chkWholeOrg.IsChecked = false; List <Site> siteList = new List <Site>(); siteList.Add(new Site()); if (selectedSiteGroup.Sites != null) { siteList.AddRange(selectedSiteGroup.Sites); } //Check site security : siteList = CheckSiteLevelSecurity(siteList); uiSites.ItemsSource = siteList; if (this.UserRoleAuthData != null && this.UserRoleAuthData.SiteId > 0) { if (siteList.Count(i => i.SiteId == this.UserRoleAuthData.SiteId) > 0) { uiSites.SelectedValue = this.UserRoleAuthData.SiteId; } else { if (IsFirstLoad) { //this login user are not allowed to see the role of other sites. So, hide this record. this.Visibility = System.Windows.Visibility.Collapsed; } else { uiSites.SelectedIndex = 0; } } } else { uiSites.SelectedIndex = 0; } } else { uiSites.ItemsSource = null; } }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); var roleDefinitionName = "UT_RoleDefinition"; SiteGroup membersGroup = new SiteGroup() { Title = string.Format("Test_New Group_{0}", DateTime.Now.Ticks), }; template.Security.SiteGroups.Add(membersGroup); template.Security.AssociatedMemberGroup = membersGroup.Title; foreach (var user in admins) { template.Security.AdditionalMembers.Add(new User() { Name = user.LoginName }); } template.Security.SiteSecurityPermissions.RoleDefinitions.Add(new PnP.Framework.Provisioning.Model.RoleDefinition() { Name = roleDefinitionName }); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var memberGroup = ctx.Web.AssociatedMemberGroup; var roleDefinitions = ctx.Web.RoleDefinitions; ctx.Load(ctx.Web, p => p.AssociatedMemberGroup); ctx.Load(memberGroup, g => g.Users); ctx.Load(roleDefinitions); ctx.ExecuteQueryRetry(); foreach (var user in admins) { var existingUser = memberGroup.Users.GetByLoginName(user.LoginName); ctx.Load(existingUser); ctx.ExecuteQueryRetry(); Assert.IsNotNull(existingUser); } Assert.IsTrue(roleDefinitions.Any(rd => rd.Name == roleDefinitionName), "New role definition wasn't found after provisioning"); } }
/// <summary> /// Add a specific user into the Server Site's group /// </summary> /// <param name="userEmail"></param> /// <param name="thisProvisionGroup"></param> /// <param name="siteUsersList"></param> private void Execute_ProvisionGroups_SingleGroup_AddUser( TableauServerSignIn siteSignIn, string userEmail, SiteGroup siteGroup, WorkingListSiteUsers siteUsersList) { var siteUserToAddToGroup = siteUsersList.FindUserByName(userEmail); //Sanity test. If the user is not a member of the site, they cannot be added to a group if (siteUserToAddToGroup == null) { CSVRecord_ErrorUpdatingUser(userEmail, "", "", "User not on site. Cannot be added to group"); _statusLogs.AddError("User not on site. Cannot be added to group, " + userEmail); return; //FAILED } switch (_provisionInstructions.ActionForMissingGroupMembers) { case ProvisionUserInstructions.MissingGroupMemberAction.Add: //Call the server and add the user var addUserToGroup = new SendAddUserToGroup(siteSignIn, siteUserToAddToGroup.Id, siteGroup.Id); bool userGroupAddSuccess = addUserToGroup.ExecuteRequest(); if (userGroupAddSuccess) { //SUCCESS CSVRecord_GroupModified_WithUser(siteGroup.Name, "added member", siteUserToAddToGroup.Name, ""); _statusLogs.AddStatus("Group membership: Added " + siteUserToAddToGroup.Name + " to group " + siteGroup.Name); } else { CSVRecord_ErrorUpdatingUser(userEmail, "", "", "User could not be added to group " + siteGroup.Name); _statusLogs.AddError("Group membership error: Failed to add " + siteUserToAddToGroup.Name + " to group " + siteGroup.Name); } return; case ProvisionUserInstructions.MissingGroupMemberAction.Report: //We are instructed to NOT REALLY add the user, jsut report CSVRecord_GroupModified_WithUser(siteGroup.Name, "SIMULATED added member", siteUserToAddToGroup.Name, ""); return; default: IwsDiagnostics.Assert(false, "814-433: Unknown action"); throw new Exception("814-433: Unknown action"); } }
public async Task <IActionResult> Create([Bind("Memco_cd,Memco_nm,Sort_no,Use_yn,Memo1,Memo2,Input_dt,Update_dt,Input_id,Update_id")] SiteGroup siteGroup) { //var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; //var userName = User.FindFirstValue(ClaimTypes.Name); //var userEmail = User.FindFirstValue(ClaimTypes.Email); siteGroup.Input_dt = DateTime.Now; siteGroup.Update_dt = DateTime.Now; siteGroup.Input_id = User.FindFirst(ClaimTypes.Name).Value; siteGroup.Update_id = User.FindFirst(ClaimTypes.Name).Value; if (ModelState.IsValid) { _context.Add(siteGroup); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(siteGroup)); }
void btnAddSite_Click(object sender, RoutedEventArgs e) { if (ucSitePicker.SelectedSite != null && ucSitePicker.SelectedSite.SiteId > 0 && gvwSiteGroup.SelectedItem != null) { SiteGroup sg = gvwSiteGroup.SelectedItem as SiteGroup; if (sg != null) { if (sg.Sites.Count(i => i.SiteId == ucSitePicker.SelectedSite.SiteId) == 0) { sg.IsChanged = true; sg.Sites.Add(ucSitePicker.SelectedSite); gvwSites.ItemsSource = null; gvwSites.ItemsSource = sg.Sites; } else { MessageBox.Show(ResourceHelper.GetReourceValue("SiteGroupAdminPage_SiteAlreadyExist"), ResourceHelper.GetReourceValue("Common_ValidationError"), MessageBoxButton.OK); } } } }
/// <summary> /// CSV rows for each member of a group /// </summary> /// <param name="group"></param> private void AddGroupUsersData(SiteGroup group) { var usersInGroup = group.Users; //Nothing to add? if (usersInGroup == null) { return; } string groupId = group.Id; string groupName = group.Name; foreach (var thisUser in usersInGroup) { this.AddKeyValuePairs( new string[] { ContentType //1 , ContentId //2 , ContentName //3 , SiteRole //4 , ContentUserId //5 , ContentUserName //6 , ContentGroupId //7 , ContentGroupName //8 , DeveloperNotes //9 }, new string[] { "group-member" //1 , thisUser.Id //2 , thisUser.Name //3 , thisUser.SiteRole //4 , thisUser.Id //5 , thisUser.Name //6 , groupId //7 , groupName //8 , thisUser.DeveloperNotes //9 }); } }
private void HandleAdditionalMembers(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { if (!siteRequest.IsSiteCollectionRequest) { var memberGroup = new SiteGroup() { AllowMembersEditMembership = false, AutoAcceptRequestToJoinLeave = false, AllowRequestToJoinLeave = true, Description = siteRequest.Title + " Members Group", Title = siteRequest.Title + " Members Group", OnlyAllowMembersViewMembership = true, Owner = siteRequest.SiteOwner.Email, RequestToJoinLeaveEmailSetting = siteRequest.SiteOwner.Email, }; foreach (var member in siteRequest.AdditionalMembers) { User user = new User(); user.Name = member.Name; memberGroup.Members.Add(user); } provisioningTemplate.Security.SiteGroups.Add(memberGroup); provisioningTemplate.Security.SiteSecurityPermissions.RoleAssignments.Add(new RoleAssignment() { Principal = siteRequest.Title + " Members Group", RoleDefinition = "Contribute" }); } else { foreach (var _Admin in siteRequest.AdditionalAdministrators) { User _user = new User(); _user.Name = _Admin.Name; provisioningTemplate.Security.AdditionalAdministrators.Add(_user); } } }
void gvwSiteGroup_Deleting(object sender, GridViewDeletingEventArgs e) { if (e.Items != null && e.Items.Count() > 0) { SiteGroup siteGroup = e.Items.First() as SiteGroup; if (siteGroup != null) { if (siteGroup.CanDelete) { MessageBoxResult result = MessageBox.Show(ResourceHelper.GetReourceValue("Common_ConfirmDeleteNoParam"), ResourceHelper.GetReourceValue("Common_ConfirmationRequired"), MessageBoxButton.OKCancel); if (result == MessageBoxResult.Cancel) { e.Cancel = true; } } else { MessageBoxResult result = MessageBox.Show(string.Format(ResourceHelper.GetReourceValue("Common_DeleteFailed"), siteGroup.GroupName), ResourceHelper.GetReourceValue("Common_OperationFailed"), MessageBoxButton.OK); e.Cancel = true; } } } }
public async Task <IActionResult> Edit(int id, [Bind("Memco_cd,Memco_nm,Sort_no,Use_yn,Memo1,Memo2,Input_dt,Update_dt,Input_id,Update_id")] SiteGroup siteGroup) { //var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; //var userName = User.FindFirstValue(ClaimTypes.Name); //var userEmail = User.FindFirstValue(ClaimTypes.Email); siteGroup.Update_dt = DateTime.Now; siteGroup.Update_id = User.FindFirst(ClaimTypes.Name).Value; if (id != siteGroup.Memco_cd) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(siteGroup); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SiteGroupExists(siteGroup.Memco_cd)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Details), new { id })); } return(View(siteGroup)); }
/// <summary> /// Does sanity checking and error logging on missing data in groups /// </summary> /// <param name="group"></param> private void SanityCheckGroup(SiteGroup group, XmlNode xmlNode) { if(string.IsNullOrWhiteSpace(group.Id)) { _onlineSession.StatusLog.AddError(group.Name + " is missing a group ID. Not returned from server! xml=" + xmlNode.OuterXml); } }
/// <summary> /// Get a page's worth of Groups /// </summary> /// <param name="onlineGroups"></param> /// <param name="pageToRequest">Page # we are requesting (1 based)</param> /// <param name="totalNumberPages">Total # of pages of data that Server can return us</param> private void ExecuteRequest_ForPage( List<SiteGroup> onlineGroups, int pageToRequest, out int totalNumberPages) { int pageSize = _onlineUrls.PageSize; //Create a web request, in including the users logged-in auth information in the request headers var urlQuery = _onlineUrls.Url_GroupsList(_onlineSession, pageSize, pageToRequest); var webRequest = CreateLoggedInWebRequest(urlQuery); webRequest.Method = "GET"; _onlineSession.StatusLog.AddStatus("Web request: " + urlQuery, -10); var response = GetWebReponseLogErrors(webRequest, "get groups list"); var xmlDoc = GetWebResponseAsXml(response); //Get all the group nodes var nsManager = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline"); var groups = xmlDoc.SelectNodes("//iwsOnline:group", nsManager); //Get information for each of the data sources foreach (XmlNode itemXml in groups) { SiteGroup thisGroup = null; try { thisGroup = new SiteGroup( itemXml, null); //We'll get and add the list of users later (see below) onlineGroups.Add(thisGroup); SanityCheckGroup(thisGroup, itemXml); } catch(Exception exGetGroup) { AppDiagnostics.Assert(false, "Group parse error"); _onlineSession.StatusLog.AddError("Error parsing group: " + itemXml.OuterXml + ", " + exGetGroup.Message); } //============================================================== //Get the set of users in the group //============================================================== if (thisGroup != null) { try { var downloadUsersInGroup = new DownloadUsersListInGroup( _onlineUrls, _onlineSession, thisGroup.Id); downloadUsersInGroup.ExecuteRequest(); thisGroup.AddUsers(downloadUsersInGroup.Users); } catch (Exception exGetUsers) { _onlineSession.StatusLog.AddError("Error parsing group's users: " + exGetUsers.Message); } } } //end: foreach //------------------------------------------------------------------- //Get the updated page-count //------------------------------------------------------------------- totalNumberPages = DownloadPaginationHelper.GetNumberOfPagesFromPagination( xmlDoc.SelectSingleNode("//iwsOnline:pagination", nsManager), pageSize); }
/// <summary> /// REMOVE an undesired user from a group /// </summary> /// <param name="siteSignIn"></param> /// <param name="userRemoveFromGroup"></param> /// <param name="siteGroup"></param> private void Execute_ProvisionGroups_RemoveSingleUser(TableauServerSignIn siteSignIn, SiteUser userRemoveFromGroup, SiteGroup siteGroup) { _statusLogs.AddStatus("Attempting to remove the user " + userRemoveFromGroup.Name + " from group " + siteGroup.Name); switch (_provisionInstructions.ActionForUnexpectedGroupMembers) { case ProvisionUserInstructions.UnexpectedGroupMemberAction.Delete: var deleteUserFromGroup = new SendDeleteUserFromGroup(siteSignIn, userRemoveFromGroup.Id, siteGroup.Id); bool wasSuccess = deleteUserFromGroup.ExecuteRequest(); if (wasSuccess) { //SUCCESS CSVRecord_GroupModified_WithUser(siteGroup.Name, "removed member", userRemoveFromGroup.Name, ""); _statusLogs.AddStatus("Group membership: Removed " + userRemoveFromGroup.Name + " from group " + siteGroup.Name); } else { CSVRecord_Error(userRemoveFromGroup.Name, "", "", "User could not be removed to group " + siteGroup.Name); _statusLogs.AddError("Group membership error: Failed to remove " + userRemoveFromGroup.Name + " to group " + siteGroup.Name); } return; case ProvisionUserInstructions.UnexpectedGroupMemberAction.Report: //We are instructed to NOT REALLY DELETE the user from the group, jsut report CSVRecord_GroupModified_WithUser(siteGroup.Name, "SIMULATED removed member", userRemoveFromGroup.Name, ""); return; default: IwsDiagnostics.Assert(false, "814-433: Unknown action"); throw new Exception("814-433: Unknown action"); } }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { web.EnsureProperties(w => w.HasUniqueRoleAssignments, w => w.Title); // Changed by Paolo Pialorsi to embrace the new sub-site attributes for break role inheritance and copy role assignments // if this is a sub site then we're not creating security entities as by default security is inherited from the root site if (web.IsSubSite() && !web.HasUniqueRoleAssignments) { return(template); } var ownerGroup = web.AssociatedOwnerGroup; var memberGroup = web.AssociatedMemberGroup; var visitorGroup = web.AssociatedVisitorGroup; web.Context.ExecuteQueryRetry(); if (!ownerGroup.ServerObjectIsNull.Value) { web.Context.Load(ownerGroup, o => o.Id, o => o.Users, o => o.Title); } if (!memberGroup.ServerObjectIsNull.Value) { web.Context.Load(memberGroup, o => o.Id, o => o.Users, o => o.Title); } if (!visitorGroup.ServerObjectIsNull.Value) { web.Context.Load(visitorGroup, o => o.Id, o => o.Users, o => o.Title); } web.Context.ExecuteQueryRetry(); List <int> associatedGroupIds = new List <int>(); var owners = new List <User>(); var members = new List <User>(); var visitors = new List <User>(); if (!ownerGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(ownerGroup.Id); foreach (var member in ownerGroup.Users) { owners.Add(new User() { Name = member.LoginName }); } } if (!memberGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(memberGroup.Id); foreach (var member in memberGroup.Users) { members.Add(new User() { Name = member.LoginName }); } } if (!visitorGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(visitorGroup.Id); foreach (var member in visitorGroup.Users) { visitors.Add(new User() { Name = member.LoginName }); } } var siteSecurity = new SiteSecurity(); siteSecurity.AdditionalOwners.AddRange(owners); siteSecurity.AdditionalMembers.AddRange(members); siteSecurity.AdditionalVisitors.AddRange(visitors); var query = from user in web.SiteUsers where user.IsSiteAdmin select user; var allUsers = web.Context.LoadQuery(query); web.Context.ExecuteQueryRetry(); var admins = new List <User>(); foreach (var member in allUsers) { admins.Add(new User() { Name = member.LoginName }); } siteSecurity.AdditionalAdministrators.AddRange(admins); if (creationInfo.IncludeSiteGroups) { web.Context.Load(web.SiteGroups, o => o.IncludeWithDefaultProperties( gr => gr.Id, gr => gr.Title, gr => gr.AllowMembersEditMembership, gr => gr.AutoAcceptRequestToJoinLeave, gr => gr.AllowRequestToJoinLeave, gr => gr.Description, gr => gr.Users.Include(u => u.LoginName), gr => gr.OnlyAllowMembersViewMembership, gr => gr.Owner.LoginName, gr => gr.RequestToJoinLeaveEmailSetting )); web.Context.ExecuteQueryRetry(); if (web.IsSubSite()) { WriteMessage("You are requesting to export sitegroups from a subweb. Notice that ALL sitegroups from the site collection are included in the result.", ProvisioningMessageType.Warning); } foreach (var group in web.SiteGroups.AsEnumerable().Where(o => !associatedGroupIds.Contains(o.Id))) { try { scope.LogDebug("Processing group {0}", group.Title); var siteGroup = new SiteGroup() { Title = !string.IsNullOrEmpty(web.Title) ? group.Title.Replace(web.Title, "{sitename}") : group.Title, AllowMembersEditMembership = group.AllowMembersEditMembership, AutoAcceptRequestToJoinLeave = group.AutoAcceptRequestToJoinLeave, AllowRequestToJoinLeave = group.AllowRequestToJoinLeave, Description = group.Description, OnlyAllowMembersViewMembership = group.OnlyAllowMembersViewMembership, Owner = ReplaceGroupTokens(web, group.Owner.LoginName), RequestToJoinLeaveEmailSetting = group.RequestToJoinLeaveEmailSetting }; if (String.IsNullOrEmpty(siteGroup.Description)) { var groupItem = web.SiteUserInfoList.GetItemById(group.Id); web.Context.Load(groupItem); web.Context.ExecuteQueryRetry(); var groupNotes = (String)groupItem["Notes"]; if (!String.IsNullOrEmpty(groupNotes)) { siteGroup.Description = groupNotes; } } foreach (var member in group.Users) { scope.LogDebug("Processing member {0} of group {0}", member.LoginName, group.Title); siteGroup.Members.Add(new User() { Name = member.LoginName }); } siteSecurity.SiteGroups.Add(siteGroup); } catch (Exception ee) { scope.LogError(ee.StackTrace); scope.LogError(ee.Message); scope.LogError(ee.InnerException.StackTrace); } } } var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(r => r.Name, r => r.Description, r => r.BasePermissions, r => r.RoleTypeKind)); web.Context.ExecuteQueryRetry(); if (web.HasUniqueRoleAssignments) { var permissionKeys = Enum.GetNames(typeof(PermissionKind)); if (!web.IsSubSite()) { foreach (var webRoleDefinition in webRoleDefinitions) { if (webRoleDefinition.RoleTypeKind == RoleType.None) { scope.LogDebug("Processing custom role definition {0}", webRoleDefinition.Name); var modelRoleDefinitions = new Model.RoleDefinition(); modelRoleDefinitions.Description = webRoleDefinition.Description; modelRoleDefinitions.Name = webRoleDefinition.Name; foreach (var permissionKey in permissionKeys) { scope.LogDebug("Processing custom permissionKey definition {0}", permissionKey); var permissionKind = (PermissionKind)Enum.Parse(typeof(PermissionKind), permissionKey); if (webRoleDefinition.BasePermissions.Has(permissionKind)) { modelRoleDefinitions.Permissions.Add(permissionKind); } } siteSecurity.SiteSecurityPermissions.RoleDefinitions.Add(modelRoleDefinitions); } else { scope.LogDebug("Skipping OOTB role definition {0}", webRoleDefinition.Name); } } } var webRoleAssignments = web.Context.LoadQuery(web.RoleAssignments.Include( r => r.RoleDefinitionBindings.Include( rd => rd.Name, rd => rd.RoleTypeKind), r => r.Member.LoginName, r => r.Member.PrincipalType)); web.Context.ExecuteQueryRetry(); foreach (var webRoleAssignment in webRoleAssignments) { scope.LogDebug("Processing Role Assignment {0}", webRoleAssignment.ToString()); if (webRoleAssignment.Member.PrincipalType == PrincipalType.SharePointGroup && !creationInfo.IncludeSiteGroups) { continue; } if (webRoleAssignment.Member.LoginName != "Excel Services Viewers") { foreach (var roleDefinition in webRoleAssignment.RoleDefinitionBindings) { if (roleDefinition.RoleTypeKind != RoleType.Guest) { var modelRoleAssignment = new Model.RoleAssignment(); var roleDefinitionValue = roleDefinition.Name; if (roleDefinition.RoleTypeKind != RoleType.None) { // Replace with token roleDefinitionValue = $"{{roledefinition:{roleDefinition.RoleTypeKind}}}"; } modelRoleAssignment.RoleDefinition = roleDefinitionValue; if (webRoleAssignment.Member.PrincipalType == PrincipalType.SharePointGroup) { modelRoleAssignment.Principal = ReplaceGroupTokens(web, webRoleAssignment.Member.LoginName); } else { modelRoleAssignment.Principal = webRoleAssignment.Member.LoginName; } siteSecurity.SiteSecurityPermissions.RoleAssignments.Add(modelRoleAssignment); } } } } } template.Security = siteSecurity; // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { // if this is a sub site then we're not creating security entities as by default security is inherited from the root site if (web.IsSubSite()) { return template; } web.Context.Load(web, w => w.HasUniqueRoleAssignments, w => w.Title); var ownerGroup = web.AssociatedOwnerGroup; var memberGroup = web.AssociatedMemberGroup; var visitorGroup = web.AssociatedVisitorGroup; web.Context.ExecuteQueryRetry(); if (!ownerGroup.ServerObjectIsNull.Value) { web.Context.Load(ownerGroup, o => o.Id, o => o.Users, o => o.Title); } if (!memberGroup.ServerObjectIsNull.Value) { web.Context.Load(memberGroup, o => o.Id, o => o.Users, o => o.Title); } if (!visitorGroup.ServerObjectIsNull.Value) { web.Context.Load(visitorGroup, o => o.Id, o => o.Users, o => o.Title); } web.Context.ExecuteQueryRetry(); List<int> associatedGroupIds = new List<int>(); var owners = new List<User>(); var members = new List<User>(); var visitors = new List<User>(); if (!ownerGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(ownerGroup.Id); foreach (var member in ownerGroup.Users) { owners.Add(new User() { Name = member.LoginName }); } } if (!memberGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(memberGroup.Id); foreach (var member in memberGroup.Users) { members.Add(new User() { Name = member.LoginName }); } } if (!visitorGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(visitorGroup.Id); foreach (var member in visitorGroup.Users) { visitors.Add(new User() { Name = member.LoginName }); } } var siteSecurity = new SiteSecurity(); siteSecurity.AdditionalOwners.AddRange(owners); siteSecurity.AdditionalMembers.AddRange(members); siteSecurity.AdditionalVisitors.AddRange(visitors); var query = from user in web.SiteUsers where user.IsSiteAdmin select user; var allUsers = web.Context.LoadQuery(query); web.Context.ExecuteQueryRetry(); var admins = new List<User>(); foreach (var member in allUsers) { admins.Add(new User() { Name = member.LoginName }); } siteSecurity.AdditionalAdministrators.AddRange(admins); if (creationInfo.IncludeSiteGroups) { web.Context.Load(web.SiteGroups, o => o.IncludeWithDefaultProperties( gr => gr.Title, gr => gr.AllowMembersEditMembership, gr => gr.AutoAcceptRequestToJoinLeave, gr => gr.AllowRequestToJoinLeave, gr => gr.Description, gr => gr.Users.Include(u => u.LoginName), gr => gr.OnlyAllowMembersViewMembership, gr => gr.Owner.LoginName, gr => gr.RequestToJoinLeaveEmailSetting )); web.Context.ExecuteQueryRetry(); foreach (var group in web.SiteGroups.AsEnumerable().Where(o => !associatedGroupIds.Contains(o.Id))) { scope.LogDebug("Processing group {0}", group.Title); var siteGroup = new SiteGroup() { Title = group.Title.Replace(web.Title, "{sitename}"), AllowMembersEditMembership = group.AllowMembersEditMembership, AutoAcceptRequestToJoinLeave = group.AutoAcceptRequestToJoinLeave, AllowRequestToJoinLeave = group.AllowRequestToJoinLeave, Description = group.Description, OnlyAllowMembersViewMembership = group.OnlyAllowMembersViewMembership, Owner = ReplaceGroupTokens(web, group.Owner.LoginName), RequestToJoinLeaveEmailSetting = group.RequestToJoinLeaveEmailSetting }; foreach (var member in group.Users) { siteGroup.Members.Add(new User() { Name = member.LoginName }); } siteSecurity.SiteGroups.Add(siteGroup); } } var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(r => r.Name, r => r.Description, r => r.BasePermissions, r => r.RoleTypeKind)); web.Context.ExecuteQueryRetry(); if (web.HasUniqueRoleAssignments) { var permissionKeys = Enum.GetNames(typeof(PermissionKind)); foreach (var webRoleDefinition in webRoleDefinitions) { if (webRoleDefinition.RoleTypeKind == RoleType.None) { scope.LogDebug("Processing custom role definition {0}", webRoleDefinition.Name); var modelRoleDefinitions = new Model.RoleDefinition(); modelRoleDefinitions.Description = webRoleDefinition.Description; modelRoleDefinitions.Name = webRoleDefinition.Name; var permissions = new List<PermissionKind>(); foreach (var permissionKey in permissionKeys) { var permissionKind = (PermissionKind)Enum.Parse(typeof(PermissionKind), permissionKey); if (webRoleDefinition.BasePermissions.Has(permissionKind)) { modelRoleDefinitions.Permissions.Add(permissionKind); } } siteSecurity.SiteSecurityPermissions.RoleDefinitions.Add(modelRoleDefinitions); } else { scope.LogDebug("Skipping OOTB role definition {0}", webRoleDefinition.Name); } } var webRoleAssignments = web.Context.LoadQuery(web.RoleAssignments.Include( r => r.RoleDefinitionBindings.Include( rd => rd.Name, rd => rd.RoleTypeKind), r => r.Member.LoginName)); web.Context.ExecuteQueryRetry(); foreach (var webRoleAssignment in webRoleAssignments) { if (webRoleAssignment.Member.LoginName != "Excel Services Viewers") { foreach (var roleDefinition in webRoleAssignment.RoleDefinitionBindings) { if (roleDefinition.RoleTypeKind != RoleType.Guest) { var modelRoleAssignment = new Model.RoleAssignment(); modelRoleAssignment.RoleDefinition = roleDefinition.Name; modelRoleAssignment.Principal = ReplaceGroupTokens(web, webRoleAssignment.Member.LoginName); siteSecurity.SiteSecurityPermissions.RoleAssignments.Add(modelRoleAssignment); } } } } template.Security = siteSecurity; } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return template; }
/// <summary> /// Get a page's worth of Groups /// </summary> /// <param name="onlineGroups"></param> /// <param name="pageToRequest">Page # we are requesting (1 based)</param> /// <param name="totalNumberPages">Total # of pages of data that Server can return us</param> private void ExecuteRequest_ForPage( List <SiteGroup> onlineGroups, int pageToRequest, bool downloadMemberList, out int totalNumberPages) { int pageSize = _onlineUrls.PageSize; //Create a web request, in including the users logged-in auth information in the request headers var urlQuery = _onlineUrls.Url_GroupsList(_onlineSession, pageSize, pageToRequest); _onlineSession.StatusLog.AddStatus("Web request: " + urlQuery, -10); XmlDocument xmlDoc = ResourceSafe_PerformWebRequest_GetXmlDocument(urlQuery, "get groups list"); //Get all the group nodes var nsManager = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline"); var groups = xmlDoc.SelectNodes("//iwsOnline:group", nsManager); //Get information for each of the data sources foreach (XmlNode itemXml in groups) { SiteGroup thisGroup = null; try { thisGroup = new SiteGroup( itemXml, null); //We'll get and add the list of users later (see below) onlineGroups.Add(thisGroup); SanityCheckGroup(thisGroup, itemXml); } catch (Exception exGetGroup) { AppDiagnostics.Assert(false, "Group parse error"); _onlineSession.StatusLog.AddError("Error parsing group: " + itemXml.OuterXml + ", " + exGetGroup.Message); } //============================================================== //Get the set of users in the group //============================================================== if ((thisGroup != null) && (downloadMemberList)) { try { var downloadUsersInGroup = new DownloadUsersListInGroup( _onlineSession, thisGroup.Id); downloadUsersInGroup.ExecuteRequest(); thisGroup.AddUsers(downloadUsersInGroup.Users); } catch (Exception exGetUsers) { _onlineSession.StatusLog.AddError("Error parsing group's users: " + exGetUsers.Message); } } } //end: foreach //------------------------------------------------------------------- //Get the updated page-count //------------------------------------------------------------------- totalNumberPages = DownloadPaginationHelper.GetNumberOfPagesFromPagination( xmlDoc.SelectSingleNode("//iwsOnline:pagination", nsManager), pageSize); }
/// <summary> /// Adds to the list /// </summary> /// <param name="newGroup"></param> internal void AddGroup(SiteGroup newGroup) { _groups.Add(newGroup); }
public async Task CanMapToExistingGroupsInNewScriptSite() { if (TestCommon.AppOnlyTesting()) { Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only"); } var newCommSiteUrl = string.Empty; ProvisioningTemplate template = new ProvisioningTemplate(); // check setting of owner group with a configuration that would also create the group var ownerGroupTitle = string.Format("Test_New OWNER Group_{0}", DateTime.Now.Ticks); SiteGroup ownerGroup = new SiteGroup() { Title = ownerGroupTitle }; template.Security.AssociatedOwnerGroup = ownerGroup.Title; template.Security.SiteGroups.Add(ownerGroup); // check setting of member group with a configuration that only works if the group already exists in the web var memberGroupTitle = string.Format("Test_New MEMBER Group_{0}", DateTime.Now.Ticks); template.Security.AssociatedMemberGroup = memberGroupTitle; using (var clientContext = TestCommon.CreateClientContext()) { newCommSiteUrl = await CreateCommunicationSite(clientContext, "Dummy", true); } try { using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl)) { // pre-create owner and member group to test mapping ctx.Web.SiteGroups.Add(new GroupCreationInformation() { Title = ownerGroupTitle }); ctx.Web.SiteGroups.Add(new GroupCreationInformation() { Title = memberGroupTitle }); ctx.ExecuteQueryRetry(); ctx.Load(ctx.Web, w => w.SiteGroups.Include( g => g.Id, g => g.Title), w => w.AssociatedVisitorGroup); ctx.ExecuteQueryRetry(); var newOwnerGroup = ctx.Web.SiteGroups.First(g => g.Title == ownerGroupTitle); var newMemberGroup = ctx.Web.SiteGroups.First(g => g.Title == memberGroupTitle); var oldAssociatedVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id; var parser = new TokenParser(ctx.Web, template); new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); LoadAssociatedOwnerGroupsData(ctx, true); var associatedOwnerGroupId = ctx.Web.AssociatedOwnerGroup.Id; var associatedMemberGroupId = ctx.Web.AssociatedMemberGroup.Id; var associatedVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id; Assert.AreEqual(newOwnerGroup.Id, associatedOwnerGroupId, "Expected owners group to change"); Assert.AreEqual(newMemberGroup.Id, associatedMemberGroupId, "Expected members group to change"); Assert.AreEqual(oldAssociatedVisitorGroupId, associatedVisitorGroupId, "Expected visitors group to stay the same"); } } finally { using (var clientContext = TestCommon.CreateTenantClientContext()) { var tenant = new Tenant(clientContext); tenant.DeleteSiteCollection(newCommSiteUrl, false); } } }
public async Task CanCreateNewAssociatedGroupsInNewScriptSite_CreateNewAssociatedGroup() { if (TestCommon.AppOnlyTesting()) { Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only"); } var newCommSiteUrl = string.Empty; ProvisioningTemplate template = new ProvisioningTemplate(); SiteGroup ownersGroup = new SiteGroup() { Title = string.Format("Test_New Group_{0}", DateTime.Now.Ticks), }; template.Security.SiteGroups.Add(ownersGroup); template.Security.AssociatedOwnerGroup = ownersGroup.Title; using (var clientContext = TestCommon.CreateClientContext()) { newCommSiteUrl = await CreateCommunicationSite(clientContext, "Dummy", true); } try { using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl)) { LoadAssociatedOwnerGroupsData(ctx); var oldOwnerGroupId = ctx.Web.AssociatedOwnerGroup.Id; var oldMemberGroupId = ctx.Web.AssociatedMemberGroup.Id; var oldVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id; var oldSiteGroupCount = ctx.Web.SiteGroups.Count; var parser = new TokenParser(ctx.Web, template); new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); await WaitForAsyncGroupTitleChangeWithTimeout(ctx); LoadAssociatedOwnerGroupsData(ctx, true); var newOwnerGroupId = ctx.Web.AssociatedOwnerGroup.Id; var newMemberGroupId = ctx.Web.AssociatedMemberGroup.Id; var newVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id; var newSiteGroupsCount = ctx.Web.SiteGroups.Count; var group = ctx.Web.SiteGroups.First(sg => sg.Title == ownersGroup.Title); Assert.AreEqual(group.Id, newOwnerGroupId, "Expected owners group to change"); Assert.AreEqual(oldMemberGroupId, newMemberGroupId, "Expected members group to stay the same"); Assert.AreEqual(oldVisitorGroupId, newVisitorGroupId, "Expected visitors group to stay the same"); Assert.AreEqual(oldSiteGroupCount + 1, newSiteGroupsCount, "Expected only one group to be created"); // and apply a second time to be sure this works as well new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); LoadAssociatedOwnerGroupsData(ctx, true); Assert.AreEqual(newOwnerGroupId, ctx.Web.AssociatedOwnerGroup.Id, "Expected owners group to stay the same"); Assert.AreEqual(newMemberGroupId, ctx.Web.AssociatedMemberGroup.Id, "Expected members group to stay the same"); Assert.AreEqual(newVisitorGroupId, ctx.Web.AssociatedVisitorGroup.Id, "Expected visitors group to stay the same"); Assert.AreEqual(newSiteGroupsCount, ctx.Web.SiteGroups.Count, "Expected no new groups to be created"); } } finally { using (var clientContext = TestCommon.CreateTenantClientContext()) { var tenant = new Tenant(clientContext); tenant.DeleteSiteCollection(newCommSiteUrl, false); } } }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { // if this is a sub site then we're not creating security entities as by default security is inherited from the root site if (web.IsSubSite()) { return(template); } web.Context.Load(web, w => w.HasUniqueRoleAssignments, w => w.Title); var ownerGroup = web.AssociatedOwnerGroup; var memberGroup = web.AssociatedMemberGroup; var visitorGroup = web.AssociatedVisitorGroup; web.Context.ExecuteQueryRetry(); if (!ownerGroup.ServerObjectIsNull.Value) { web.Context.Load(ownerGroup, o => o.Id, o => o.Users, o => o.Title); } if (!memberGroup.ServerObjectIsNull.Value) { web.Context.Load(memberGroup, o => o.Id, o => o.Users, o => o.Title); } if (!visitorGroup.ServerObjectIsNull.Value) { web.Context.Load(visitorGroup, o => o.Id, o => o.Users, o => o.Title); } web.Context.ExecuteQueryRetry(); List <int> associatedGroupIds = new List <int>(); var owners = new List <User>(); var members = new List <User>(); var visitors = new List <User>(); if (!ownerGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(ownerGroup.Id); foreach (var member in ownerGroup.Users) { owners.Add(new User() { Name = member.LoginName }); } } if (!memberGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(memberGroup.Id); foreach (var member in memberGroup.Users) { members.Add(new User() { Name = member.LoginName }); } } if (!visitorGroup.ServerObjectIsNull.Value) { associatedGroupIds.Add(visitorGroup.Id); foreach (var member in visitorGroup.Users) { visitors.Add(new User() { Name = member.LoginName }); } } var siteSecurity = new SiteSecurity(); siteSecurity.AdditionalOwners.AddRange(owners); siteSecurity.AdditionalMembers.AddRange(members); siteSecurity.AdditionalVisitors.AddRange(visitors); var query = from user in web.SiteUsers where user.IsSiteAdmin select user; var allUsers = web.Context.LoadQuery(query); web.Context.ExecuteQueryRetry(); var admins = new List <User>(); foreach (var member in allUsers) { admins.Add(new User() { Name = member.LoginName }); } siteSecurity.AdditionalAdministrators.AddRange(admins); if (creationInfo.IncludeSiteGroups) { web.Context.Load(web.SiteGroups, o => o.IncludeWithDefaultProperties( gr => gr.Title, gr => gr.AllowMembersEditMembership, gr => gr.AutoAcceptRequestToJoinLeave, gr => gr.AllowRequestToJoinLeave, gr => gr.Description, gr => gr.Users.Include(u => u.LoginName), gr => gr.OnlyAllowMembersViewMembership, gr => gr.Owner.LoginName, gr => gr.RequestToJoinLeaveEmailSetting )); web.Context.ExecuteQueryRetry(); foreach (var group in web.SiteGroups.AsEnumerable().Where(o => !associatedGroupIds.Contains(o.Id))) { scope.LogDebug("Processing group {0}", group.Title); var siteGroup = new SiteGroup() { Title = group.Title.Replace(web.Title, "{sitename}"), AllowMembersEditMembership = group.AllowMembersEditMembership, AutoAcceptRequestToJoinLeave = group.AutoAcceptRequestToJoinLeave, AllowRequestToJoinLeave = group.AllowRequestToJoinLeave, Description = group.Description, OnlyAllowMembersViewMembership = group.OnlyAllowMembersViewMembership, Owner = ReplaceGroupTokens(web, group.Owner.LoginName), RequestToJoinLeaveEmailSetting = group.RequestToJoinLeaveEmailSetting }; foreach (var member in group.Users) { siteGroup.Members.Add(new User() { Name = member.LoginName }); } siteSecurity.SiteGroups.Add(siteGroup); } } var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(r => r.Name, r => r.Description, r => r.BasePermissions, r => r.RoleTypeKind)); web.Context.ExecuteQueryRetry(); if (web.HasUniqueRoleAssignments) { var permissionKeys = Enum.GetNames(typeof(PermissionKind)); foreach (var webRoleDefinition in webRoleDefinitions) { if (webRoleDefinition.RoleTypeKind == RoleType.None) { scope.LogDebug("Processing custom role definition {0}", webRoleDefinition.Name); var modelRoleDefinitions = new Model.RoleDefinition(); modelRoleDefinitions.Description = webRoleDefinition.Description; modelRoleDefinitions.Name = webRoleDefinition.Name; var permissions = new List <PermissionKind>(); foreach (var permissionKey in permissionKeys) { var permissionKind = (PermissionKind)Enum.Parse(typeof(PermissionKind), permissionKey); if (webRoleDefinition.BasePermissions.Has(permissionKind)) { modelRoleDefinitions.Permissions.Add(permissionKind); } } siteSecurity.SiteSecurityPermissions.RoleDefinitions.Add(modelRoleDefinitions); } else { scope.LogDebug("Skipping OOTB role definition {0}", webRoleDefinition.Name); } } var webRoleAssignments = web.Context.LoadQuery(web.RoleAssignments.Include( r => r.RoleDefinitionBindings.Include( rd => rd.Name, rd => rd.RoleTypeKind), r => r.Member.LoginName)); web.Context.ExecuteQueryRetry(); foreach (var webRoleAssignment in webRoleAssignments) { if (webRoleAssignment.Member.LoginName != "Excel Services Viewers") { foreach (var roleDefinition in webRoleAssignment.RoleDefinitionBindings) { if (roleDefinition.RoleTypeKind != RoleType.Guest) { var modelRoleAssignment = new Model.RoleAssignment(); modelRoleAssignment.RoleDefinition = roleDefinition.Name; modelRoleAssignment.Principal = ReplaceGroupTokens(web, webRoleAssignment.Member.LoginName); siteSecurity.SiteSecurityPermissions.RoleAssignments.Add(modelRoleAssignment); } } } } template.Security = siteSecurity; } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
/// <summary> /// CSV rows for each member of a group /// </summary> /// <param name="group"></param> private void AddGroupUsersData(SiteGroup group) { var usersInGroup = group.Users; //Nothing to add? if(usersInGroup == null) { return; } string groupId = group.Id; string groupName = group.Name; foreach(var thisUser in usersInGroup) { this.AddKeyValuePairs( new string[] { ContentType //1 ,ContentId //2 ,ContentName //3 ,SiteRole //4 ,ContentUserId //5 ,ContentUserName //6 ,ContentGroupId //7 ,ContentGroupName //8 ,DeveloperNotes //9 }, new string[] { "group-member" //1 ,thisUser.Id //2 ,thisUser.Name //3 ,thisUser.SiteRole //4 ,thisUser.Id //5 ,thisUser.Name //6 ,groupId //7 ,groupName //8 ,thisUser.DeveloperNotes //9 }); } }
/// <summary> /// See if we need to update the Grant License on Sign In behavior of a group /// </summary> /// <param name="siteSignIn"></param> /// <param name="groupProvisionInstructions"></param> /// <param name="thisExistingGroup"></param> private void Execute_ProvisionGroups_SingleGroup_GrantLicenseUpdate( TableauServerSignIn siteSignIn, ProvisioningGroup groupProvisionInstructions, SiteGroup thisExistingGroup) { //If are instruction is to INGORE this attribute, then there is nothing to do if (groupProvisionInstructions.GrantLicenseInstructions == ProvisioningGroup.GrantLicenseMode.Ignore) { return; } //====================================================================================== //Determine if we need to updae the group's Grant License setting //====================================================================================== string newGrantLicensingMode; switch (groupProvisionInstructions.GrantLicenseInstructions) { case ProvisioningGroup.GrantLicenseMode.None: //If the provisioning instructions are for NO Grant Licensing mode, and this is already the case, then there is nothing to do if (string.IsNullOrEmpty(thisExistingGroup.GrantLicenseMode)) { return; } newGrantLicensingMode = ""; //Set the new mode as blank; break; case ProvisioningGroup.GrantLicenseMode.OnLogin: //If the grant license mode and ROLEis already as expected, then there is nothing to do if ((thisExistingGroup.GrantLicenseMode == ProvisioningGroup.GrantLicenseMode_OnLogin) && (thisExistingGroup.SiteMinimumRoleOrNull == groupProvisionInstructions.GrantLicenseRole)) { return; } newGrantLicensingMode = ProvisioningGroup.GrantLicenseMode_OnLogin; //Set the new mode; break; //Degenerate case: Unknown instruction default: IwsDiagnostics.Assert(false, "920-1130: Unknown Grant License instruction for group: " + groupProvisionInstructions.GroupName); throw new Exception("920-1130: Unknown Grant License instruction for group: " + groupProvisionInstructions.GroupName); } //================================================================================ //Perform the update to the site //================================================================================ var sendUpdateGroup = new SendUpdateGroup( siteSignIn, thisExistingGroup.Id, groupProvisionInstructions.GroupName, true, newGrantLicensingMode, groupProvisionInstructions.GrantLicenseRole); var wasSuccessUpdatingGroup = false; string updateGroupErrorText = ""; try { wasSuccessUpdatingGroup = sendUpdateGroup.ExecuteRequest(); } catch (Exception exUpdateGroup) { updateGroupErrorText = exUpdateGroup.Message; } if (!wasSuccessUpdatingGroup) { //Record failure CSVRecord_ErrorUpdatingGroup(groupProvisionInstructions.GroupName, "Error attempting to update group auto grant roles: " + NullSafeText(thisExistingGroup.SiteMinimumRoleOrNull) + "->" + NullSafeText(groupProvisionInstructions.GrantLicenseRole) + ", error details: " + updateGroupErrorText); } else { //Record success CSVRecord_GroupModified( groupProvisionInstructions.GroupName , "Grant license: " + NullSafeText(thisExistingGroup.GrantLicenseMode) + "->" + NullSafeText(newGrantLicensingMode) + ", Site role: " + NullSafeText(thisExistingGroup.SiteMinimumRoleOrNull) + "->" + NullSafeText(groupProvisionInstructions.GrantLicenseRole) , "" ); } }