Exemplo n.º 1
0
        public static void SetReadOnly(SPListItem item)
        {
            SPWeb web = item.Web;
            bool  allowUnsafeUpdates = web.AllowUnsafeUpdates;

            web.AllowUnsafeUpdates = true;
            if (!item.HasUniqueRoleAssignments)
            {
                item.BreakRoleInheritance(true);
            }
            web.AllowUnsafeUpdates = true;
            SPRoleAssignmentCollection roleAssignments = item.RoleAssignments;
            int iD   = web.Site.SystemAccount.ID;
            int num2 = (web.AssociatedOwnerGroup != null) ? web.AssociatedOwnerGroup.ID : -1;

            for (int i = roleAssignments.Count - 1; i > -1; i--)
            {
                SPRoleAssignment assignment = roleAssignments[i];
                int num4 = assignment.Member.ID;
                if ((num4 != iD) && (num4 != num2))
                {
                    SPRoleDefinitionBindingCollection roleDefinitionBindings = assignment.RoleDefinitionBindings;
                    if ((roleDefinitionBindings.Count != 1) || (roleDefinitionBindings[0].Type != SPRoleType.Reader))
                    {
                        roleDefinitionBindings.RemoveAll();
                        SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                        roleDefinitionBindings.Add(byType);
                        assignment.Update();
                    }
                }
            }
            web.AllowUnsafeUpdates = allowUnsafeUpdates;
        }
Exemplo n.º 2
0
        }//SetListPermissions()

        static void BreakInheritanceAndDeletePermissions(SPWeb web, SPList ccpList, SPList library, SPListItem eventLogItem)
        {
            try
            {
                //Ensure library permissions are broken
                library.BreakRoleInheritance(true);

                //Delete list permissions
                SPRoleAssignmentCollection roleAssignments = library.RoleAssignments;
                for (int i = roleAssignments.Count - 1; i >= 0; i--)
                {
                    library.RoleAssignments.Remove(0);
                }
            }
            catch (Exception e)
            {
                //Log
                if (library.Title == "Contracts")
                {
                    eventLogItem["Contracts"] = e.Message + " at " + web.Title + " : " + web.Url;
                    eventLogItem.Update();
                }
                else if (library.Title == "Proposals")
                {
                    eventLogItem["Proposals"] = e.Message + " at " + web.Title + " : " + web.Url;
                    eventLogItem.Update();
                }
            }
        }//BreakInheritanceAndDeletePermissions()
Exemplo n.º 3
0
        /// <summary>
        /// This method should be used instead of BreakRoleInheritance(true).
        ///
        /// The OOTB method replicates all permissions from the parent, including the "Limited Access" permissions.
        /// In environments with many users, there can be many of these meaningless permissions, which bloats the
        /// SharePoint permission tables in SQL. This method reviews all RoleDefinitions in each principal's
        /// RoleAssignments, stripping "Limited Access", before adding them to the item.
        /// </summary>
        /// <param name="item"></param>
        public static void BreakCopyRoleInheritance(this SPListItem item)
        {
            SPRoleAssignmentCollection roleAssignments = item.RoleAssignments;

            var activeAssignments = from SPRoleAssignment p in roleAssignments
                                    where p.RoleDefinitionBindings.Count >= 1
                                    select p;

            item.BreakRoleInheritance(false);

            foreach (SPRoleAssignment p in activeAssignments)
            {
                SPRoleAssignment assignment = new SPRoleAssignment(p.Member);
                SPRoleDefinitionBindingCollection bindings = new SPRoleDefinitionBindingCollection();

                foreach (SPRoleDefinition roleDef in p.RoleDefinitionBindings)
                {
                    if (roleDef.Name != "Limited Access")
                    {
                        bindings.Add(roleDef);
                    }
                }
                if (bindings.Count > 0)
                {
                    assignment.ImportRoleDefinitionBindings(bindings);
                    item.RoleAssignments.Add(assignment);
                }
            }
        }
Exemplo n.º 4
0
        public static void SetReadOnly(SPListItem item, int userId)
        {
            SPWeb web = item.Web;
            bool  allowUnsafeUpdates = web.AllowUnsafeUpdates;

            web.AllowUnsafeUpdates = true;
            if (!item.HasUniqueRoleAssignments)
            {
                item.BreakRoleInheritance(true);
            }
            web.AllowUnsafeUpdates = true;
            SPRoleAssignmentCollection roleAssignments = item.RoleAssignments;

            for (int i = roleAssignments.Count - 1; i > -1; i--)
            {
                SPRoleAssignment assignment = roleAssignments[i];
                if (assignment.Member.ID == userId)
                {
                    SPRoleDefinitionBindingCollection roleDefinitionBindings = assignment.RoleDefinitionBindings;
                    if ((roleDefinitionBindings.Count != 1) || (roleDefinitionBindings[0].Type != SPRoleType.Reader))
                    {
                        roleDefinitionBindings.RemoveAll();
                        SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                        roleDefinitionBindings.Add(byType);
                        assignment.Update();
                    }
                    break;
                }
            }
            web.AllowUnsafeUpdates = allowUnsafeUpdates;
        }
Exemplo n.º 5
0
        private bool UpdateUserPermissions(SPWeb web, SPRoleAssignmentCollection roleAssignments, XmlNodeList principalUserNodes)
        {
            bool dirty = false;

            foreach (XmlNode principalUserNode in principalUserNodes)
            {
                string loginName = principalUserNode.Attributes["login"].Value;
                string userName  = principalUserNode.Attributes["name"].Value;
                try
                {
                    SPClaimProviderManager cpm = SPClaimProviderManager.Local;
                    SPClaim userClaim          = cpm.ConvertIdentifierToClaim(loginName, SPIdentifierTypes.WindowsSamAccountName);

                    SPUser user = web.EnsureUser(userClaim.ToEncodedString());
                    if (user == null)
                    {
                        throw new Exception();
                    }

                    SPPrincipal userPrincipal = (SPPrincipal)user;

                    try
                    {
                        SPRoleAssignment roleAssignment = roleAssignments.GetAssignmentByPrincipal(userPrincipal);
                        if (roleAssignment == null)
                        {
                            throw new Exception();
                        }

                        UpdatePrincipal(web, principalUserNode,
                                        string.Format("{0,20}, '{1,15}'", userName, loginName),
                                        roleAssignment);
                    }
                    catch
                    {
                        output.Append(string.Format("permissins missing for user: {0,20} with login: {1,15}, adding new..." + Environment.NewLine, userName, loginName));
                        SPRoleAssignment roleAssignmentNew = new SPRoleAssignment(userPrincipal);
                        XmlNodeList      roleNodes         = principalUserNode.SelectNodes("role");
                        foreach (XmlNode roleNode in roleNodes)
                        {
                            string roleName = roleNode.Attributes["name"].Value;
                            if (roleName.ToLower().Equals("limited access"))
                            {
                                roleName = "Limited User";
                            }

                            SPRoleDefinition role = web.RoleDefinitions[roleName];
                            roleAssignmentNew.RoleDefinitionBindings.Add(role);
                        }
                        roleAssignments.Add(roleAssignmentNew);
                        output.Append("completed" + Environment.NewLine);
                        dirty = true;
                    }
                }
                catch { output.Append(string.Format("user not found: {0,20} with login: {1,15}" + Environment.NewLine, userName, loginName)); }
            }

            return(dirty);
        }
