Find out wether a filled in user field is a group or a user

The following method allows you to find out wether a filled in user field is an actual user, or might be an active directory group. Here I use the principalInfo variable to see if there’s an actual windows principal behind the value of “user”. I use the user’s e-mail in the first part, since there might be more persons with the same user.LookupValue value. In other words: some people have the same displayname.

For the same reason, I use the user.User.LoginName in the web.EnsureUser method.

protected static SPPrincipal GetUserOrGroup(SPWeb web, SPFieldUserValue user)
{
	if (user.User != null)
		var principalInfo = SPUtility.ResolveWindowsPrincipal(
			web.Site.WebApplication, user.User.Email, SPPrincipalType.All, true);

	// if the user has no e-mail, check the user's name. This is not failsafe when 2 persons have the same name
	if (principalInfo == null)
		principalInfo = SPUtility.ResolveWindowsPrincipal(
			web.Site.WebApplication, user.LookupValue, SPPrincipalType.All, false);

	SPPrincipal principal;
	if (principalInfo != null)
		principal = web.EnsureUser(user.User.LoginName);
	else
		principal = web.SiteGroups[user.LookupValue];
	return principal;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s