Monday, January 28, 2008

Searching for Users or Groups Using SPUtility.ResolvePrincipal

It's sometimes handy to know that the Person or Group SharePoint column data type is stored internally as a SPFieldUserValue. This in turn is derived from SPFieldLookupValue which is serialized as "ID;#VALUE" in the content database, e.g.:

        SPListItem item = web.Lists["Docs"].Items[0];
        string fieldValue = item["Contact"].ToString(); // Contact is the name of Person or Group column and in this case has a value "1;#Test User"
        SPFieldUserValue user = new SPFieldUserValue(web, fieldValue);
        string name = user.LookupValue; // Test User


The LookupId for this field type is the ID property of the SPPrincipal class.

Sometimes you might need to determine what this Lookup ID is for a particular user name (you can even search for a user by email address), and that's where the SPUtility.ResolvePrincipal method is helpful, e.g.:

        using Microsoft.SharePoint.Utilities;
        ...
        SPPrincipalInfo userInfo = SPUtility.ResolvePrincipal(web, "Test User", SPPrincipalType.All, SPPrincipalSource.All, null, false);
        if (userInfo != null)
        {
            item["Contact"] = new SPFieldUserValue(web, userInfo.PrincipalId, userInfo.DisplayName);
            item.Update();
        }


A good example of using this method can be found here which demonstrates using this method to find out if a user has access to your site or list.

A second SPUtility method - SPUtility.SearchPrincipals - returns a list of principals much like the list returned by the "Select People and Groups" picker dialog box, e.g:

        bool reachedMaxCount = false;
        IList<SPPrincipalInfo> users = SPUtility.SearchPrincipals(web, "T", SPPrincipalType.All, SPPrincipalSource.All, null, 100, out reachedMaxCount);