Example #1
0
        private static List <DetailedUser> GetPermissions(RoleAssignmentCollection roleAssignments, string url)
        {
            List <DetailedUser> users = new List <DetailedUser>();

            foreach (var roleAssignment in roleAssignments)
            {
                if (roleAssignment.Member.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User)
                {
                    var detailedUser = new DetailedUser();
                    detailedUser.Url         = url;
                    detailedUser.User        = roleAssignment.Member as User;
                    detailedUser.Permissions = new List <string>();

                    foreach (var roleDefinition in roleAssignment.RoleDefinitionBindings)
                    {
                        if (roleDefinition.Name == "Limited Access")
                        {
                            continue;
                        }

                        detailedUser.Permissions.Add(roleDefinition.Name);
                    }

                    // if no permissions are recorded (hence, limited access, skip the adding of the permissions)
                    if (detailedUser.Permissions.Count == 0)
                    {
                        continue;
                    }

                    users.Add(detailedUser);
                }
            }
            return(users);
        }
Example #2
0
        private void ProcessRoleAssignments(SecurableObject securableObject, ClientContext clientContext)
        {
            clientContext.Load(securableObject, x => x.HasUniqueRoleAssignments);
            clientContext.ExecuteQuery();

            if (!securableObject.HasUniqueRoleAssignments)
            {
                outPutText += "Same perms as parent" + "<br/>";
            }
            else
            {
                RoleAssignmentCollection roleAssignments = securableObject.RoleAssignments;

                clientContext.Load <RoleAssignmentCollection>(roleAssignments);
                clientContext.ExecuteQuery();

                foreach (RoleAssignment roleAssignment in roleAssignments)
                {
                    Principal member = roleAssignment.Member;
                    RoleDefinitionBindingCollection roleDef = roleAssignment.RoleDefinitionBindings;

                    clientContext.Load(member);
                    clientContext.Load <RoleDefinitionBindingCollection>(roleDef);
                    clientContext.ExecuteQuery();

                    foreach (var binding in roleDef)
                    {
                        outPutText += string.Format("[{0}]{1}: {2}<br/>", member.PrincipalType, member.LoginName, binding.Name);
                    }
                }
            }
        }
        protected RoleAssignment FindRoleRoleAssignment(RoleAssignmentCollection roleAssignments, Group securityGroup)
        {
            TraceService.Verbose((int)LogEventId.CoreCalls, "FindRoleRoleAssignment call");

            if (roleAssignments == null || roleAssignments.ServerObjectIsNull == true)
            {
                TraceService.Verbose((int)LogEventId.CoreCalls,
                                     "roleAssignments arg is null or ServerObjectIsNull. Returning NULL.");

                return(null);
            }

            TraceService.Verbose((int)LogEventId.CoreCalls,
                                 string.Format("roleAssignments.Count: [{0}]", roleAssignments.Count));

            foreach (var ra in roleAssignments)
            {
                TraceService.Verbose((int)LogEventId.CoreCalls, string.Format("Current RoleAssignments:[{0}] Member:[{1}]", ra, ra.Member));

                if (ra.Member.Id == securityGroup.Id)
                {
                    return(ra);
                }
            }

            return(null);
        }
        protected RoleAssignment FindClientRoleRoleAssignment(RoleAssignmentCollection roleAssignments, Group securityGroup)
        {
            foreach (var ra in roleAssignments)
                if (ra.Member.Id == securityGroup.Id)
                    return ra;

            return null;
        }
        private void ExecuteGetFolderPermissionByName()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            serviceObject.Properties.InitResultTable();
            DataTable results = base.ServiceBroker.ServicePackage.ResultTable;

            string listTitle   = serviceObject.GetListTitle();
            string siteURL     = GetSiteURL();
            string folderName  = base.GetStringProperty(Constants.SOProperties.FolderName, true);
            string userOrGroup = base.GetStringProperty(Constants.SOProperties.UserOrGroup, true);
            string permissions = string.Empty;

            using (ClientContext context = InitializeContext(siteURL))
            {
                Web spWeb = context.Web;

                List list = spWeb.Lists.GetByTitle(listTitle);
                context.Load(list);
                context.Load(list, l => l.RootFolder, l => l.DefaultDisplayFormUrl);
                context.ExecuteQuery();

                Folder currentFolder = null;

                try
                {
                    currentFolder = spWeb.GetFolderByServerRelativeUrl(string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, folderName));
                    context.Load(currentFolder);
                    context.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(string.Format(Constants.ErrorMessages.FolderWasNotFound, folderName), ex);
                }

                RoleAssignmentCollection roles = currentFolder.ListItemAllFields.RoleAssignments;
                context.Load(roles, role => role.Include(roleassigned => roleassigned.Member.LoginName, roleassigned => roleassigned.Member));
                context.ExecuteQuery();

                foreach (RoleAssignment role in roles)
                {
                    if (role.Member.LoginName == GetUserOrGroupLogin(context, userOrGroup))
                    {
                        RoleDefinitionBindingCollection roleDefinitions = role.RoleDefinitionBindings;
                        context.Load(roleDefinitions);
                        context.ExecuteQuery();

                        foreach (var roleDefinition in roleDefinitions)
                        {
                            DataRow dataRow = results.NewRow();
                            dataRow[Constants.SOProperties.Permission] = roleDefinition.Name;
                            results.Rows.Add(dataRow);
                        }
                    }
                }
            }
        }
Example #6
0
        /// <summary>
        /// Remove Full Permission.
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="listName">Name of the list</param>
        /// <param name="currentLoggedInUser">Name of logged in User</param>
        internal void RemoveFullControl(ClientContext clientContext, string listName, string currentLoggedInUser, bool isListItem, int matterLandingPageId)
        {
            ListItem listItem = null;
            RoleAssignmentCollection roleCollection = null;
            List list = clientContext.Web.Lists.GetByTitle(listName);

            clientContext.Load(list);
            clientContext.ExecuteQuery();
            if (isListItem)
            {
                // Fetch the list item
                if (0 <= matterLandingPageId)
                {
                    listItem = list.GetItemById(matterLandingPageId);
                    clientContext.Load(listItem, listProperties => listProperties.RoleAssignments.Include(roleAssignmentProperties =>
                                                                                                          roleAssignmentProperties.Member,
                                                                                                          roleAssignmentProperties => roleAssignmentProperties.Member.Title,
                                                                                                          roleAssignmentProperties => roleAssignmentProperties.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.BasePermissions)));
                    clientContext.ExecuteQuery();
                    roleCollection = listItem.RoleAssignments;
                }
            }
            else
            {
                clientContext.Load(list, listProperties => listProperties.RoleAssignments.Include(roleAssignmentProperties =>
                                                                                                  roleAssignmentProperties.Member,
                                                                                                  roleAssignmentProperties => roleAssignmentProperties.Member.Title,
                                                                                                  roleAssignmentProperties => roleAssignmentProperties.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.BasePermissions)));
                clientContext.ExecuteQuery();
                roleCollection = list.RoleAssignments;
            }


            if (null != roleCollection && 0 < roleCollection.Count)
            {
                foreach (RoleAssignment role in roleCollection)
                {
                    if (role.Member.Title == currentLoggedInUser)
                    {
                        IList <RoleDefinition> roleDefinationList = new List <RoleDefinition>();
                        foreach (RoleDefinition roleDef in role.RoleDefinitionBindings)
                        {
                            if (roleDef.Name == "Full Control")
                            {
                                roleDefinationList.Add(roleDef);
                            }
                        }
                        foreach (RoleDefinition roleDef in roleDefinationList)
                        {
                            role.RoleDefinitionBindings.Remove(roleDef);
                        }
                    }
                    role.Update();
                }
            }
            clientContext.ExecuteQuery();
        }