Exemplo n.º 6
0
        public SPRoleAssignmentCollectionInstance(ObjectInstance prototype, SPRoleAssignmentCollection roleAssignmentCollection)
            : this(prototype)
        {
            if (roleAssignmentCollection == null)
            {
                throw new ArgumentNullException("roleAssignmentCollection");
            }

            m_roleAssignmentCollection = roleAssignmentCollection;
        }
Exemplo n.º 7
0
        public static void CopyRights(SPListItem fromItem, SPListItem toItem)
        {
            SPRoleAssignmentCollection fromRights = fromItem.RoleAssignments;

            ClearRights(toItem);
            foreach (SPRoleAssignment right in fromRights)
            {
                toItem.RoleAssignments.Add(right);
            }
        }
Exemplo n.º 8
0
        private void CheckUsers(SPWeb web, SPListItem item, XmlNodeList principalGroupNodes)
        {
            SPRoleAssignmentCollection roleAssignments = item.RoleAssignments;
            bool updated = UpdateUserPermissions(web, roleAssignments, principalGroupNodes);

            if (updated)
            {
                item.SystemUpdate();
            }
        }
Exemplo n.º 9
0
        private void CheckGroups(SPWeb web, SPList list, XmlNodeList principalGroupNodes)
        {
            SPRoleAssignmentCollection roleAssignments = list.RoleAssignments;
            bool updated = UpdateGroupPermissions(web, roleAssignments, principalGroupNodes);

            if (updated)
            {
                list.Update();
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// An item was updated
 /// </summary>
 public override void ItemUpdated(SPItemEventProperties properties)
 {
     if (properties.ListItem["updateContributors"].ToString().Equals("True"))
     {
         //work around so it goes through it only once instead of everytime the item is updated
         properties.ListItem["updateContributors"] = "False";
         SPSite site = new SPSite("http://sp2010dev/ardt/");
         using (SPWeb web = site.OpenWeb())
         {
             SPList     list      = web.Lists["Document Collaboration"];
             SPListItem listItem  = properties.ListItem;
             SPUser     userName  = null;
             String     toAddress = null;
             //EMail initializations
             bool   appendHtmlTag = false;
             bool   htmlEncode    = false;
             string subject       = "You have been assigned to a Document";
             string message       = "Test Message";
             //get usernames
             string   tempFieldValue = listItem["Assigned To"].ToString();
             string[] userNameArray  = listItem["Assigned To"].ToString().Split(';');
             //remove permissions first
             web.AllowUnsafeUpdates = true;
             listItem.BreakRoleInheritance(false);
             SPRoleAssignmentCollection raCollection = listItem.RoleAssignments;
             //remove exisiting permissions one by one
             for (int a = raCollection.Count - 1; a >= 0; a--)
             {
                 raCollection.Remove(a);
             }
             for (int i = 1; i < userNameArray.Length; i++)
             {
                 tempFieldValue = userNameArray[i].Replace("#", "");
                 userName       = web.AllUsers[tempFieldValue];
                 toAddress      = userName.Email;
                 SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                     //EMAIL USER
                     bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);
                     //PERMISSIONS
                     //grant permissions for specific list item
                     SPRoleDefinition roleDefintion  = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                     SPRoleAssignment roleAssignment = new SPRoleAssignment(userName);
                     roleAssignment.RoleDefinitionBindings.Add(roleDefintion);
                     listItem.RoleAssignments.Add(roleAssignment);
                     listItem.Update();
                 });
                 i++;
             }
         }
         //base.ItemUpdated(properties);
         //after final update has been done return true
         properties.ListItem["updateContributors"] = "True";
     }
 }
Exemplo n.º 11
0
        private bool UpdateGroupPermissions(SPWeb web, SPRoleAssignmentCollection roleAssignments, XmlNodeList principalGroupNodes)
        {
            bool dirty = false;

            foreach (XmlNode principalGroupNode in principalGroupNodes)
            {
                string groupName = principalGroupNode.Attributes["name"].Value;
                try
                {
                    SPGroup group = web.SiteGroups.GetByName(groupName);
                    if (group == null)
                    {
                        throw new Exception();
                    }

                    SPPrincipal groupPrincipal = (SPPrincipal)group;

                    try
                    {
                        SPRoleAssignment roleAssignment = roleAssignments.GetAssignmentByPrincipal(groupPrincipal);
                        if (roleAssignment == null)
                        {
                            throw new Exception();
                        }

                        UpdatePrincipal(web, principalGroupNode, groupName, roleAssignment);
                    }
                    catch
                    {
                        output.Append(string.Format("permissins missing for: {0,20}, adding new..." + Environment.NewLine, groupName));
                        SPRoleAssignment roleAssignmentNew = new SPRoleAssignment(groupPrincipal);
                        XmlNodeList      roleNodes         = principalGroupNode.SelectNodes("role");
                        foreach (XmlNode roleNode in roleNodes)
                        {
                            string roleName = roleNode.Attributes["name"].Value;
                            if (roleName.ToLower().Equals("limited access"))
                            {
                                roleName = "Limited User";
                            }

                            SPRoleDefinition role = web.RoleDefinitions[roleName];
                            roleAssignmentNew.RoleDefinitionBindings.Add(role);
                        }
                        roleAssignments.Add(roleAssignmentNew);
                        output.Append("completed" + Environment.NewLine);
                        dirty = true;
                    }
                }
                catch { output.Append(string.Format("group not found: {0,20}" + Environment.NewLine, groupName)); }
            }

            return(dirty);
        }
