shutterstock_184473665.jpg

Summit 7 Team Blogs

Programmatically Assigning AD Security Groups to SharePoint Tasks

Recently, I came across an issue with programmatically assigning an Active Directory account to a SharePoint task.  The problem was that the current web object didn’t contain the AD security group I was looking for in “allusers” even though I had specifically added the group to the site with contribute permissions.  Below is the code that was not returning a user object.

private SPUser getWebUser(string userName, SPWeb web)
{
SPUser result = default(SPUser);
try
{
web.EnsureUser(userNameLoginOrEmail);
userName = userName.ToLower();
foreach (SPUser user in web.AllUsers)
{
if (user.LoginName.ToLower() == userName)
{
result = user;
break;
}
}
}
catch (Exception ex)
{
//Handle Exception
}
return result;
}

After further investigation, it turns out that when an Active Directory user browses to the site, they get added to the AllUsers Group.  Since a group cannot log in to browse to the site, AD security groups will never exist in that web.AllUsers.  Alternatively, we must use the web.SiteUsers to get a comprehensive list of users belonging to the site collection.  So with a slight modification to the code, my function finds the desired group and returns a user object that can be used to assign the task.  Hopefully this will help you save a headache while tracking down AD Security Groups in code.

private SPUser getWebUser(string userName, SPWeb web)
{
SPUser result = default(SPUser);
try
{
web.EnsureUser(userNameLoginOrEmail);
userName = userName.ToLower();
foreach (SPUser user in web.SiteUsers)
{
if (user.LoginName.ToLower() == userName)
{
result = user;
break;
}
}
}
catch (Exception ex)
{
//Handle Exception
}
return result;
}

Happy Programming!

Steve Jenkins

Summit 7 Systems

References:

Know the difference between SPWeb.Users and SPWeb.SiteUsers

SharePoint: Difference between Web.AllUsers and Web.Users

 

Disclaimer
The sample scripts are not supported under any Summit 7 Systems standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Summit 7 Systems further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Summit 7 Systems, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Summit 7 Systems has been advised of the possibility of such damages.

SHARE THIS STORY | |