Example #7
0
        public void DCMAddUserRole(int storageObjID, string userAccount, string rolename)
        {
            (storageObjID > 0).FalseThrow <ArgumentException>("ID值{0}无效,请传入大于0的值.", storageObjID);
            using (DocLibContext context = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
            {
                context.Load(context.Web.RoleDefinitions);
                context.ExecuteQuery();
                RoleDefinition selectedRoleDef = null;
                foreach (RoleDefinition role in context.Web.RoleDefinitions)
                {
                    if (role.Name == rolename)
                    {
                        selectedRoleDef = role;
                        break;
                    }
                }
                if (null == selectedRoleDef)
                {
                    return;
                }
                context.Load(selectedRoleDef);
                ListItem listItem = GetListItemById(storageObjID, context);
                if (null == listItem)
                {
                    return;
                }
                context.Load(listItem);
                context.Load(listItem.RoleAssignments);
                context.ExecuteQuery();

                RoleAssignmentCollection roleAssignments = listItem.RoleAssignments;

                bool userFound = false;
                foreach (RoleAssignment roleAssignment in roleAssignments)
                {
                    context.Load(roleAssignment.Member);
                    context.ExecuteQuery();
                    if (roleAssignment.Member.LoginName != userAccount)
                    {
                        continue;
                    }
                    userFound = true;
                    roleAssignment.RoleDefinitionBindings.Add(selectedRoleDef);
                    roleAssignment.Update();
                }
                if (!userFound)
                {
                    RoleDefinitionBindingCollection newBinding = new RoleDefinitionBindingCollection(context);
                    newBinding.Add(selectedRoleDef);
                    User user = context.Web.EnsureUser(userAccount);
                    listItem.RoleAssignments.Add(user, newBinding);
                    listItem.Update();
                }
                context.ExecuteQuery();
            }
        }
Example #8
0
        private static void AddPermissionLevelImplementation(this Web web, Principal principal, RoleType permissionLevel, bool removeExistingPermissionLevels = false)
        {
            if (principal != null)
            {
                bool processed = false;

                RoleAssignmentCollection rac = web.RoleAssignments;
                web.Context.Load(rac);
                web.Context.ExecuteQuery();

                //Find the roles assigned to the principal
                foreach (RoleAssignment ra in rac)
                {
                    // correct role assignment found
                    if (ra.PrincipalId == principal.Id)
                    {
                        // load the role definitions for this role assignment
                        RoleDefinitionBindingCollection rdc = ra.RoleDefinitionBindings;
                        web.Context.Load(rdc);
                        web.Context.Load(web.RoleDefinitions);
                        web.Context.ExecuteQuery();

                        // Load the role definition to add (e.g. contribute)
                        RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel);
                        if (removeExistingPermissionLevels)
                        {
                            // Remove current role definitions by removing all current role definitions
                            rdc.RemoveAll();
                        }
                        // Add the selected role definition
                        rdc.Add(roleDefinition);

                        //update
                        ra.ImportRoleDefinitionBindings(rdc);
                        ra.Update();
                        web.Context.ExecuteQuery();

                        // Leave the for each loop
                        processed = true;
                        break;
                    }
                }

                // For a principal without role definitions set we follow a different code path
                if (!processed)
                {
                    RoleDefinitionBindingCollection rdc = new RoleDefinitionBindingCollection(web.Context);
                    RoleDefinition roleDefinition       = web.RoleDefinitions.GetByType(permissionLevel);
                    rdc.Add(roleDefinition);
                    web.RoleAssignments.Add(principal, rdc);
                    web.Context.ExecuteQuery();
                }
            }
        }
Example #9
0
 public PermissionCollection(RoleAssignmentCollection roleAssCol)
     : this(roleAssCol.Count)
 {
     this.Context = roleAssCol.Context;
     for (int i = 0; i < roleAssCol.Count; i++)
     {
         RoleAssignment ass  = roleAssCol[i];
         Permission     perm = new Permission(ass);
         this.InnerList.Add(perm);
     }
 }
Example #10
0
        protected RoleAssignment FindClientRoleRoleAssignment(RoleAssignmentCollection roleAssignments, Group securityGroup)
        {
            foreach (var ra in roleAssignments)
            {
                if (ra.Member.Id == securityGroup.Id)
                {
                    return(ra);
                }
            }

            return(null);
        }
Example #11
0
        /// <summary>
        /// Get user or group of specified name
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="groupName">Group or user name</param>
        /// <returns>Role Assignment</returns>
        private static RoleAssignment GetGroup(ClientContext clientContext, string groupName)
        {
            RoleAssignmentCollection roles = clientContext.Web.RoleAssignments;

            clientContext.Load(roles, item => item.Include(items => items.Member.Title));
            clientContext.ExecuteQuery();
            RoleAssignment group = roles.Where(role => role.Member.Title == groupName).FirstOrDefault();

            clientContext.Load(group, item => item.Member.Title);
            clientContext.ExecuteQuery();
            return(group);
        }
Example #12
0
        public static PermissionCollection ResolvePermissions(SecurableObject securableObject)
        {
            RoleAssignmentCollection roleAssCol = securableObject.RoleAssignments;

            if (!roleAssCol.AreItemsAvailable)
            {
                roleAssCol.LoadAllAssignments();
            }

            var permCol = new PermissionCollection(roleAssCol);

            permCol.AddSecuringObject(securableObject);
            return(permCol);
        }
