Working with the PeoplePicker Data Values in SharePoint 1

Posted by Bob Silva Mon, 29 Oct 2007 04:54:00 GMT

The SharePoint PeoplePicker control is great for selecting a user, but it doesn't do much more than that. When it stores the value in the database, like many other controls, it uses the familiar ;# delimiter like so: 15;#Robert Silva. The first value is the ID of the user in the User Information List in the top-level site. It's a hidden list. If you want to see what's in it, use this cool little PowerShell trick I just learned myself:
# Load the Microsoft.SharePoint.dll assembly
[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

# Load your site
$site = New-Object Microsoft.SharePoint.SPSite("http://url")

# Load the User Information List
$userlist = $site.RootWeb.Lists["User Information List"]

# Print the ID and Title of each list item
$userlist.Items | Format-List -property ID, Title

$site.RootWeb.Dispose()
$site.Dispose()
This information itself doesn't do you much good. What if you want the email address of the user or their user profile. Luckily, SharePoint provides everything we need and makes it (finally) pretty easy for us. In the following code example, I have a column named Technician defined as a Person or Group column. In code, I use this list item value to load a User and their User Profile. The magic is the SPFieldUserValue object that we pass the 15;#Robert Silva into. Using its User property, we are able to do whatever we want with them.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://url"))
            {
                using (SPWeb web = site.AllWebs["webname"])
                {
                    SPList list = web.Lists["listname"];
                    ServerContext sc = ServerContext.GetContext(site);
                    UserProfileManager profileManager = new UserProfileManager(sc);
                    foreach (SPListItem item in list.Items)
                    {
                        SPFieldUserValue uv = new SPFieldUserValue(web, item["Technician"].ToString());
                        if (profileManager.UserExists(uv.User.LoginName))
                        {
                            UserProfile user = profileManager.GetUserProfile(uv.User.LoginName);                            
                        }
                    }
                }                
            }

            System.Console.ReadLine();
        }
    }
}

Comments

Leave a response

  1. Zach Rosenfield 1 day later:
    Great to see these cool PowerShell tricks for SharePoint being posted online (and thanks for adding the Dispose!).
Comments