Monday, October 15, 2012

How to Fetch User with their permission

Some times we need to fetch the user form Sharepoint with their role and permission.

If i need to fetch all user who is having Admin Rights "Full Control" on the site.

There are two ways to achieve this. One is by using Object model and other is SQL Query on Content DB


Through Object Model

using (SPSite _Site = new SPSite("http://YourSiteName"))
        {
            using (SPWeb _Web = _Site.OpenWeb())
            {

                SPRoleDefinitionCollection roleDefinitions = _Web.RoleDefinitions;
                SPRoleDefinition roleDefinition = roleDefinitions["Full Control"];
                foreach (SPRoleAssignment roleAssigment in _Web.RoleAssignments)
                {
                    if (roleAssigment.RoleDefinitionBindings.Contains(roleDefinition))
                    {
                        SPPrincipal oPrincipal = roleAssigment.Member;
                        
                        //it can be SPUser or SPGroup, you can process and add it to the result
                         SPUser oRoleUser = (SPUser)oPrincipal;
                    }
                }
               
            }
        }

Query through Content DataBase

SELECTdbo.Webs.Id, dbo.Webs.Title, dbo.Webs.FullUrl, dbo.Roles.RoleId, dbo.Roles.Title AS RoleTitle, dbo.UserInfo.tp_Title, dbo.UserInfo.tp_LoginFROMdbo.RoleAssignment INNER JOINdbo.RolesONdbo.RoleAssignment.SiteId = dbo.Roles.SiteIdANDdbo.RoleAssignment.RoleId = dbo.Roles.RoleIdINNER JOINdbo.WebsONdbo.Roles.SiteId = dbo.Webs.SiteIdANDdbo.Roles.WebId = dbo.Webs.IdINNER JOINdbo.UserInfoONdbo.RoleAssignment.PrincipalId = dbo.UserInfo.tp_ID AND dbo.RoleAssignment.RoleID='1073741829'

Here You need to pass the RoleID. 

No comments:

Post a Comment