Exemplo n.º 12
0
        public static void ClearRights(SPWeb web, SPListItem item, bool deleteGuest)
        {
            bool allowUnsafeUpdates = web.AllowUnsafeUpdates;

            web.AllowUnsafeUpdates = true;
            item.BreakRoleInheritance(true);
            web.AllowUnsafeUpdates = true;
            SPRoleAssignmentCollection roleAssignments = item.RoleAssignments;
            bool flag2 = false;
            bool flag3 = false;
            int  iD    = web.Site.SystemAccount.ID;
            int  num2  = (web.AssociatedOwnerGroup != null) ? web.AssociatedOwnerGroup.ID : -1;

            for (int i = roleAssignments.Count - 1; i > -1; i--)
            {
                SPRoleAssignment assignment = roleAssignments[i];
                int num4 = assignment.Member.ID;
                if (num4 == iD)
                {
                    flag3 = true;
                }
                else if (num4 == num2)
                {
                    flag2 = true;
                }
                else if (deleteGuest)
                {
                    roleAssignments.Remove(i);
                }
                else
                {
                    assignment.RoleDefinitionBindings.RemoveAll();
                    assignment.Update();
                }
            }
            web.AllowUnsafeUpdates = true;
            SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Administrator);

            if (!flag3)
            {
                var roleAssignment = new SPRoleAssignment(web.Site.SystemAccount);
                roleAssignment.RoleDefinitionBindings.Add(byType);
                roleAssignments.Add(roleAssignment);
            }
            if (!(flag2 || (web.AssociatedOwnerGroup == null)))
            {
                var assignment3 = new SPRoleAssignment(web.AssociatedOwnerGroup);
                assignment3.RoleDefinitionBindings.Add(byType);
                roleAssignments.Add(assignment3);
            }
            web.AllowUnsafeUpdates = allowUnsafeUpdates;
        }
