internal static void VerifyPermissions(string userName, List <string> permutations) { #if DEV string url = "https://connect2dev.beamsuntory.com"; #endif #if PROD string url = "https://connect.beamsuntory.com"; #endif try { #if DEV string userClaim = "i:0e.t|acs dev|" + userName; #endif #if PROD string userClaim = "i:0e.t|beam suntory acs|" + userName; #endif using (SPSite s = new SPSite(url)) { using (SPWeb w = s.RootWeb) { w.AllowUnsafeUpdates = true; List <string> missingGroups; List <SPGroup> groups = PermutationGroups(permutations, w, out missingGroups); SPUser cUser = w.EnsureUser(userClaim); SPGroupCollection gUser = cUser.Groups; foreach (SPGroup g in groups) { bool isAlreadyMember = false; foreach (SPGroup gu in gUser) { if (gu.Name == g.Name) { isAlreadyMember = true; break; } } if (!isAlreadyMember) { g.AddUser(cUser); #if DEBUG Console.WriteLine("Adding user to group:" + g.Name); #endif } #if DEBUG Console.WriteLine("Already a member of group: " + g.Name); #endif } w.AllowUnsafeUpdates = false; } } } catch (Exception ex) { Console.WriteLine("Error Verifying Permissions:" + ex.Message + "\n" + ex.StackTrace); } }
internal static SPGroup AddSecurityGroup(SPGroupCollection groups, string name, string description, SPUser owner, bool addOwnerToGroup) { SPGroup item = null; try { item = groups[name]; if (addOwnerToGroup) { item.AddUser(owner); } } catch (SPException ex) { if (-2146232832 == ex.ErrorCode) { SPMember associatedOwnerGroup = owner; if (groups.Web.AssociatedOwnerGroup != null) { associatedOwnerGroup = groups.Web.AssociatedOwnerGroup; } if (addOwnerToGroup) { groups.Add(name, associatedOwnerGroup, owner, description); } else { groups.Add(name, associatedOwnerGroup, null, description); } item = groups[name]; } else { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); } } IList <SPGroup> associatedGroups = item.ParentWeb.AssociatedGroups; if ((item != null) && (associatedGroups != null)) { bool flag = true; foreach (SPGroup group2 in associatedGroups) { if (group2.ID == item.ID) { flag = false; break; } } if (flag) { associatedGroups.Add(item); } } return(item); }
private void AssignSsrsRole(SPGroupCollection groups, SPList userList, Role role, string spRole) { string errors = string.Empty; var reportViewers = groups.GetByName(spRole); try { foreach (SPUser user in reportViewers.Users) { try { var extendedList = userList.Items.GetItemById(user.ID); if ((extendedList["Synchronized"] == null || Convert.ToBoolean(extendedList["Synchronized"]) == false) && user.Name != "System Account") { string loginName = user.LoginName; bool inheritParent; var policies = client.GetPolicies($"/{siteCollectionId.ToString()}", out inheritParent).ToList(); loginName = SPClaimProviderManager.Local.DecodeClaim(loginName).Value; var existingRole = policies.SingleOrDefault(x => x.GroupUserName.ToLower() == loginName.ToLower()); if (existingRole == null) { policies.Add(new Policy { GroupUserName = loginName.Split('\\').Last(), Roles = new Role[] { role } }); } else { var roleList = existingRole.Roles.ToList(); roleList.Clear(); roleList.Add(role); existingRole.Roles = roleList.ToArray(); } client.SetPolicies($"/{siteCollectionId.ToString()}", policies.ToArray()); extendedList["Synchronized"] = true; extendedList.SystemUpdate(); } } catch (Exception exception) { errors += exception.ToString(); } } } catch (Exception exception) { errors += exception.ToString(); } if (!string.IsNullOrEmpty(errors)) { throw new Exception(errors); } }
public SPGroupCollectionInstance(ObjectInstance prototype, SPGroupCollection groupCollection) : this(prototype) { if (groupCollection == null) { throw new ArgumentNullException("groupCollection"); } m_groupCollection = groupCollection; }
static void AddGroup(SPWeb web, string groupPartialName, string description) { string name = web.ParentWeb.Title + " " + web.Title + groupPartialName; //Only create the group if it doesn't already exist. SPGroupCollection existing = web.SiteGroups.GetCollection(new string[] { name }); if (existing.Count == 0) { web.SiteGroups.Add(name, web.Site.Owner, null, description + web.Title); } }
public static SPGroup GetByName(this SPGroupCollection groups, string groupName) { try { return(groups[groupName]); } catch { return(null); } }
public static bool IsGroupBy(string groupName) { SPGroupCollection groups = SPWeb.CurrentUser.Groups; foreach (SPGroup group in groups) { if (group.Name == groupName) { return(true); } } return(false); }
protected bool ContainsGroup(SPGroupCollection groupCollection, string index) { try { SPGroup testGroup = groupCollection[index]; return(true); } catch (SPException e) { e.Message.ToString(); ULSLogger.LogErrorInULS("Inside catch in ContainsGroup() in PWC Secure Folder Feature----" + e.Message); return(false); } }
public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { var web = (properties.Feature.Parent as SPSite).RootWeb; string groupName = "WOFHonorGroup"; try { SPGroupCollection collGroups = web.SiteGroups; collGroups.Remove(groupName); } catch { //Лог } }
private bool UserIsMemberOf(SPItemEventProperties properties, string groupName) { SPUser user = properties.Web.CurrentUser; SPGroupCollection groupCollection = user.Groups; foreach (string group in groupCollection) { if (group == groupName) { return(true); } } return(false); }
public static void SetPermGroup(string spsURL, string libName, string fPath, string grpName, string lvlAccess) { // lvlAccess - Full Control; Design; Contribute; Read; View Only; Limited Access; using (SPSite site = new SPSite(spsURL)) { using (SPWeb web = site.OpenWeb()) { SPFolder eXfolder = web.GetFolder(spsURL + "/" + libName + "/" + fPath); SPGroupCollection spc = web.SiteGroups; SPGroup group = spc[grpName]; SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group); eXfolder.Item.BreakRoleInheritance(true); roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[lvlAccess]); eXfolder.Item.RoleAssignments.Add(roleAssignment); } } }
public static bool CheckForEditing(string SPUrl, string SPListURLDir, SPUser currentUser) { var canEdit = false; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPUrl)) { using (SPWeb web = site.OpenWeb()) { SPList docLibrary = web.GetList(SPListURLDir); try { SPRoleAssignment userRoles = docLibrary.RoleAssignments.GetAssignmentByPrincipal(currentUser); canEdit = CheckRolesForEditing(userRoles); } catch (Exception ex) { Log.LogError(ex.Message); SPGroupCollection groupColl = web.Groups; if (groupColl.Count == 0) { try { SPRoleAssignment currentUserRole = web.RoleAssignments.GetAssignmentByPrincipal(currentUser); canEdit = CheckRolesForEditing(currentUserRole); } catch (Exception e) { Log.LogError(e.Message); } } foreach (SPGroup group in groupColl) { try { SPRoleAssignment groupsRoles = docLibrary.RoleAssignments.GetAssignmentByPrincipal(group); canEdit = CheckRolesForEditing(groupsRoles); if (canEdit) { break; } } catch (Exception exception) { Log.LogError(exception.Message); } } } } } }); return(canEdit); }
public static bool GroupExists(SPGroupCollection groups, string name) { if (string.IsNullOrEmpty(name) || (name.Length > 255) || (groups == null) || (groups.Count == 0)) return false; else return (groups.GetCollection(new String[] { name }).Count > 0); }
public void DeleteGroup(string groupName) { try { using (SPWeb website = GetWebSite()) { SPGroupCollection sharepointGroups = website.SiteGroups; sharepointGroups.Remove(groupName); website.Update(); } } catch (Exception ex) { var log = new AppEventLog(AppException.ExceptionMessage(ex, "aGroupName", "ClsHelper")); log.WriteToLog(); } }
// Uncomment the method below to handle the event raised before a feature is deactivated. public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { SPSite currentSite = properties.Feature.Parent as SPSite; SPWeb rootWeb = currentSite.RootWeb; SPUser currentUser = rootWeb.CurrentUser; SPGroupCollection groups = rootWeb.SiteGroups; groups.Remove("Trainers"); groups.Remove("Training Administrators"); groups.Remove("Students"); SPList registrationsList = rootWeb.Lists["Registrations"]; registrationsList.ResetRoleInheritance(); }
/// <summary> /// Creates a group, if the group does not already exist. Sets the following properties: /// AllowRequestToJoinLeave = true /// OnlyAllowMembersViewMembership = true /// AllowMembersEditMembership = false /// </summary> /// <param name="web">The web where the group will be created</param> /// <param name="groupName">The name of the group</param> /// <param name="groupDescription">The group description</param> /// <param name="owner">The group's owner</param> public static SPGroup CreateGroup(this SPWeb web, string groupName, string groupDescription, SPMember owner) { SPGroup group; if (web.TryGetGroup(groupName, out group) == false) { SPGroupCollection gc = web.SiteGroups; gc.Add(groupName, owner, web.Site.Owner, groupDescription); group = gc[groupName]; group.AllowRequestToJoinLeave = false; group.OnlyAllowMembersViewMembership = true; group.AllowMembersEditMembership = false; group.Update(); } return(group); }
public override List <string> GetDirectoryAdmin(int parentBrand, int brand, int agency, string country) { List <string> grpNames = new List <string>(); List <string> adminEmails = new List <string>(); grpNames.Add(Utility.GenerateContentMgrGroupName(parentBrand, brand, agency)); if (!string.IsNullOrEmpty(country)) { grpNames.AddRange(Utility.GeneratePossibleContentMgrGroupName(parentBrand, brand, country)); } if (grpNames.Count <= 0) { return(adminEmails); } SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(this._spweb.Url)) { using (SPWeb elevatedWeb = site.OpenWeb()) { SPGroupCollection grpsFound = elevatedWeb.SiteGroups.GetCollection(grpNames.ToArray()); if (grpsFound.Count > 0) { foreach (SPGroup grp in grpsFound) { if (grp.Users.Count > 0) { foreach (SPUser s in grp.Users) { adminEmails.Add(s.Email); } } } } } } }); return(adminEmails); }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite currentSite = properties.Feature.Parent as SPSite; SPWeb rootWeb = currentSite.RootWeb; SPUser currentUser = rootWeb.CurrentUser; SPGroupCollection groups = rootWeb.SiteGroups; groups.Add("Training Administrators", currentUser, currentUser, "All Globomantics Training Administrators are in this group"); SPGroup trainingAdmins = groups["Training Administrators"]; groups.Add("Trainers", trainingAdmins, currentUser, "All Globomantics Trainers are in this group"); groups.Add("Students", trainingAdmins, currentUser, "All Globomantics students are in this group"); SPRoleDefinition fullControl = rootWeb.RoleDefinitions["Full Control"]; SPRoleDefinition contribute = rootWeb.RoleDefinitions["Contribute"]; SPRoleDefinition read = rootWeb.RoleDefinitions["Read"]; SPRoleAssignment trainersRoleAssignment = new SPRoleAssignment(groups["Trainers"]); trainersRoleAssignment.RoleDefinitionBindings.Add(contribute); rootWeb.RoleAssignments.Add(trainersRoleAssignment); SPRoleAssignment studentsRoleAssignment = new SPRoleAssignment(groups["Students"]); studentsRoleAssignment.RoleDefinitionBindings.Add(read); rootWeb.RoleAssignments.Add(studentsRoleAssignment); SPList registrationsList = rootWeb.Lists["Registrations"]; registrationsList.BreakRoleInheritance(true); SPRoleAssignment registrationsRoleAssignment = new SPRoleAssignment(groups["Students"]); registrationsRoleAssignment.RoleDefinitionBindings.Add(contribute); registrationsList.RoleAssignments.Add(registrationsRoleAssignment); SPRoleAssignment trainingAdminsRoleAssignment = new SPRoleAssignment(trainingAdmins); trainingAdminsRoleAssignment.RoleDefinitionBindings.Add(fullControl); rootWeb.RoleAssignments.Add(trainingAdminsRoleAssignment); }
public UserGroupsInfo GetGroupsFromCurrentUser() { UserGroupsInfo response = new UserGroupsInfo(); response.UserGroups = new List <string>(); using (SPWeb currentWeb = SPContext.Current.Web) { response.UserLogIn = currentWeb.CurrentUser.LoginName; SPGroupCollection groups = currentWeb.CurrentUser.Groups; foreach (SPGroup group in groups) { response.UserGroups.Add(group.Name); } } return(response); }
/// <summary> /// Add group to SPWeb and set permission for this group /// </summary> /// <param name="web"></param> /// <param name="groupName"></param> /// <param name="groupDescription"></param> /// <param name="role"></param> /// <param name="member"></param> public static void CreateNewGroup(this SPWeb web, string groupName, string groupDescription, SPRoleType role) { if (string.IsNullOrEmpty(groupName)) { return; } try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite spSite = new SPSite(web.Site.ID)) { using (SPWeb spWeb = spSite.OpenWeb(web.ID)) { SPUserCollection users = spWeb.AllUsers; SPUser owner = users[spWeb.Author.LoginName]; SPMember member = users[spWeb.Author.LoginName]; //Add the group to the SPWeb web SPGroupCollection groups = spWeb.SiteGroups; var isExits = groups.Cast <SPGroup>().FirstOrDefault(p => p.Name == groupName); if (isExits == null) { groups.Add(groupName, member, owner, groupDescription); } //Associate the group with SPWeb //spWeb.AssociatedGroups.Add(spWeb.SiteGroups[groupName]); spWeb.Update(); //Assignment of the roles to the group. SPRoleAssignment assignment = new SPRoleAssignment(spWeb.SiteGroups[groupName]); SPRoleDefinition _role = spWeb.RoleDefinitions.GetByType(role); assignment.RoleDefinitionBindings.Add(_role); spWeb.RoleAssignments.Add(assignment); } } }); } catch { // Not catch exception because check group exists } }
public void AddGroup(string groupName, string owner, string defaultUser, string description, UserObject.RoleDefinition role) { if (string.IsNullOrEmpty(groupName)) { return; } if (string.IsNullOrEmpty(owner)) { return; } if (string.IsNullOrEmpty(defaultUser)) { return; } try { using (SPWeb website = GetWebSite()) { SPUser sharepointOwner = GetUserObject(owner); if (sharepointOwner == null) { return; } SPUser sharepointDefaultUser = GetUserObject(defaultUser); if (sharepointDefaultUser == null) { return; } SPGroupCollection sharepointGroups = website.SiteGroups; sharepointGroups.Add(groupName, sharepointOwner, sharepointDefaultUser, description); AssignPermission(role, groupName, string.Empty); website.Update(); } } catch (Exception ex) { var log = new AppEventLog(AppException.ExceptionMessage(ex, "AddGroup", "ClsHelper")); log.WriteToLog(); } }
public static bool GroupExists(SPGroupCollection groups, string name) { if (string.IsNullOrEmpty(name) || (name.Length > 255) || (groups == null) || (groups.Count == 0)) { return(false); } else { foreach (SPGroup group in groups) { if (group.Name == name) { return(true); } } } return(false); }
private static bool WhereUser(string condition, string group) { SPUser user = SPContext.Current.Web.CurrentUser; SPGroupCollection userGroups = user.Groups; bool userInGroup = false; foreach (SPGroup groupItem in userGroups) { if (groupItem.Name.Equals(group)) { userInGroup = true; continue; } } if (condition.Equals("IsInGroup")) { return(userInGroup); } return(!userInGroup); }
public static void CreateNewGroup(this SPWeb web, string groupName, string groupDescription) { if (string.IsNullOrEmpty(groupName)) { return; } try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPUserCollection users = web.AllUsers; SPUser owner = users[web.Author.LoginName]; SPMember member = users[web.Author.LoginName]; try { //Add the group to the SPWeb web SPGroupCollection groups = web.SiteGroups; groups.Add(groupName, member, owner, groupDescription); //Associate the group with SPWeb web.AssociatedGroups.Add(web.SiteGroups[groupName]); web.Update(); } catch { } //Assignment of the roles to the group. SPRoleAssignment assignment = new SPRoleAssignment(web.SiteGroups[groupName]); SPRoleDefinition _role = web.RoleDefinitions.GetByType(SPRoleType.Contributor); assignment.RoleDefinitionBindings.Add(_role); web.RoleAssignments.Add(assignment); }); } catch { // Not catch exception because check group exists } }
private void DeleteGroup(SPWeb web, string groupNames) { try { foreach (string groupName in groupNames.Split(';')) { if (IsExistGroup(web, groupName)) { web.AllowUnsafeUpdates = true; SPGroupCollection groupCol = web.SiteGroups; SPGroup group = web.SiteGroups.GetByName(groupNames); groupCol.Remove(group.Name); web.AllowUnsafeUpdates = false; } } } catch (Exception) { } }
private void LoadUserSiteGroups() { XPathNavigator form = this.MainDataSource.CreateNavigator(); string siteUrl = form.SelectSingleNode("/my:EmployeeForm/my:siteUrl", NamespaceManager).Value; using (SPSite site = new SPSite(siteUrl)) { using (SPWeb web = site.RootWeb) { string userID = form.SelectSingleNode("/my:EmployeeForm/my:txtUserID", NamespaceManager).Value; SPUser user = web.EnsureUser(userID); SPGroupCollection userGroups = user.Groups; if (userGroups.Count > 0) { XPathNavigator siteGroups = form.SelectSingleNode("//my:SiteGroups", NamespaceManager); XPathNavigator siteGroup = form.SelectSingleNode("//my:SiteGroups/my:SiteGroup", NamespaceManager); string prevSiteGroups = ""; foreach (SPGroup group in userGroups) { XPathNavigator newSiteGroup = siteGroup.Clone(); newSiteGroup.SetValue(group.ID.ToString()); siteGroups.AppendChild(newSiteGroup); if (prevSiteGroups.Length > 0) { prevSiteGroups += ","; } prevSiteGroups += group.Name; } form.SelectSingleNode("/my:EmployeeForm/my:prevSiteGroups", NamespaceManager).SetValue(prevSiteGroups); } // if (userGroups.Count > 0) } // using (SPWeb web } // using (SPSite site } // private void LoadUserSiteGroups()
protected void CreateSFGroup(SPWeb web, string grpName, string permName, string member_visitor) { web.AllowUnsafeUpdates = true; SPMember bronzeAdminMember = null; try { ULSLogger.LogErrorInULS("Inside try in createGroup() in PWC Secure Folder Feature"); if (ContainsPermLevel(web, permName)) { SPGroupCollection sgc = web.SiteGroups; string adminGrpName = string.Empty; foreach (SPGroup grp in sgc) { adminGrpName = grp.Name; if (adminGrpName.EndsWith("Bronze Admin")) { ULSLogger.LogErrorInULS("Inside foreach if in createGroup() in PWC Secure Folder Feature.. Found Bronze Admin group---name is---" + adminGrpName); bronzeAdminMember = grp; } } if (member_visitor.Equals("member")) { web.SiteGroups.Add(grpName, bronzeAdminMember, null, "Members for the folder " + grpName); } if (member_visitor.Equals("visitor")) { web.SiteGroups.Add(grpName, bronzeAdminMember, null, "Visitors for the folder " + grpName); } } } catch (Exception e) { e.Message.ToString(); ULSLogger.LogErrorInULS("Inside catch in createGroup() in PWC Secure Folder Feature---" + e.Message); } }
private bool UserCanSeeView(string viewId, Dictionary <int, Dictionary <string, bool> > roleProperties) { SPUser user = SPContext.Current.Web.CurrentUser; SPGroupCollection userGroups = user.Groups; if (userGroups.Count > 0) { foreach (SPGroup group in userGroups) { if (roleProperties.ContainsKey(group.ID)) { if ((roleProperties[group.ID].ContainsKey(viewId)) && (roleProperties[group.ID][viewId] == true)) { return(true); } } } return(false); } else { return(true); } }
private static bool ContainsGroup(SPGroupCollection groupCollection, string groupName) { try { var group = groupCollection[groupName]; return true; } catch (SPException) { return false; } }