Example #13
0
        private static void RemovePermissionLevelImplementation(this Web web, Principal principal, RoleType permissionLevel, bool removeAllPermissionLevels = false)
        {
            if (principal != null)
            {
                RoleAssignmentCollection rac = web.RoleAssignments;
                web.Context.Load(rac);
                web.Context.ExecuteQuery();

                //if no permission level is passed we remove all permission levels
                if (permissionLevel == null)
                {
                    removeAllPermissionLevels = true;
                }

                //Find the roles assigned to the principal
                foreach (RoleAssignment ra in rac)
                {
                    // correct role assignment found
                    if (ra.PrincipalId == principal.Id)
                    {
                        // load the role definitions for this role assignment
                        RoleDefinitionBindingCollection rdc = ra.RoleDefinitionBindings;
                        web.Context.Load(rdc);
                        web.Context.Load(web.RoleDefinitions);
                        web.Context.ExecuteQuery();

                        if (removeAllPermissionLevels)
                        {
                            // Remove current role definitions by removing all current role definitions
                            rdc.RemoveAll();
                        }
                        else
                        {
                            // Load the role definition to remove (e.g. contribute)
                            RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel);
                            rdc.Remove(roleDefinition);
                        }

                        //update
                        ra.ImportRoleDefinitionBindings(rdc);
                        ra.Update();
                        web.Context.ExecuteQuery();

                        // Leave the for each loop
                        break;
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Get the users who have permissions on the list
        /// </summary>
        /// <param name="clientContext">Client Context object</param>
        /// <param name="configurationList">Configuration list</param>
        /// <returns>User list</returns>
        internal static List <string> GetUsers(ClientContext clientContext, List configurationList)
        {
            List <string> userList = new List <string>();

            try
            {
                RoleAssignmentCollection roleAssignments = configurationList.RoleAssignments;
                clientContext.Load(roleAssignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
                clientContext.ExecuteQuery();
                string limitedAccessRole = ConfigurationManager.AppSettings["LimitedAccessRole"];
                RoleAssignment(clientContext, userList, roleAssignments, limitedAccessRole);
            }
            catch (Exception exception)
            {
                ErrorLogger.DisplayErrorMessage(string.Format(CultureInfo.InvariantCulture, Constants.CreateConfigListExceptionMessage, exception.Message));
            }
            return(userList);
        }
        private void ExecuteGetItemPermissionById()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            serviceObject.Properties.InitResultTable();
            DataTable results = base.ServiceBroker.ServicePackage.ResultTable;

            string listTitle   = serviceObject.GetListTitle();
            string siteURL     = GetSiteURL();
            int    id          = base.GetIntProperty(Constants.SOProperties.ID, true);
            string userOrGroup = base.GetStringProperty(Constants.SOProperties.UserOrGroup, true);
            string permissions = string.Empty;

            using (ClientContext context = InitializeContext(siteURL))
            {
                Web spWeb = context.Web;

                List     list     = spWeb.Lists.GetByTitle(listTitle);
                ListItem listItem = list.GetItemById(id);
                context.Load(listItem);
                context.ExecuteQuery();

                RoleAssignmentCollection roles = listItem.RoleAssignments;
                context.Load(roles, role => role.Include(roleassigned => roleassigned.Member.LoginName, roleassigned => roleassigned.Member));
                context.ExecuteQuery();

                foreach (RoleAssignment role in roles)
                {
                    if (role.Member.LoginName == GetUserOrGroupLogin(context, userOrGroup))
                    {
                        RoleDefinitionBindingCollection roleDefinitions = role.RoleDefinitionBindings;
                        context.Load(roleDefinitions);
                        context.ExecuteQuery();

                        foreach (var roleDefinition in roleDefinitions)
                        {
                            DataRow dataRow = results.NewRow();
                            dataRow[Constants.SOProperties.Permission] = roleDefinition.Name;
                            results.Rows.Add(dataRow);
                        }
                    }
                }
            }
        }
Example #16
0
        public BaseCollection <DCTRoleAssignment> DCMGetRoleAssignments(int storageObjID)
        {
            (storageObjID <= 0).TrueThrow <ArgumentException>("ID:{0}无效,请传入大于0的值.", storageObjID);

            using (DocLibContext context = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
            {
                ListItem listItem = GetListItemById(storageObjID, context);
                if (null == listItem)
                {
                    return(new BaseCollection <DCTRoleAssignment>());
                }
                context.Load(listItem);
                context.Load(listItem.RoleAssignments);
                context.ExecuteQuery();

                RoleAssignmentCollection           roleAssignments = listItem.RoleAssignments;
                BaseCollection <DCTRoleAssignment> results         = new BaseCollection <DCTRoleAssignment>();

                foreach (RoleAssignment roleAssignment in roleAssignments)
                {
                    DCTRoleAssignment dctRoleAssignment = new DCTRoleAssignment();
                    context.Load(roleAssignment.Member);
                    context.Load(roleAssignment.RoleDefinitionBindings);
                    context.ExecuteQuery();

                    dctRoleAssignment.Member = GetPrinciple(roleAssignment.Member.PrincipalType);
                    DCTConverterHelper.Convert(roleAssignment.Member, dctRoleAssignment.Member);

                    dctRoleAssignment.RoleDefinitions = new BaseCollection <DCTRoleDefinition>();
                    RoleDefinitionBindingCollection bindingCollection = roleAssignment.RoleDefinitionBindings;
                    foreach (RoleDefinition roleDefinition in bindingCollection)
                    {
                        DCTRoleDefinition dctRoleDefinition = new DCTRoleDefinition();
                        DCTConverterHelper.Convert(roleDefinition, dctRoleDefinition);
                        dctRoleAssignment.RoleDefinitions.Add(dctRoleDefinition);
                    }

                    results.Add(dctRoleAssignment);
                }

                return(results);
            }
        }
Example #17
0
        public static void LoadAllAssignments(this RoleAssignmentCollection roleAssCol)
        {
            roleAssCol.Context.Load(roleAssCol, rac =>
                                    rac.Include(
                                        ra => ra.Member, ra => ra.Member.Id, ra => ra.Member.IsHiddenInUI, ra => ra.Member.LoginName,
                                        ra => ra.Member.PrincipalType, ra => ra.Member.Title, ra => ra.PrincipalId, ra => ra.RoleDefinitionBindings.Include(
                                            rdb => rdb.Description, rdb => rdb.Hidden, rdb => rdb.Id, rdb => rdb.Name, rdb => rdb.Order, rdb => rdb.RoleTypeKind)),
                                    rac => rac.Groups.Include(
                                        g => g.Title, g => g.LoginName, g => g.Id));

            try
            {
                roleAssCol.Context.ExecuteQuery();
            }
            catch (ServerException sex)
            {
                throw new InvalidOperationException(string.Format(
                                                        "An error occurred while loading this RoleAssignment's properties. -- {0}",
                                                        sex.Message));
            }
        }
Example #18
0
        public void DCMRemoveUserRoles(int storageObjID, string userAccount, BaseCollection <string> rolesToRemove)
        {
            (storageObjID > 0).FalseThrow <ArgumentException>("ID值{0}无效,请传入大于0的值.", storageObjID);
            using (DocLibContext context = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
            {
                ListItem listItem = GetListItemById(storageObjID, context);
                if (null == listItem)
                {
                    return;
                }
                context.Load(listItem);
                context.Load(listItem.RoleAssignments);
                context.ExecuteQuery();

                RoleAssignmentCollection roleAssignments = listItem.RoleAssignments;

                foreach (RoleAssignment roleAssignment in roleAssignments)
                {
                    context.Load(roleAssignment.Member);
                    context.Load(roleAssignment.RoleDefinitionBindings);
                    context.ExecuteQuery();
                    if (!IsSameUser(roleAssignment.Member.LoginName, userAccount))
                    {
                        continue;
                    }
                    for (int i = 0; i < roleAssignment.RoleDefinitionBindings.Count; i++)
                    {
                        RoleDefinition roleDefinition = roleAssignment.RoleDefinitionBindings[i];
                        string         rolename       = roleDefinition.Name;
                        if (rolesToRemove.Contains(rolename))
                        {
                            roleAssignment.RoleDefinitionBindings.Remove(roleDefinition);
                            i--;
                        }
                    }
                    roleAssignment.Update();
                }
                context.ExecuteQuery();
            }
        }
 private static bool CheckUserInAdminGroups(ClientContext ctx, Web web, RoleAssignmentCollection roleAssignments, User currentUser)
 {
     if (roleAssignments != null && roleAssignments.Count != 0)
     {
         foreach (RoleAssignment ra in roleAssignments)
         {
             //Load users foreach Group - Group Name: ra.Member.Title
             UserCollection usersCollection = web.SiteGroups.GetByName(ra.Member.Title).Users;
             ctx.Load(usersCollection);
             ctx.ExecuteQuery();
             //Check Permission Groups - rd.Name: Permission Level
             foreach (RoleDefinition rd in ra.RoleDefinitionBindings)
             {
                 if (rd.Name.Equals("Full Control") && (usersCollection.GetByEmail(currentUser.Email) != null))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
Example #20
0
        void WritePermissionsForGroups(ClientContext clientContext, User searchForUserOrGroup, Web web)
        {
            HashSet <string> permissionLevels = new HashSet <string>();

            GroupCollection groups = web.SiteGroups;

            clientContext.Load(groups);
            clientContext.ExecuteQuery();

            foreach (var group in groups)
            {
                clientContext.Load(group, g => g.Users.Where(u => u.LoginName == searchForUserOrGroup.LoginName));
                clientContext.ExecuteQuery();

                foreach (var user in group.Users)
                {
                    RoleAssignmentCollection roleAssignments = web.RoleAssignments;
                    clientContext.Load(web, w => w.RoleAssignments.Where(ra => ra.Member.LoginName == group.LoginName ||
                                                                         ra.Member.LoginName == user.LoginName));
                    clientContext.ExecuteQuery();

                    foreach (var ra in web.RoleAssignments)
                    {
                        clientContext.Load(ra.Member);
                        clientContext.Load(ra.RoleDefinitionBindings);
                        clientContext.ExecuteQuery();
                        foreach (var definition in ra.RoleDefinitionBindings)
                        {
                            clientContext.Load(definition);
                            clientContext.ExecuteQuery();
                            permissionLevels.Add(definition.Name);
                        }
                    }
                }
            }
            AddToPermFile(searchForUserOrGroup, web, web.ServerRelativeUrl, permissionLevels);
        }
Example #21
0
 /// <summary>
 /// Constructor for SiteSecurityPermissions class
 /// </summary>
 public SiteSecurityPermissions()
 {
     this._roleDefinitions = new RoleDefinitionCollection(this.ParentTemplate);
     this._roleAssignments = new RoleAssignmentCollection(this.ParentTemplate);
 }
Example #22
0
 /// <summary>
 /// Static method to assign the role
 /// </summary>
 /// <param name="clientContext">Client context</param>
 /// <param name="userList">User list object</param>
 /// <param name="roleAssignments">Role assignments collection</param>
 /// <param name="limitedAccessRole">Limited to access role</param>
 private static void RoleAssignment(ClientContext clientContext, List <string> userList, RoleAssignmentCollection roleAssignments, string limitedAccessRole)
 {
     foreach (RoleAssignment roleAssignment in roleAssignments)
     {
         RoleDefinitionBindingCollection roleDefinitionsCollection = roleAssignment.RoleDefinitionBindings;
         clientContext.Load(roleDefinitionsCollection, roleDefinition => roleDefinition.Where(definitionItem => definitionItem.Name == limitedAccessRole));
         clientContext.ExecuteQuery();
         if (0 == roleDefinitionsCollection.Count)
         {
             userList.Add(roleAssignment.Member.Title);
         }
     }
 }
Example #23
0
        /// <summary>
        /// Updates permissions on existing lists
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="clientContext">Client context</param>
        private static void UpdateListPermissions(string groupName, ClientContext clientContext)
        {
            try
            {
                string permissionLevelName        = ConfigurationManager.AppSettings["MatterCenterContributePermission"];
                string permissionLevelDescription = ConfigurationManager.AppSettings["MatterCenterContributePermissionDescription"];
                if (CreateNewPermissionLevel(clientContext, permissionLevelName, permissionLevelDescription))
                {
                    ErrorMessage.ShowMessage(ConfigurationManager.AppSettings["UpdateList"], ErrorMessage.MessageType.Notification);
                    string[] lists     = ConfigurationManager.AppSettings["ListTitles"].Split(',');
                    int      listCount = lists.Count();
                    for (int iterator = 0; iterator < listCount; iterator++)
                    {
                        string listName = lists[iterator];
                        List   list     = GetListIfExists(clientContext, listName);

                        // Check if list already exists
                        if (null != list)
                        {
                            if (!list.HasUniqueRoleAssignments)
                            {
                                list.BreakRoleInheritance(true, true);
                                ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["RemovedPermission"], listName), ErrorMessage.MessageType.Notification);
                                clientContext.ExecuteQuery();
                            }

                            // remove group (Matter Center Users) from list
                            RoleAssignmentCollection collection = list.RoleAssignments;
                            clientContext.Load(collection, items => items.Include(item => item.Member.Title).Where(item => item.Member.Title == groupName));
                            clientContext.ExecuteQuery();

                            // Check if group is exists in list, then only remove it
                            if (0 < collection.Count())
                            {
                                collection.FirstOrDefault().DeleteObject();
                                clientContext.ExecuteQuery();
                                ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["RemovedGroup"], groupName, listName), ErrorMessage.MessageType.Notification);
                            }
                            else
                            {
                                ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["GroupFailure"], groupName, listName), ErrorMessage.MessageType.Notification);
                            }

                            // Assign new permission to group(Matter Center Users) & add that group to list

                            // 1. select new permission level
                            RoleDefinition matterCenterContribute = GetPermissionLevel(clientContext, permissionLevelName);

                            // 2. select Group (Matter Center Users)
                            RoleAssignment group = GetGroup(clientContext, groupName);

                            // 3. Check if permission level already added to group, if not then assign new permission level(Matter Center Contribute) to group
                            AssignPermissionLevelToGroup(clientContext, matterCenterContribute, group);

                            // 4. Add group into list
                            AddGroupToList(groupName, clientContext, list, matterCenterContribute);
                            ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["AddGroup"], group.Member.Title, listName), ErrorMessage.MessageType.Notification);

                            // 5. get list item and User who created it and assign full control to that user
                            AssignFullControltoListItem(clientContext, list);
                        }
                        else
                        {
                            ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ListNotFound"], listName), ErrorMessage.MessageType.Error);
                        }
                    }
                }
                else
                {
                    ErrorMessage.ShowMessage(ConfigurationManager.AppSettings["PermissionFailure"], ErrorMessage.MessageType.Error);
                }
            }
            catch (Exception exception)
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, string.Concat(exception.Message, "\n", exception.StackTrace));
            }
        }
 public SiteSecurityPermissions()
 {
     this._roleDefinitions = new RoleDefinitionCollection(this.ParentTemplate);
     this._roleAssignments = new RoleAssignmentCollection(this.ParentTemplate);
 }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "havePermission")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                // Gets data from request body.
                dynamic data = await req.Content.ReadAsAsync <object>();

                string siteUrl = data.SiteUrl;
                //test comment
                string currentEmail = data.CurrentUser_EmailAddress;
                if (String.IsNullOrEmpty(siteUrl) || String.IsNullOrEmpty(currentEmail))
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass parametes site URL and Email Address in request body!"));
                }

                // Fetches client id and client secret from app settings.
                string clientId     = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process);
                string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
                string urlAdminSite = Environment.GetEnvironmentVariable("UrlAdminSite", EnvironmentVariableTarget.Process);

                // Obtains client context using the client id and client secret.
                var ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(urlAdminSite, clientId, clientSecret);

                Tenant                   tenant          = new Tenant(ctx);
                SiteProperties           siteProp        = tenant.GetSitePropertiesByUrl(siteUrl, true);
                Site                     site            = tenant.GetSiteByUrl(siteUrl);
                Web                      web             = site.RootWeb;
                RoleAssignmentCollection roleAssignments = web.RoleAssignments;

                //Get the current user by email address.
                User currentUser = web.EnsureUser(currentEmail);

                ctx.Load(site, s => s.RootWeb, s => s.RootWeb.CurrentUser);
                ctx.Load(siteProp);
                ctx.Load(currentUser);
                ctx.Load(web, w => w.CurrentUser, w => w.SiteGroups, w => w.Url, w => w.Title);
                ctx.Load(roleAssignments, roleAssignement => roleAssignement.Include(r => r.Member, r => r.RoleDefinitionBindings));
                ctx.ExecuteQuery();

                var allowedListDomainFromSite = siteProp.SharingAllowedDomainList.Split(',').Select(x => x.Trim().ToUpper()).ToList();

                if (!siteProp.SharingCapability.ToString().Equals("Disabled"))
                {
                    if (allowedListDomainFromSite.Count() != 0)
                    {
                        if (currentUser.IsSiteAdmin || CheckUserInAdminGroups(ctx, web, roleAssignments, currentUser)) // check if the current user have full control
                        {
                            return(req.CreateResponse(HttpStatusCode.OK, true));
                        }
                    }
                }
                else
                {
                    return(req.CreateResponse(HttpStatusCode.OK, false));
                }

                return(req.CreateResponse(HttpStatusCode.OK, false));
            }
            catch (Exception e)
            {
                return(req.CreateResponse(HttpStatusCode.InternalServerError, e.Message));
            }
        }