Exemplo n.º 13
0
        private void RemoveAllPermisions(SPListItem currentListItem)
        {
            //The below function Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments
            currentListItem.BreakRoleInheritance(true);

            //Get the list of Role Assignments to list item and remove one by one.
            SPRoleAssignmentCollection SPRoleAssColn = currentListItem.RoleAssignments;

            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssColn.Remove(i);
            }
        }
        internal static void AddRoleAssignment(SPRoleAssignmentCollection roleAssignments, SPPrincipal groupOrUser, SPRoleDefinition role, bool addToCurrentScopeOnly)
        {
            SPRoleAssignment roleAssignment = new SPRoleAssignment(groupOrUser);

            roleAssignment.RoleDefinitionBindings.Add(role);
            if (addToCurrentScopeOnly)
            {
                roleAssignments.AddToCurrentScopeOnly(roleAssignment);
            }
            else
            {
                roleAssignments.Add(roleAssignment);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// This method will add RoleAssignment instances to a RoleAssignmentCollection based on the Xml supplied.  The
        /// Xml must conform to the SPPermissions.Xml format which is returned by the SPRoleAssignmentCollection.Xml property.
        /// </summary>
        /// <param name="roleAssignments">the object on which to operate</param>
        /// <param name="roleAssignmentsXml">the XML string to retrieve RoleAssignments from</param>
        /// <param name="web">the web containing the RoleDefinitions and SPPrincipals contained in the XML</param>
        /// <returns></returns>
        public static bool Add(this SPRoleAssignmentCollection roleAssignments, string roleAssignmentsXml, SPWeb web)
        {
            bool retVal = true;

            try
            {
                // Create XML Document from xml string
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(roleAssignmentsXml);
                XmlNodeList permissions = xDoc.SelectNodes("//permission");
                foreach (XmlNode permission in permissions)
                {
                    int         memberId  = Convert.ToInt32(permission.Attributes["memberid"].Value);
                    SPPrincipal principal = null;
                    try { principal = web.SiteUsers.GetByID(memberId) as SPPrincipal; }
                    catch (Exception x) { Logger.Instance.Info(string.Format("User with ID {0} not found at {1}", memberId, web.Url, x), DiagnosticsCategories.eCaseExtensions); }
                    if (principal == null)
                    {
                        try { principal = web.SiteGroups.GetByID(memberId) as SPPrincipal; }
                        catch (Exception x)
                        {
                            Logger.Instance.Info(string.Format("Group with ID {0} not found at {1}", memberId, web.Url, x), DiagnosticsCategories.eCaseExtensions);
                            throw x;
                        }
                    }

                    ulong            permissionMask = Convert.ToUInt64(permission.Attributes["mask"].Value);
                    SPRoleDefinition roleDefinition = null;
                    foreach (SPRoleDefinition roleDef in web.RoleDefinitions)
                    {
                        ulong mask = (ulong)roleDef.BasePermissions;
                        if (permissionMask == mask)
                        {
                            roleDefinition = roleDef;
                            break;
                        }
                    }
                    roleAssignments.ParentSecurableObject.TryGrantPermission(principal, roleDefinition);
                }
            }
            catch (Exception x)
            {
                retVal = false;
                Logger.Instance.Error(string.Format("{0}: Failed to Add Permissions {1}", web.Url, roleAssignmentsXml), x, DiagnosticsCategories.eCaseExtensions);
            }
            return(retVal);
        }
Exemplo n.º 16
0
        private void AddGroupRole(SPWeb web, string groupNames, string ouGuid)
        {
            SPGroup group = null;

            try
            {
                SPUser user = web.Author;
                foreach (string groupName in groupNames.Split(';'))
                {
                    if (!IsExistGroup(web, groupName))
                    {
                        //web.AllowUnsafeUpdates = true;
                        web.SiteGroups.Add(groupName, user, null, ouGuid);//新建组

                        if (IsExistGroup(web, groupName))
                        {
                            group = web.SiteGroups.GetByName(groupName);
                            //改变站点继承权
                            if (!web.HasUniqueRoleAssignments)
                            {
                                web.BreakRoleInheritance(true);
                            }

                            //组权限分配与定义(New)
                            SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
                            SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                            SPMember         memCrossSiteGroup         = web.SiteGroups[groupName];
                            SPPrincipal      myssp   = (SPPrincipal)memCrossSiteGroup;
                            SPRoleAssignment myroles = new SPRoleAssignment(myssp);
                            SPRoleDefinitionBindingCollection roleDefBindings = myroles.RoleDefinitionBindings;

                            roleDefBindings.Add(roleDefinitions["Read"]);
                            roleAssignments.Add(myroles);
                        }

                        //web.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// 组权限分配与定义(New)
        /// </summary>
        /// <param name="web"></param>
        /// <param name="groupname"></param>
        /// <param name="roles"></param>
        /// <returns></returns>
        public bool AddGroupToRoles(SPWeb web, string groupname, string[] roles)
        {
            try
            {
                string[] _roles  = roles;
                int      rolemun = _roles.Length;

                if (IsExistGroup(web, groupname))
                {
                    //改变站点继承权
                    if (!web.HasUniqueRoleDefinitions)
                    {
                        web.RoleDefinitions.BreakInheritance(true, true);//复制父站点角色定义并且保持权限
                    }

                    //站点继承权改变后重新设置状态
                    web.AllowUnsafeUpdates = true;

                    //组权限分配与定义(New)
                    SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
                    SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                    SPMember         memCrossSiteGroup         = web.SiteGroups[groupname];
                    SPPrincipal      myssp   = (SPPrincipal)memCrossSiteGroup;
                    SPRoleAssignment myroles = new SPRoleAssignment(myssp);
                    SPRoleDefinitionBindingCollection roleDefBindings = myroles.RoleDefinitionBindings;
                    if (rolemun > 0)
                    {
                        for (int i = 0; i < rolemun; i++)
                        {
                            roleDefBindings.Add(roleDefinitions[_roles[i]]);
                        }
                    }
                    roleAssignments.Add(myroles);
                    return(true);
                }
                return(false);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 18
0
        }//SetItem()

        static void BreakInheritanceAndDeletePermissions(SPWeb web, SPList ccpList, SPListItem item)
        {
            try
            {
                //Ensure item permissions are broken
                item.BreakRoleInheritance(true);

                // 3. Delete item permissions
                SPRoleAssignmentCollection roleAssignments = item.RoleAssignments;
                for (int i = roleAssignments.Count - 1; i >= 0; i--)
                {
                    item.RoleAssignments.Remove(0);
                }
            }
            catch (Exception e)
            {
                //Log to Library
                item["Permission Log"] = e.Message;
                item.Update();
            }
        }//BreakInheritanceAndDeletePermissions()
        public static List <SPPrincipal> GetAssignmentsPrincipals(SPRoleAssignmentCollection assignments)
        {
            List <SPPrincipal> actualAssignees = new List <SPPrincipal>();

            foreach (SPRoleAssignment assignment in assignments)
            {
                if (Regex.IsMatch(assignment.Member.Name, @"svc_|system"))
                {
                    continue;
                }

                foreach (SPRoleDefinition assignmentBinding in assignment.RoleDefinitionBindings)
                {
                    if (assignmentBinding.Name != "Ограниченный доступ")
                    {
                        actualAssignees.Add(assignment.Member);
                    }
                }
            }
            return(actualAssignees);
        }
Exemplo n.º 20
0
        static void BreakInheritanceAndDeletePermissions(SPWeb web, SPList ccpList, SPListItem eventLogItem)
        {
            try
            {
                //Ensure Web Permissions are broken
                web.BreakRoleInheritance(true);

                //Delete Site Permissions
                SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                for (int i = roleAssignments.Count - 1; i >= 0; i--)
                {
                    web.RoleAssignments.Remove(0);
                }
            }
            catch (Exception e)
            {
                //Log
                eventLogItem["Site"] = "Client Permission Error: " + e.Message;
                eventLogItem.Update();
            }
        }//BreakInheritanceAndDeletePermissions
Exemplo n.º 21
0
        private file AddFile(SPFile spFile, SPRoleAssignmentCollection roleAssignments)
        {
            file file = new file();

            file.fileName          = spFile.Name;
            file.serverRelativeUrl = spFile.ServerRelativeUrl;

            foreach (SPRoleAssignment roleAssignment in roleAssignments)
            {
                SPPrincipal principal      = roleAssignment.Member;
                string      principalLogin = (principal is SPUser) ? principal.ParentWeb.AllUsers.GetByID(principal.ID).LoginName : principal.ID.ToString();
                bool        isGroup        = !(principal is SPUser);

                file.AddPrincipal(principalLogin,
                                  principal.Name,
                                  isGroup,
                                  roleAssignment.RoleDefinitionBindings);
            }

            return(file);
        }
Exemplo n.º 22
0
        static string ShowRoleAssignments(SPRoleAssignmentCollection roleAssignments)
        {
            StringBuilder
                output = new StringBuilder();

            foreach (SPRoleAssignment spRoleAssignment in roleAssignments)
            {
                SPUser
                                      spUser;

                SPGroup
                    spGroup;

                SPPrincipal
                    spPrincipal = spRoleAssignment.Member;

                if ((spUser = spPrincipal as SPUser) != null)
                {
                    output.Append(string.Format("SPUser: {{ID: {0} LoginName: {1}, Name: {2}}}{3}", spUser.ID, spUser.LoginName, spUser.Name, Environment.NewLine));
                }
                if ((spGroup = spPrincipal as SPGroup) != null)
                {
                    output.Append(string.Format("SPGroup: {{ID: {0}, Name: {1}}}{2}", spGroup.ID, spGroup.Name, Environment.NewLine));
                }

                foreach (SPRoleDefinition spRoleDefinition in spRoleAssignment.RoleDefinitionBindings)
                {
                    output.Append(string.Format("{{Id: {0}, Type: {1}, Name: {2}, Description: {3}, BasePermissions: {4}}}{5}",
                                                spRoleDefinition.Id,
                                                spRoleDefinition.Type,
                                                spRoleDefinition.Name,
                                                spRoleDefinition.Description,
                                                spRoleDefinition.BasePermissions,
                                                Environment.NewLine));
                }
                output.Append(Environment.NewLine);
            }

            return(output.ToString());
        }
Exemplo n.º 23
0
        public static void RemoveRoleAssignments(SPSecurableObject securable, SPWeb web)
#endif
        {
            // There's a bug with BreakRoleInheritance which means that passing false resets AllowUnsafeUpdates to
            // false so the call fails. http://www.ofonesandzeros.com/2008/11/18/the-security-validation-for-this-page-is-invalid/
            securable.BreakRoleInheritance(true);

            // No need to cache the original value as already set to true before calling here and
            // BreakRoleInheritance has reset to false
            web.AllowUnsafeUpdates = true;

            SPRoleAssignmentCollection roleAssigns = securable.RoleAssignments;

            while (roleAssigns.Count > 0)
            {
                roleAssigns.Remove(0);
            }

            for (int i = roleAssigns.Count - 1; i >= 0; i--)
            {
                roleAssigns.Remove(i);
            }
        }
Exemplo n.º 24
0
        private folder AddFolder(SPFolder spFolder, SPRoleAssignmentCollection roleAssignments, bool isList)
        {
            folder folder = new folder();

            folder.folderName        = isList ? spFolder.ParentWeb.Lists[spFolder.ParentListId].Title : spFolder.Name;
            folder.folderName        = folder.folderName.Replace("\v", " ");
            folder.serverRelativeUrl = spFolder.ServerRelativeUrl;

            folder.isSharePointList = isList;

            foreach (SPRoleAssignment roleAssignment in roleAssignments)
            {
                SPPrincipal principal      = roleAssignment.Member;
                string      principalLogin = (principal is SPUser) ? principal.ParentWeb.AllUsers.GetByID(principal.ID).LoginName : principal.ID.ToString();
                bool        isGroup        = !(principal is SPUser);

                folder.AddPrincipal(principalLogin,
                                    principal.Name,
                                    isGroup,
                                    roleAssignment.RoleDefinitionBindings);
            }

            return(folder);
        }
Exemplo n.º 25
0
        public void execute(SPSite site, SPWeb web, Guid listId, int itemId, int userid, string data)
        {
            SPList            list        = null;
            SPListItem        li          = null;
            GridGanttSettings settings    = null;
            List <string>     cNewGrps    = null;
            List <string>     fields      = null;
            SPUser            orignalUser = null;
            EnhancedLookupConfigValuesHelper valueHelper = null;
            SPList             lookupPrntList            = null;
            GridGanttSettings  prntListSettings          = null;
            SPFieldLookupValue lookupVal  = null;
            SPListItem         targetItem = null;

            try
            {
                list     = web.Lists[listId];
                li       = list.GetItemById(itemId);
                settings = new GridGanttSettings(list);
                cNewGrps = new List <string>();
                bool isSecure = false;
                try
                {
                    isSecure = settings.BuildTeamSecurity;
                }
                catch { }

                orignalUser = web.AllUsers.GetByID(userid);

                string safeTitle = !string.IsNullOrEmpty(li.Title) ? GetSafeGroupTitle(li.Title) : string.Empty;

                if (string.IsNullOrEmpty(safeTitle) && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                {
                    safeTitle = GetSafeGroupTitle(li.Name); //Assign Name instead of Title - This should perticularly happen with Document libraries.
                }
                if (isSecure)
                {
                    if (!li.HasUniqueRoleAssignments)
                    {
                        web.AllowUnsafeUpdates = true;
                        safeGroupTitle         = safeTitle;

                        safeTitle = GetIdenticalGroupName(site.ID, web.ID, safeTitle, 0);

                        // step 1 perform actions related to "parent item"
                        // ===============================================
                        Dictionary <string, SPRoleType> pNewGrps = null;
                        try
                        {
                            pNewGrps = AddBasicSecurityGroups(web, safeTitle, orignalUser, li);

                            li.BreakRoleInheritance(false);

                            foreach (KeyValuePair <string, SPRoleType> group in pNewGrps)
                            {
                                SPGroup g = web.SiteGroups[group.Key];
                                AddNewItemLvlPerm(li, web, group.Value, g);
                                g = null;
                            }

                            AddBuildTeamSecurityGroups(web, settings, li);
                        }
                        catch { }
                        finally
                        {
                            pNewGrps = null;
                        }
                    }
                }


                // step 2 perform actions related to "child item"
                // ====================================
                // find lookups that has security enabled
                string lookupSettings = settings.Lookups;
                //string rawValue = "Region^dropdown^none^none^xxx|State^autocomplete^Region^Region^xxx|City^autocomplete^State^State^xxx";
                valueHelper = new EnhancedLookupConfigValuesHelper(lookupSettings);

                if (valueHelper == null)
                {
                    return;
                }

                fields = valueHelper.GetSecuredFields();

                bool bHasLookup = false;

                foreach (string fld in fields)
                {
                    SPFieldLookup lookup = null;
                    try
                    {
                        lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                    }
                    catch { }

                    if (lookup == null)
                    {
                        continue;
                    }

                    lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                    prntListSettings = new GridGanttSettings(lookupPrntList);
                    string sVal = string.Empty;
                    try
                    {
                        sVal = li[fld].ToString();
                    }
                    catch { }
                    if (!string.IsNullOrEmpty(sVal))
                    {
                        bHasLookup = true;
                        break;
                    }
                }
                if (bHasLookup)
                {
                    // has security fields
                    if (fields.Count > 0)
                    {
                        // if the list is not a security list itself
                        if (isSecure)
                        {
                            li.BreakRoleInheritance(false);
                        }

                        foreach (string fld in fields)
                        {
                            SPFieldLookup lookup = null;
                            try
                            {
                                lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                            }
                            catch { }

                            if (lookup == null)
                            {
                                continue;
                            }

                            lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                            prntListSettings = new GridGanttSettings(lookupPrntList);
                            bool isEnableSecurity = false;
                            bool isParentSecure   = false;
                            try
                            {
                                isParentSecure = prntListSettings.BuildTeamSecurity;
                            }
                            catch { }

                            string[]  LookupArray = settings.Lookups.Split('|');
                            string[]  sLookupInfo = null;
                            Hashtable hshLookups  = new Hashtable();
                            foreach (string sLookup in LookupArray)
                            {
                                if (sLookup != "")
                                {
                                    sLookupInfo = sLookup.Split('^');
                                    hshLookups.Add(sLookupInfo[0], sLookupInfo);
                                }
                            }
                            try
                            {
                                if (sLookupInfo != null && sLookupInfo[4].ToLower() == "true")
                                {
                                    isEnableSecurity = true;
                                }
                                else
                                {
                                    isEnableSecurity = false;
                                }
                            }
                            catch { isEnableSecurity = false; }

                            // skip fields with empty lookup values
                            string sVal = string.Empty;
                            try { sVal = li[fld].ToString(); }
                            catch { }
                            if (string.IsNullOrEmpty(sVal))
                            {
                                continue;
                            }

                            lookupVal  = new SPFieldLookupValue(sVal.ToString());
                            targetItem = lookupPrntList.GetItemById(lookupVal.LookupId);
                            if (!targetItem.HasUniqueRoleAssignments)
                            {
                                continue;
                            }
                            else
                            {
                                //EPML-4422: When a project is not using unique security, and a child list like tasks is set to Inherit security from the project lookup, It sets the task to unique, but does not add any groups. It should not get set to Unique.
                                if (!isSecure && isParentSecure && isEnableSecurity)
                                {
                                    web.AllowUnsafeUpdates = true;
                                    li.BreakRoleInheritance(false);
                                }
                            }

                            SPRoleAssignmentCollection raCol = targetItem.RoleAssignments;
                            string itemMemberGrp             = "Member";
                            foreach (SPRoleAssignment ra in raCol)
                            {
                                // add their groups to this item but change permission lvl
                                if (ra.Member.Name.Contains(itemMemberGrp))
                                {
                                    SPRoleAssignment newRa  = new SPRoleAssignment(ra.Member);
                                    SPRoleDefinition newDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                    newRa.RoleDefinitionBindings.Add(newDef);
                                    li.RoleAssignments.Add(newRa);
                                }
                                else
                                {
                                    li.RoleAssignments.Add(ra);
                                }

                                cNewGrps.Add(ra.Member.Name);
                            }
                        }
                    }
                }
                ProcessSecurity(site, list, li, userid);

                // we wait until all groups have been created to createworkspace
                // only if there isn't a current process creating ws
                WorkspaceTimerjobAgent.QueueWorkspaceJobOnHoldForSecurity(site.ID, web.ID, list.ID, li.ID);
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                list             = null;
                li               = null;
                lookupPrntList   = null;
                prntListSettings = null;
                settings         = null;
                cNewGrps         = null;
                fields           = null;
                orignalUser      = null;
                valueHelper      = null;
                lookupVal        = null;
                targetItem       = null;
                fields           = null;
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Returns a list presenting the SharePoint Security Groups for the current web that have a specified permission associated with them
        /// </summary>
        /// <param name="webUrl">The URL for the SP site</param>
        /// <param name="permissionLevel">The permission level the groups must have</param>
        /// <returns>A list of groups (wrapped by a ResponseObject)</returns>
        internal GetSecurityGroupsResponse GetSecurityGroups(GlymaPermissionLevel permissionLevel)
        {
            GetSecurityGroupsResponse result = new GetSecurityGroupsResponse()
            {
                HasError = false
            };
            IList <GlymaSecurityGroup> results = new List <GlymaSecurityGroup>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(WebUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPRoleDefinition roleDefinition = null;
                            try
                            {
                                // Check if the role exists, if it does a definition will exist
                                roleDefinition = web.RoleDefinitions[GlymaPermissionLevelHelper.GetPermissionLevelName(permissionLevel)];
                            }
                            catch (Exception)
                            {
                                //if unable to find the role definition it will throw an exception
                            }

                            if (roleDefinition != null)
                            {
                                SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                                foreach (SPRoleAssignment roleAssignment in roleAssignments)
                                {
                                    bool hasRoleDefinition = false;
                                    foreach (
                                        SPRoleDefinition definition in roleAssignment.RoleDefinitionBindings)
                                    {
                                        if (definition.Id == roleDefinition.Id)
                                        {
                                            //The role exists for this role assignment
                                            hasRoleDefinition = true;
                                            break;
                                        }
                                    }

                                    if (hasRoleDefinition)
                                    {
                                        SPGroup group = roleAssignment.Member as SPGroup;
                                        //we only want to look at groups
                                        if (group != null)
                                        {
                                            GlymaSecurityGroup glymaGroup = new GlymaSecurityGroup();
                                            glymaGroup.DisplayName        = group.Name;

                                            SecurableContext securableContext = this.GetSecurableContext();
                                            glymaGroup.SecurableContextId     = securableContext.SecurableContextId;

                                            GlymaSecurityGroupContext sgc = new GlymaSecurityGroupContext(this, securableContext.SecurableContextId, group.ID, web.ID);
                                            Group glGroup = sgc.GetGroup(group.Name);
                                            if (glGroup == null)
                                            {
                                                glGroup = sgc.CreateGroup(group.Name);
                                            }
                                            if (glGroup != null)
                                            {
                                                glymaGroup.GroupId = glGroup.GroupId;
                                                results.Add(glymaGroup);
                                            }
                                            else
                                            {
                                                result.HasError     = true;
                                                result.ErrorMessage = "Failed to create the Group in the Glyma Security Database.";
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                results = new List <GlymaSecurityGroup>(); //there was no role by this name, it has no groups
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                //If an error occurs getting the group listing return no groups
                result.HasError     = true;
                result.ErrorMessage = ex.Message;
            }
            if (!result.HasError)
            {
                result.Result = results;
            }
            return(result);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Creates an SPWeb object
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static void CreateSPWeb(SPListItem item, string managerUserName)
        {
            //Construct the Url, display name and language ID for the site
            string newWebUrl   = item.ID.ToString();
            string newWebTitle = null;

            if (item["Matter Number: Matter Name"] != null)
            {
                newWebTitle = item["Matter Number: Matter Name"].ToString();
            }
            else if (item["Matter Number: Account Name"] != null)
            {
                newWebTitle = item["Matter Number: Account Name"].ToString();
            }
            string newWebDescription = string.Empty;
            uint   newWebLcid        = item.Web.Language;

            //Get the ID of the web template for Matter sites
            SPWebTemplateCollection templateCollection = item.Web.GetAvailableWebTemplates(item.Web.Language);
            SPWebTemplate           newWebTemplate     = null;

            foreach (SPWebTemplate currentTemplate in templateCollection)
            {
                if (currentTemplate.Title == "Matter Template")
                {
                    newWebTemplate = currentTemplate;
                }
            }

            //Create the new web using the Matter Template as a web template
            using (SPWeb newWeb = item.Web.Webs.Add(newWebUrl, newWebTitle, string.Empty, newWebLcid, newWebTemplate, true, false))
            {
                //Apply the same permissions that are on the list item to the subsite
                SPRoleAssignmentCollection newWebRoles = item.RoleAssignments;
                foreach (SPRoleAssignment currentRole in newWebRoles)
                {
                    newWeb.RoleAssignments.Add(currentRole);
                }
                newWeb.Update();

                //Create a matter summary object on the subsite
                SPListItem matterSummary = newWeb.Lists["Matter summary"].AddItem();
                matterSummary["Account Name"] = item["Matter Number: Account Name"];

                //Affiliate is a multi-value managed metadata value column, can't update display value directly
                if (item["Matter Number: Affiliate"] != null)
                {
                    string   affiliatesConcat = item["Matter Number: Affiliate"].ToString();
                    string[] affiliates       = affiliatesConcat.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    UpdateMultiMMField(affiliates, matterSummary, "Affiliate");
                }

                matterSummary["Case Caption"]  = item["Matter Number: Case Caption"];
                matterSummary["Docket Number"] = item["Matter Number: Docket Number"];

                //Manager is a person/group field, must update with an actual SPUser object
                if (!string.IsNullOrEmpty(managerUserName))
                {
                    if (!managerUserName.StartsWith(@"i:0#.w|TRG"))
                    {
                        managerUserName = @"i:0#.w|TRG\" + managerUserName;
                    }
                    SPUser manager = null;
                    try
                    {
                        manager = item.Web.AllUsers[managerUserName];
                    }
                    catch (Exception ex)
                    {
                        manager = item.Web.EnsureUser(@"i:0#.w|TRG\Legacy");
                    }
                    matterSummary["Litigation Manager"] = manager;
                }

                //Litigation type is a managed metadata value column, can't update display value directly
                if (item["Matter Number: Litigation Type"] != null)
                {
                    UpdateMMField(item["Matter Number: Litigation Type"].ToString(), matterSummary, "Litigation Type");
                }

                matterSummary["Matter Name"]   = item["Matter Number: Matter Name"];
                matterSummary["Matter Status"] = item["Matter Number: Matter Status"];

                //State filed is a managed metadata value column, can't update display value directly
                if (item["Matter Number: State Filed"] != null)
                {
                    UpdateMMField(item["Matter Number: State Filed"].ToString(), matterSummary, "State Filed");
                }

                //Venue is a managed metadata value column, can't update display value directly
                if (item["Matter Number: Venue"] != null)
                {
                    UpdateMMField(item["Matter Number: Venue"].ToString(), matterSummary, "Venue");
                }

                //Work matter type is a multi-value managed metadata value column, can't update display value directly
                if (item["Matter Number: Work/Matter Type"] != null)
                {
                    string   workmatterTypeConcat = item["Matter Number: Work/Matter Type"].ToString();
                    string[] workmatterTypes      = workmatterTypeConcat.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    UpdateMultiMMField(workmatterTypes, matterSummary, "Work/Matter Type");
                }
                matterSummary.Update();
            }
        }
Exemplo n.º 28
0
        public static SPWeb UpdateSPWeb(SPListItem item, string managerUserName)
        {
            //Update the subsite's title
            string url = item["Matter Site"].ToString().Substring(item["Matter Site"].ToString().IndexOf(',') + 2);

            using (SPWeb updateWeb = item.Web.Site.AllWebs[url])
            {
                if (!updateWeb.Exists)
                {
                    CreateSPWeb(item, managerUserName);
                }
            }
            using (SPWeb updateWeb = item.Web.Site.AllWebs[url])
            {
                string newWebTitle = null;
                if (item["Matter Number: Matter Name"] != null)
                {
                    newWebTitle = item["Matter Number: Matter Name"].ToString();
                }
                else if (item["Matter Number: Account Name"] != null)
                {
                    newWebTitle = item["Matter Number: Account Name"].ToString();
                }
                updateWeb.Title = newWebTitle;

                //Apply the same permissions that are on the list item to the subsite
                SPRoleAssignmentCollection newWebRoles = item.RoleAssignments;
                foreach (SPRoleAssignment currentRole in newWebRoles)
                {
                    updateWeb.RoleAssignments.Add(currentRole);
                }
                updateWeb.Update();

                //Update the matter summary list item on the subsite
                SPListItem matterSummary = null;
                if (updateWeb.Lists["Matter summary"].ItemCount > 0)
                {
                    matterSummary = updateWeb.Lists["Matter summary"].Items[0];
                }
                else
                {
                    matterSummary = updateWeb.Lists["Matter summary"].AddItem();
                }
                matterSummary["Account Name"] = item["Matter Number: Account Name"];

                //Affiliate is a multi-value managed metadata value column, can't update display value directly
                if (item["Matter Number: Affiliate"] != null)
                {
                    string   affiliatesConcat = item["Matter Number: Affiliate"].ToString();
                    string[] affiliates       = affiliatesConcat.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    UpdateMultiMMField(affiliates, matterSummary, "Affiliate");
                }

                matterSummary["Case Caption"]  = item["Matter Number: Case Caption"];
                matterSummary["Docket Number"] = item["Matter Number: Docket Number"];

                //Manager is a person/group field, must update with an actual SPUser object
                if (!string.IsNullOrEmpty(managerUserName))
                {
                    if (!managerUserName.StartsWith(@"i:0#.w|TRG"))
                    {
                        managerUserName = @"i:0#.w|TRG\" + managerUserName;
                    }
                    SPUser manager = null;
                    try
                    {
                        manager = item.Web.AllUsers[managerUserName];
                    }
                    catch (Exception ex)
                    {
                        manager = item.Web.EnsureUser(@"i:0#.w|TRG\Legacy");
                    }
                    matterSummary["Litigation Manager"] = manager;
                }

                //Litigation type is a managed metadata value column, can't update display value directly
                if (item["Matter Number: Litigation Type"] != null)
                {
                    UpdateMMField(item["Matter Number: Litigation Type"].ToString(), matterSummary, "Litigation Type");
                }

                matterSummary["Matter Name"]   = item["Matter Number: Matter Name"];
                matterSummary["Matter Status"] = item["Matter Number: Matter Status"];

                //State filed is a managed metadata value column, can't update display value directly
                if (item["Matter Number: State Filed"] != null)
                {
                    UpdateMMField(item["Matter Number: State Filed"].ToString(), matterSummary, "State Filed");
                }

                //Venue is a managed metadata value column, can't update display value directly
                if (item["Matter Number: Venue"] != null)
                {
                    UpdateMMField(item["Matter Number: Venue"].ToString(), matterSummary, "Venue");
                }

                //Work matter type is a multi-value managed metadata value column, can't update display value directly
                if (item["Matter Number: Work/Matter Type"] != null)
                {
                    string   workmatterTypeConcat = item["Matter Number: Work/Matter Type"].ToString();
                    string[] workmatterTypes      = workmatterTypeConcat.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
                    UpdateMultiMMField(workmatterTypes, matterSummary, "Work/Matter Type");
                }
                matterSummary.Update();
                return(updateWeb);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Ejecuta acciones en caso de marcar la correspondencia como "Privada"
        /// </summary>
        /// <param name="properties"></param>
        private void EventoHacerCorrespondenciaPrivada(SPItemEventProperties properties)
        {
            SPSite sitioAdm = null;
            SPWeb  webAdm   = null;

            try
            {
                string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"];

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {//Como usuario administrador
                    sitioAdm = new SPSite(UrlFPC);
                    webAdm   = sitioAdm.OpenWeb();
                });

                bool       esPrivada = (bool)properties.ListItem["Privada"];
                SPList     lista     = webAdm.Lists[properties.ListId];
                SPListItem listItem  = lista.GetItemById(properties.ListItemId);

                if (!listItem.HasUniqueRoleAssignments)
                {
                    listItem.BreakRoleInheritance(true);

                    #region Eliminar grupos
                    if (esPrivada)
                    {
                        try
                        {
                            if (webAdm.Lists[properties.ListId].Title.Contains(CORREO_EDUCAPRO_SC))
                            {
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES_SC].ID);
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_EP_SC].ID);
                            }
                            else if (webAdm.Lists[properties.ListId].Title.Contains(CORREO_EDUCAPRO_CB))
                            {
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES_CB].ID);
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_EP_CB].ID);
                            }
                            else if (webAdm.Lists[properties.ListId].Title.Contains(CORREO_EDUCAPRO))
                            {
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES].ID);
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_EP].ID);
                            }
                            else if (webAdm.Lists[properties.ListId].Title.Contains(CORREO_FUNDAPRO))
                            {
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES].ID);
                                listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_FP].ID);
                            }

                            //if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                            //    CORREO_FUNDAPRO, StringComparison.CurrentCultureIgnoreCase))
                            //{
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES].ID);
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_FP].ID);
                            //}
                            //else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                            //    CORREO_EDUCAPRO, StringComparison.CurrentCultureIgnoreCase))
                            //{
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES].ID);
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_EP].ID);
                            //}
                            //else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                            //    CORREO_EDUCAPRO_CB, StringComparison.CurrentCultureIgnoreCase))
                            //{
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES_CB].ID);
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_EP_CB].ID);
                            //}
                            //else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                            //    CORREO_EDUCAPRO_SC, StringComparison.CurrentCultureIgnoreCase))
                            //{
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_COLABORADORES_SC].ID);
                            //    listItem.RoleAssignments.RemoveById(webAdm.Groups[GRUPO_INTEGRANTES_EP_SC].ID);
                            //}
                        }
                        catch { }
                    }
                    #endregion
                }

                string idEditor = listItem["Editor"].ToString().Remove(
                    listItem["Editor"].ToString().IndexOf(';'));
                SPFieldUserValueCollection usuarios =
                    (SPFieldUserValueCollection)properties.ListItem["Dirigida a"];

                if (Convert.ToInt32(idEditor) != usuarios[0].User.ID)
                {
                    #region Agregar usuario emisor
                    listItem.RoleAssignments.RemoveById(Convert.ToInt32(idEditor));

                    SPRoleDefinitionCollection roleDefinitionsColab = webAdm.RoleDefinitions;
                    SPRoleAssignmentCollection roleAssignmentsColab = webAdm.RoleAssignments;
                    SPRoleAssignment           roleAssignmentColab  = new SPRoleAssignment(
                        webAdm.SiteUsers.GetByID(Convert.ToInt32(idEditor)).LoginName, "", "", "");

                    SPRoleDefinitionBindingCollection roleDefinitionBindingsColab =
                        roleAssignmentColab.RoleDefinitionBindings;
                    roleDefinitionBindingsColab.Add(roleDefinitionsColab["Leer"]);
                    roleAssignmentsColab.Add(roleAssignmentColab);

                    listItem.RoleAssignments.Add(roleAssignmentColab);
                    #endregion

                    #region Agregar usuarios receptores
                    for (int i = 0; i < usuarios.Count; i++)
                    {
                        SPFieldUserValue usuario = usuarios[i];

                        SPRoleDefinitionCollection roleDefinitionsLect = webAdm.RoleDefinitions;
                        SPRoleAssignmentCollection roleAssignmentsLect = webAdm.RoleAssignments;
                        SPRoleAssignment           roleAssignmentLect  =
                            new SPRoleAssignment(usuario.User.LoginName, "", "", "");

                        SPRoleDefinitionBindingCollection roleDefinitionBindingsLect =
                            roleAssignmentLect.RoleDefinitionBindings;
                        if (i == 0)
                        {
                            roleDefinitionBindingsLect.Add(roleDefinitionsLect["Colaborar Res."]);
                        }
                        else
                        {
                            roleDefinitionBindingsLect.Add(roleDefinitionsLect["Leer"]);
                        }
                        roleAssignmentsLect.Add(roleAssignmentLect);

                        listItem.RoleAssignments.Add(roleAssignmentLect);
                    }
                    #endregion
                }
            }
            finally
            {
                if (webAdm != null)
                {
                    webAdm.Dispose();
                }
                if (sitioAdm != null)
                {
                    sitioAdm.Dispose();
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// 创建子项目按钮事件
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnCreateSite_Click(object sender, EventArgs e)
        {
            try
            {
                SPSite site = SPContext.Current.Web.Site;
                //string spwt = SPWebTemplate.WebTemplateSTS;//默认选择工作组网站模板

                SPWeb web = site.OpenWeb("/");
                web.AllowUnsafeUpdates = true;
                SPMember memUser = web.Users[0];
                SPUser   suser   = web.Users[0];


                //新建组
                //web.SiteGroups.Add("skyteam3", memUser, suser, "new skyteam");
                //web.SiteGroups["skyteam3"].AddUser("adr\\administrator", "[email protected]", "蔡", "系统维修人员");
                //web.Groups["skyteam2"].AddUser("adr\\pccai", "[email protected]", "蔡", "系统维修人员");


                //新建子站点
                string currentTemplate = web.WebTemplate;
                //web.Webs.Add("Test2", "站点名称2", "站点描述2", 2052, "_GLOBAL_#0", true, false);


                //打开子站点
                SPWeb web2 = site.OpenWeb("Projects/Test2");
                web2.AllowUnsafeUpdates = true;
                // web2.SiteGroups.Add("skyteam6", memUser, suser, "new skyteam");//新建组
                // web2.SiteGroups["skyteam6"].AddUser("adr\\administrator", "[email protected]", "边", "系统维修人员");


                //改变站点继承权
                if (!web2.HasUniqueRoleDefinitions)
                {
                    web2.RoleDefinitions.BreakInheritance(true, true);
                }

                //站点继承权改变后重新设置状态
                web2.AllowUnsafeUpdates = true;



                //添加权限级别 (Role)
                //SPRoleDefinition roleDefinition = new SPRoleDefinition();
                //roleDefinition.Name = "项目角色";
                //roleDefinition.Description = "项目角色可以批准所有项目情况.";
                //roleDefinition.BasePermissions = SPBasePermissions.FullMask ^ SPBasePermissions.ManagePermissions;
                //web2.RoleDefinitions.Add(roleDefinition);


                //更改权限级别 (Permissions)
                SPRoleDefinitionCollection roles           = web2.RoleDefinitions;
                SPRoleDefinition           roleDefinition1 = roles["读取"];
                roleDefinition1.BasePermissions = SPBasePermissions.AddListItems |
                                                  SPBasePermissions.BrowseDirectories |
                                                  SPBasePermissions.EditListItems |
                                                  SPBasePermissions.DeleteListItems |
                                                  SPBasePermissions.AddDelPrivateWebParts;
                roleDefinition1.Update();


                //用户权限分配与定义(New)
                SPRoleDefinitionCollection        roleDefinitions = web2.RoleDefinitions;
                SPRoleAssignmentCollection        roleAssignments = web2.RoleAssignments;
                SPRoleAssignment                  roleAssignment  = new SPRoleAssignment("adr\\administrator", "*****@*****.**", "Display_Name", "Notes");
                SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
                roleDefBindings.Add(roleDefinitions["项目角色"]);
                roleAssignments.Add(roleAssignment);


                //权限定义(Old)
                //SPRoleCollection siteGroups = web2.Roles;
                //siteGroups.Add("skyteam6", "Description", SPRights.ManageWeb | SPRights.ManageSubwebs);


                //获得权限定义
                SPRoleDefinition sprole = roleDefinitions.GetByType(SPRoleType.Reader);
                string           spname = sprole.Name;


                //组权限分配与定义(New)
                SPRoleDefinitionCollection roleDefinitions1 = web2.RoleDefinitions;
                SPRoleAssignmentCollection roleAssignments1 = web2.RoleAssignments;
                SPMember         memCrossSiteGroup          = web2.SiteGroups["skyteam6"];
                SPPrincipal      myssp   = (SPPrincipal)memCrossSiteGroup;
                SPRoleAssignment myroles = new SPRoleAssignment(myssp);
                SPRoleDefinitionBindingCollection roleDefBindings1 = myroles.RoleDefinitionBindings;
                roleDefBindings1.Add(roleDefinitions1["设计"]);
                roleDefBindings1.Add(roleDefinitions1["读取"]);
                roleAssignments1.Add(myroles);


                //组权限分配与定义(Old)
                //SPMember member = web2.Roles["skyteam"];
                //web2.Permissions[member].PermissionMask =
                //    SPRights.ManageLists | SPRights.ManageListPermissions;



                //更改列表权限(Old)
                //SPList list = site.Lists["通知"];
                //SPPermissionCollection perms = list.Permissions;
                //SPUserCollection users = site.Users;
                //SPMember member = users["ADR\\pccai"];
                //list.Permissions[member].PermissionMask = SPRights.AddListItems | SPRights.EditListItems;



                //  PermissionCollection perc = web.Permissions;
                //perc.AddUser("adr\\administrator", "[email protected]", "title", "Notes", PortalRight.AllSiteRights);
                // SecurityManager.AddRole(context, "title", "descriptions", PortalRight.ManageSite);
            }
            catch (Exception)
            {
                throw;
            }
        }