Example #26
0
 /// <summary>
 /// Static method to assign the role
 /// </summary>
 /// <param name="clientContext">Client context</param>
 /// <param name="userList">User list object</param>
 /// <param name="roleAssignments">Role assignments collection</param>
 /// <param name="limitedAccessRole">Limited to access role</param>
 private static void RoleAssignment(ClientContext clientContext, List<string> userList, RoleAssignmentCollection roleAssignments, string limitedAccessRole)
 {
     foreach (RoleAssignment roleAssignment in roleAssignments)
     {
         RoleDefinitionBindingCollection roleDefinitionsCollection = roleAssignment.RoleDefinitionBindings;
         clientContext.Load(roleDefinitionsCollection, roleDefinition => roleDefinition.Where(definitionItem => definitionItem.Name == limitedAccessRole));
         clientContext.ExecuteQuery();
         if (0 == roleDefinitionsCollection.Count)
         {
             userList.Add(roleAssignment.Member.Title);
         }
     }
 }
Example #27
0
        private void btnLoadForm_Click(object sender, EventArgs e)
        {
            // ===================== Populate Date Generated ==============================
            Word.ContentControl ccDateGenerated = GetContentControl("txtDateGenerated");
            ccDateGenerated.Range.Text = DateTime.Now.ToString("MM/dd/yyyy");

            String Stage = "Page Load";

            WebCollection childWebs = null;

            String txtURL = String.Empty;

            Word.ContentControl ccURL = GetContentControl("txtURL");

            // Clear errors
            SetContentControl("txtSmartArtError", "");
            SetContentControl("txtURLError", "");

            if (ccURL != null)
            {
                Stage = "Load Action Pane";
                // http://oigportal.hhsoig.gov/sites/OAS/AATS/TMSIS
                txtURL = ccURL.Range.Text;

                txtURL = txtURL.Replace("SitePages/Home.aspx", "");

                txtURL = txtURL.TrimEnd('/');

                actionPane.URL = txtURL;
                actionPane.LoadControl();



                try
                {
                    Stage = "Load Web";
                    ClientContext clientContext = new ClientContext(txtURL);
                    Web           currentWeb    = clientContext.Web;

                    clientContext.Load(currentWeb);
                    clientContext.ExecuteQuery();

                    // Get Web details
                    Guid webId = currentWeb.Id;
                    SetContentControl("txtTitle", currentWeb.Title);
                    SetContentControl("txtCreated", currentWeb.Created.ToString("MM/dd/yyyy"));
                    SetContentControl("txtModified", currentWeb.LastItemModifiedDate.ToString("MM/dd/yyyy"));

                    long webSize = GetWebSize(currentWeb);
                    SetContentControl("txtSize", webSize.ToString("N0"));

                    // Set document properties
                    Microsoft.Office.Core.DocumentProperties properties;
                    properties = (Office.DocumentProperties) this.CustomDocumentProperties;

                    // properties["Title"].Value = currentWeb.Title;

                    #region Smart Art Population
                    // ============ Smart Art =====================================================

                    try
                    {
                        // Set up for diagram
                        Stage = "Modify Smart Art";
                        // for background color of the current web cell in the smartart.
                        const int OrangeCell = unchecked ((int)0xED7D31);

                        Site tempSite = clientContext.Site;
                        clientContext.Load(tempSite);
                        clientContext.ExecuteQuery();

                        string siteUrl = tempSite.Url + "/";                          // http://oigportal.hhsoig.gov/sites/OAS

                        Web tmpRoot = tempSite.RootWeb;
                        clientContext.Load(tmpRoot);
                        clientContext.ExecuteQuery();

                        string rootTitle = tmpRoot.Title;

                        // Get site names by breaking down URL.
                        //  SharePoint 2010 client Web class doesn't have any way to get the parent web.
                        //  example: AATS/TMSIS
                        string   navTree = txtURL.Replace(siteUrl, "");
                        string[] nodes   = navTree.Split('/');

                        // Find the diagram and get a reference to it.
                        Word.InlineShape treeShape = null;

                        foreach (Word.InlineShape tmpShape in this.InlineShapes)
                        {
                            if (tmpShape.Type == Word.WdInlineShapeType.wdInlineShapeSmartArt)
                            {
                                treeShape = tmpShape;
                            }
                        }

                        Office.SmartArt treeArt = treeShape.SmartArt;
                        // treeShape.Height

                        // clear out existing nodes
                        foreach (Office.SmartArtNode tmpNode in treeArt.Nodes)
                        {
                            if (tmpNode != null)
                            {
                                tmpNode.Delete();
                            }
                        }

                        Office.SmartArtNode rootNode = treeArt.Nodes.Add();
                        rootNode.TextFrame2.TextRange.Text = rootTitle;

                        // Nodes from root to current site
                        foreach (string tmpNodeText in nodes)
                        {
                            Office.SmartArtNode tmpChildNode = treeArt.Nodes.Add();
                            tmpChildNode.TextFrame2.TextRange.Text = tmpNodeText;
                        }

                        // Root node - add then node, then set the text.
                        Office.SmartArtNode currentNode = treeArt.Nodes[treeArt.Nodes.Count];
                        currentNode.TextFrame2.TextRange.Text = currentWeb.Title;
                        // set root node color

                        currentNode.Shapes.Fill.ForeColor.RGB = 0xED7D31;                         // OrangeCell;

                        // Child webs for SmartArt
                        childWebs = currentWeb.Webs;
                        clientContext.Load(childWebs);
                        clientContext.ExecuteQuery();

                        foreach (Web tmpWeb in childWebs)
                        {
                            Office.SmartArtNode childNode = currentNode.AddNode(Office.MsoSmartArtNodePosition.msoSmartArtNodeBelow);
                            childNode.TextFrame2.TextRange.Text = tmpWeb.Title;
                        }
                    }
                    catch (Exception ex)
                    {
                        Word.ContentControl smartArtError = GetContentControl("txtSmartArtError");
                        Word.Range          tagRange      = smartArtError.Range;
                        tagRange.Text       = String.Concat("ERROR: ", ex.Message);
                        tagRange.Font.Color = Word.WdColor.wdColorRed;
                    }

                    #endregion

                    #region Build Child Web Table
                    // ============ Child Web Table ===============================================
                    Stage = "Load Child Web Table";

                    Word.Table webTable = GetTable("ChildWebs");

                    if (webTable != null)
                    {
                        foreach (Web tmpWeb in childWebs)
                        {
                            Word.Row newRow = webTable.Rows.Add();

                            newRow.Cells[1].Range.Text = tmpWeb.Title;
                            newRow.Cells[2].Range.Text = tmpWeb.ServerRelativeUrl;
                            // newRow.Cells[3].Range.Text = Owners
                            newRow.Cells[4].Range.Text = tmpWeb.Created.ToString("MM/dd/yyyy");

                            long WebSize = GetWebSize(tmpWeb);
                            newRow.Cells[5].Range.Text = WebSize.ToString("N0");
                        }
                    }
                    #endregion

                    #region Build Child Object Table
                    // ================== Child Object Table =========================================
                    Microsoft.SharePoint.Client.ListCollection webLists = currentWeb.Lists;
                    clientContext.Load(webLists);
                    clientContext.ExecuteQuery();

                    Word.Table objTable = GetTable("tblContentObjects");

                    if (objTable != null)
                    {
                        foreach (List tmpList in webLists)
                        {
                            Word.Row newRow = objTable.Rows.Add();

                            newRow.Cells[1].Range.Text = tmpList.BaseType.ToString();
                            newRow.Cells[2].Range.Text = tmpList.Title;
                            newRow.Cells[3].Range.Text = tmpList.ItemCount.ToString();
                            newRow.Cells[4].Range.Text = tmpList.LastItemModifiedDate.ToString("MM/dd/yyyy");
                        }
                    }
                    #endregion

                    #region Build Permissions Table
                    // =================== Permissions Table ==============================================
                    Stage = "Load Permissions Table";
                    Word.Table permTable = GetTable("tblPermissions");

                    RoleAssignmentCollection roleAssignments = currentWeb.RoleAssignments;
                    clientContext.Load(roleAssignments);
                    clientContext.ExecuteQuery();

                    Stage = "Role Assignments";
                    foreach (RoleAssignment assign in roleAssignments)
                    {
                        clientContext.Load(assign);
                        clientContext.ExecuteQuery();

                        Stage = "Load Role Principal";
                        Principal tmpMember = assign.Member;
                        clientContext.Load(tmpMember);
                        clientContext.ExecuteQuery();

                        Word.Row newRow = permTable.Rows.Add();

                        newRow.Cells[1].Range.Text = assign.Member.Title;
                        newRow.Cells[2].Range.Text = assign.Member.PrincipalType.ToString();
                        newRow.Cells[3].Range.Text = assign.Member.LoginName;

                        Stage = "Role Collection";
                        RoleDefinitionBindingCollection roles = assign.RoleDefinitionBindings;
                        clientContext.Load(roles);
                        clientContext.ExecuteQuery();

                        Stage = "Role Definitions";
                        foreach (RoleDefinition roleDef in roles)
                        {
                            clientContext.Load(roleDef);
                            clientContext.ExecuteQuery();

                            switch (roleDef.Name)
                            {
                            case "Full Control":
                                newRow.Cells[4].Range.Text = "X";
                                break;

                            case "Design":
                                newRow.Cells[5].Range.Text = "X";
                                break;

                            case "Contribute":
                                newRow.Cells[6].Range.Text = "X";
                                break;

                            case "Read":
                                newRow.Cells[7].Range.Text = "X";
                                break;
                            }
                        }
                    }
                    #endregion

                    #region Fill Workflow Table
                    Stage = "Load Workflow Table";

                    Word.Table workflowTable = GetTable("tblWorkflows");

                    WorkflowAssociationCollection workflows = currentWeb.WorkflowAssociations;

                    clientContext.Load(workflows);
                    clientContext.ExecuteQuery();

                    foreach (WorkflowAssociation workflow in workflows)
                    {
                        clientContext.Load(workflow);
                        clientContext.ExecuteQuery();

                        Word.Row newRow = workflowTable.Rows.Add();

                        newRow.Cells[1].Range.Text = workflow.Name;
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    Word.ContentControl urlError = GetContentControl("txtURLError");
                    Word.Range          rngError = urlError.Range;
                    rngError.Text       = String.Concat("ERROR at stage ", Stage, ": ", ex.Message);
                    rngError.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
                }
            }
        }
        /// <summary>
        /// Returns role assignments for the current sharepoint objects
        /// </summary>
        /// <param name="context"></param>
        /// <param name="CurrentWeb"></param>
        /// <param name="Object"></param>
        /// <param name="childSecurableObject"></param>
        private static void GetRoleAssignments(ClientContext context, Web CurrentWeb, object Object, SPSecurableObject childSecurableObject)
        {
            try
            {
                string objectDetails = string.Empty;
                childSecurableObject.RoleAssignments = new List <SPRoleAssignment>();
                RoleAssignmentCollection roleAssignments = null;

                Type spObjectType = Object.GetType();

                switch (spObjectType.Name)
                {
                case "Web":
                    Web web = Object as Web;
                    objectDetails   = web.ServerRelativeUrl;
                    roleAssignments = web.RoleAssignments;
                    break;

                case "List":
                    List list = Object as List;
                    objectDetails   = "List " + list.Title;
                    roleAssignments = list.RoleAssignments;
                    break;

                case "ListItem":
                    ListItem listItem = Object as ListItem;
                    objectDetails   = "List Item ID " + listItem.Id;
                    roleAssignments = listItem.RoleAssignments;
                    break;
                }

                context.Load(roleAssignments);
                context.ExecuteQuery();

                foreach (RoleAssignment roleAssignment in roleAssignments)
                {
                    SPRoleAssignment spRoleAssignment = new SPRoleAssignment();
                    spRoleAssignment.Member          = new SPMember();
                    spRoleAssignment.RoleDefBindings = new SPRoleDefBindings();

                    context.Load(roleAssignment);
                    context.Load(roleAssignment.Member);
                    context.ExecuteQuery();

                    Principal roleMember = roleAssignment.Member;

                    if (roleMember.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup)
                    {
                        spRoleAssignment.PrincipalType = PrincipalType.Group;
                        spRoleAssignment.Member.Group  = new SPGroup();

                        var     query = from g in spSiteGroups.SiteGroups where g.GroupName == roleMember.LoginName select g;
                        SPGroup group = query.First();

                        spRoleAssignment.Member.Group.GroupName = group.GroupName;
                        spRoleAssignment.Member.Group.Users     = new List <SPUser>();

                        foreach (SPUser usr in group.Users)
                        {
                            SPUser spUser = new SPUser
                            {
                                DisplayName = usr.DisplayName,
                                Email       = usr.Email,
                                LoginId     = usr.LoginId
                            };

                            spRoleAssignment.Member.Group.Users.Add(spUser);
                        }
                    }
                    else if (roleMember.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User)
                    {
                        spRoleAssignment.PrincipalType = PrincipalType.User;
                        spRoleAssignment.Member.User   = new SPUser
                        {
                            DisplayName = roleMember.Title,
                            LoginId     = roleMember.LoginName
                        };
                    }

                    context.Load(roleAssignment, r => r.RoleDefinitionBindings);
                    context.ExecuteQuery();

                    spRoleAssignment.RoleDefBindings.Permissions = new List <SPBasePermissions>();

                    foreach (RoleDefinition roleDef in roleAssignment.RoleDefinitionBindings)
                    {
                        if (string.IsNullOrEmpty(spRoleAssignment.RoleDefBindings.RoleName))
                        {
                            spRoleAssignment.RoleDefBindings.RoleName = roleDef.Name;
                        }
                        else
                        {
                            spRoleAssignment.RoleDefBindings.RoleName = spRoleAssignment.RoleDefBindings.RoleName + ", " + roleDef.Name;
                        }

                        //enumerate the enum and check each permission
                        //type to see if the perm is included
                        string[] keys = Enum.GetNames(typeof(PermissionKind));

                        context.Load(roleDef, r => r.BasePermissions);
                        context.ExecuteQuery();

                        //get a reference to the base permissions
                        //in this RoleDefinition
                        BasePermissions bp = roleDef.BasePermissions;

                        //enumerate the enum
                        foreach (string key in keys)
                        {
                            if (bp.Has((PermissionKind)Enum.Parse(typeof(PermissionKind), key)))
                            {
                                SPBasePermissions spBasePermission = new SPBasePermissions {
                                    PermissionName = key
                                };
                                spRoleAssignment.RoleDefBindings.Permissions.Add(spBasePermission);
                            }
                        }
                    }

                    childSecurableObject.RoleAssignments.Add(spRoleAssignment);
                }
            }
            catch (Exception ex)
            {
                RaiseStatusUpdate("ERROR: " + CurrentWeb.ServerRelativeUrl + ". Stack Trace: " + ex.Message, UpdateType.StatusUpdateOnly);
            }
        }
Example #29
0
        /// <summary>
        /// Function to update permissions on send mail list
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="configVal">Configuration values from configuration excel</param>
        internal static void UpdateSendMailListPermissions(ClientContext clientContext, Dictionary <string, string> configVal)
        {
            Dictionary <string, string> groupValues = ExcelOperations.ReadFromExcel(filePath, ConfigurationManager.AppSettings["groupSheetName"]);

            Console.Write("Updating permissions for Send Mail list");

            string listName = ConfigurationManager.AppSettings["listName"];
            Web    web      = clientContext.Web;

            clientContext.Load(web);
            clientContext.ExecuteQuery();

            ListCollection listcoll = web.Lists;

            //Attempt to get the list
            List sendList;
            int  attempts = 0;

            do
            {
                Console.Write(".");
                System.Threading.Thread.Sleep(30000);
                clientContext.Load(listcoll, lists => lists.Include(list => list.Title, list => list.HasUniqueRoleAssignments)); //Refresh the collection
                clientContext.ExecuteQuery();
                sendList  = listcoll.Cast <List>().FirstOrDefault(list => list.Title == listName);
                attempts += 1;
            }while (null == sendList && 20 > attempts);
            Console.WriteLine(string.Empty);

            if (null != sendList)
            {
                //Update list permissions
                if (sendList.HasUniqueRoleAssignments)
                {
                    sendList.ResetRoleInheritance();
                }

                sendList.BreakRoleInheritance(false, true);
                clientContext.Load(sendList);
                clientContext.ExecuteQuery();

                RoleAssignmentCollection roleAssignment = sendList.RoleAssignments;
                List <string>            groupNames     = groupValues.Keys.ToList();
                if (3 <= groupNames.Count)
                {
                    Group          provisionGroup = web.SiteGroups.GetByName(groupNames[2]);
                    RoleDefinition contributeRole = web.RoleDefinitions.GetByName(ConfigurationManager.AppSettings["roleType"]);
                    clientContext.Load(roleAssignment);
                    clientContext.Load(provisionGroup);
                    clientContext.Load(contributeRole);
                    clientContext.ExecuteQuery();

                    RoleDefinitionBindingCollection collRdb = new Microsoft.SharePoint.Client.RoleDefinitionBindingCollection(clientContext);
                    collRdb.Add(contributeRole);
                    roleAssignment.Add(provisionGroup, collRdb);
                    clientContext.ExecuteQuery();
                }
            }
            else
            {
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: SendMail list was not created successfully at " + configVal["CatalogSiteURL"] + "/" + ConfigurationManager.AppSettings["ProvisionMatterAppName"]);
            }
        }
        private void ExecuteRemoveFolderPermissionByName()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            string listTitle   = serviceObject.GetListTitle();
            string siteURL     = GetSiteURL();
            string folderName  = base.GetStringProperty(Constants.SOProperties.FolderName, true);
            string userLogins  = base.GetStringProperty(Constants.SOProperties.UserLogins);
            string groupLogins = base.GetStringProperty(Constants.SOProperties.GroupLogins);

            if (string.IsNullOrEmpty(userLogins) && string.IsNullOrEmpty(groupLogins))
            {
                throw new ApplicationException(Constants.ErrorMessages.UserGroupLoginsAreEmptyException);
            }

            using (ClientContext context = InitializeContext(siteURL))
            {
                Web spWeb = context.Web;

                List list = spWeb.Lists.GetByTitle(listTitle);
                context.Load(list, d => d.RootFolder);
                context.ExecuteQuery();

                Folder currentFolder = null;
                try
                {
                    currentFolder = spWeb.GetFolderByServerRelativeUrl(string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, folderName));
                    context.Load(currentFolder);
                    context.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(string.Format(Constants.ErrorMessages.FolderWasNotFound, folderName), ex);
                }

                RoleAssignmentCollection roles = currentFolder.ListItemAllFields.RoleAssignments;
                context.Load(roles, role => role.Include(roleassigned => roleassigned.Member.LoginName, roleassigned => roleassigned.Member));
                context.ExecuteQuery();

                if (!string.IsNullOrEmpty(userLogins))
                {
                    foreach (User user in GetUsersByLoginString(context, userLogins))
                    {
                        context.Load(user, u => u.LoginName);
                        context.ExecuteQuery();

                        foreach (RoleAssignment role in roles)
                        {
                            if (role.Member.LoginName == user.LoginName)
                            {
                                role.DeleteObject();
                                break;
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(groupLogins))
                {
                    foreach (Group group in GetGroupsByLoginString(context, groupLogins))
                    {
                        context.Load(group, g => g.LoginName);
                        context.ExecuteQuery();

                        foreach (RoleAssignment role in roles)
                        {
                            if (role.Member.LoginName == group.LoginName)
                            {
                                role.DeleteObject();
                                break;
                            }
                        }
                    }
                }

                context.ExecuteQuery();
            }
        }
        protected RoleAssignment FindRoleRoleAssignment(RoleAssignmentCollection roleAssignments, Group securityGroup)
        {
            TraceService.Verbose((int)LogEventId.CoreCalls, "FindRoleRoleAssignment call");

            if (roleAssignments == null || roleAssignments.ServerObjectIsNull == true)
            {
                TraceService.Verbose((int)LogEventId.CoreCalls,
                    "roleAssignments arg is null or ServerObjectIsNull. Returning NULL.");

                return null;
            }

            TraceService.Verbose((int)LogEventId.CoreCalls,
                string.Format("roleAssignments.Count: [{0}]", roleAssignments.Count));

            foreach (var ra in roleAssignments)
            {
                TraceService.Verbose((int)LogEventId.CoreCalls, string.Format("Current RoleAssignments:[{0}] Member:[{1}]", ra, ra.Member));

                if (ra.Member.Id == securityGroup.Id)
                    return ra;
            }

            return null;
        }
Example #32
0
        /// <summary>
        /// Function to update permissions on send mail list
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="configVal">Configuration values from configuration excel</param>
        internal static void CreateUpdateProvisionMatterListPermissions(ClientContext clientContext, Dictionary <string, string> configVal)
        {
            Dictionary <string, string> groupValues = ExcelOperations.ReadFromExcel(filePath, ConfigurationManager.AppSettings["groupSheetName"]);

            Console.Write("Creating Provision Matter List...");
            List provisionMatterList;
            //This is a dummy list that is getting created to check whether the current login user can create matter or not
            //Otherwise this list has no significance
            string listName = ConfigurationManager.AppSettings["listName"];
            Web    web      = clientContext.Web;

            ListCollection listcoll = web.Lists;

            clientContext.Load(listcoll, lists => lists.Include(list => list.Title)); //Refresh the collection
            clientContext.ExecuteQuery();
            provisionMatterList = listcoll.Cast <List>().FirstOrDefault(list => list.Title == listName);

            if (null == provisionMatterList)
            {
                ListCreationInformation listCreationInfo = new ListCreationInformation();
                listCreationInfo.Title        = listName;
                listCreationInfo.TemplateType = (int)ListTemplateType.Announcements;
                provisionMatterList           = web.Lists.Add(listCreationInfo);
                clientContext.Load(provisionMatterList);
                clientContext.ExecuteQuery();
            }

            clientContext.Load(listcoll, lists => lists.Include(list => list.Title, list => list.HasUniqueRoleAssignments)); //Refresh the collection
            clientContext.ExecuteQuery();
            provisionMatterList = listcoll.Cast <List>().FirstOrDefault(list => list.Title == listName);



            //Update list permissions
            if (provisionMatterList.HasUniqueRoleAssignments)
            {
                provisionMatterList.ResetRoleInheritance();
            }

            provisionMatterList.BreakRoleInheritance(false, true);
            clientContext.Load(provisionMatterList);
            clientContext.ExecuteQuery();

            RoleAssignmentCollection roleAssignment = provisionMatterList.RoleAssignments;
            List <string>            groupNames     = groupValues.Keys.ToList();

            if (3 <= groupNames.Count)
            {
                Group          provisionGroup = web.SiteGroups.GetByName(groupNames[2]);
                RoleDefinition contributeRole = web.RoleDefinitions.GetByName(ConfigurationManager.AppSettings["roleType"]);
                clientContext.Load(roleAssignment);
                clientContext.Load(provisionGroup);
                clientContext.Load(contributeRole);
                clientContext.ExecuteQuery();

                RoleDefinitionBindingCollection collRdb = new Microsoft.SharePoint.Client.RoleDefinitionBindingCollection(clientContext);
                collRdb.Add(contributeRole);
                roleAssignment.Add(provisionGroup, collRdb);
                clientContext.ExecuteQuery();
            }
        }
        private void ExecuteRemoveItemPermissionById()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            string listTitle   = serviceObject.GetListTitle();
            string siteURL     = GetSiteURL();
            int    id          = base.GetIntProperty(Constants.SOProperties.ID, true);
            string userLogins  = base.GetStringProperty(Constants.SOProperties.UserLogins);
            string groupLogins = base.GetStringProperty(Constants.SOProperties.GroupLogins);

            if (string.IsNullOrEmpty(userLogins) && string.IsNullOrEmpty(groupLogins))
            {
                throw new ApplicationException(Constants.ErrorMessages.UserGroupLoginsAreEmptyException);
            }

            using (ClientContext context = InitializeContext(siteURL))
            {
                Web spWeb = context.Web;

                List     list     = spWeb.Lists.GetByTitle(listTitle);
                ListItem listItem = list.GetItemById(id);
                context.Load(listItem);
                context.ExecuteQuery();

                RoleAssignmentCollection roles = listItem.RoleAssignments;
                context.Load(roles, role => role.Include(roleassigned => roleassigned.Member.LoginName, roleassigned => roleassigned.Member));
                context.ExecuteQuery();

                if (!string.IsNullOrEmpty(userLogins))
                {
                    foreach (User user in GetUsersByLoginString(context, userLogins))
                    {
                        context.Load(user, u => u.LoginName);
                        context.ExecuteQuery();

                        foreach (RoleAssignment role in roles)
                        {
                            if (role.Member.LoginName == user.LoginName)
                            {
                                role.DeleteObject();
                                break;
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(groupLogins))
                {
                    foreach (Group group in GetGroupsByLoginString(context, groupLogins))
                    {
                        context.Load(group, g => g.LoginName);
                        context.ExecuteQuery();

                        foreach (RoleAssignment role in roles)
                        {
                            if (role.Member.LoginName == group.LoginName)
                            {
                                role.DeleteObject();
                                break;
                            }
                        }
                    }
                }

                context.ExecuteQuery();
            }
        }
        /// <summary>
        /// Removes the users' permission from list or list item.
        /// </summary>
        /// <param name="clientContext">ClientContext object</param>
        /// <param name="usersToRemove">List of users</param>
        /// <param name="isListItem">ListItem or list</param>
        /// <param name="list">List object</param>
        /// <param name="matterLandingPageId">List item id</param>
        private static void RemoveSpecificUsers(ClientContext clientContext, List <string> usersToRemove, string loggedInUserTitle, bool isListItem, string listName, int matterLandingPageId)
        {
            try
            {
                ListItem listItem = null;
                RoleAssignmentCollection        roleCollection = null;
                Microsoft.SharePoint.Client.Web web            = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);
                clientContext.Load(list);
                clientContext.ExecuteQuery();
                if (0 < usersToRemove.Count)
                {
                    if (isListItem)
                    {
                        // Fetch the list item
                        if (0 <= matterLandingPageId)
                        {
                            listItem = list.GetItemById(matterLandingPageId);
                            clientContext.Load(listItem, listItemProperties => listItemProperties.RoleAssignments.Include(roleAssignmentProperties => roleAssignmentProperties.Member, roleAssignmentProperties => roleAssignmentProperties.Member.Title, roleAssignmentProperties => roleAssignmentProperties.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.BasePermissions)));
                            clientContext.ExecuteQuery();
                            roleCollection = listItem.RoleAssignments;
                        }
                    }
                    else
                    {
                        clientContext.Load(list, listProperties => listProperties.RoleAssignments.Include(roleAssignmentProperties => roleAssignmentProperties.Member, roleAssignmentProperties => roleAssignmentProperties.Member.Title, roleAssignmentProperties => roleAssignmentProperties.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.BasePermissions)));
                        clientContext.ExecuteQuery();
                        roleCollection = list.RoleAssignments;
                    }

                    if (null != roleCollection && 0 < roleCollection.Count && 0 < usersToRemove.Count)
                    {
                        foreach (string user in usersToRemove)
                        {
                            foreach (RoleAssignment role in roleCollection)
                            {
                                List <RoleDefinition> roleDefinationList = new List <RoleDefinition>();
                                foreach (RoleDefinition roleDef in role.RoleDefinitionBindings)
                                {
                                    // Removing permission for all the user except current user with full control
                                    // Add those users in list, then traverse the list and removing all users from that list
                                    if (role.Member.Title == user && !((role.Member.Title == loggedInUserTitle) && (roleDef.Name == ConstantStrings.EditMatterAllowedPermissionLevel)))
                                    {
                                        roleDefinationList.Add(roleDef);
                                    }
                                }
                                foreach (RoleDefinition roleDef in roleDefinationList)
                                {
                                    role.RoleDefinitionBindings.Remove(roleDef);
                                }
                                role.Update();
                            }
                        }
                    }
                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }