<CharlieDigital/> Programming, Politics, and uhh…pineapples

10Oct/08Off

Getting SharePoint Task Assignee

One of the more interesting problems I've been working with is trying to figure out how to get the user information for the assignee (whom the task is assigned to). Getting the user ID and the the user display name is easy enough, but then that entails another lookup to find the the login name for the user.

For example, here is some code which retrieves the user information, but as a string:

using (SPSite site = new SPSite(siteUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList tasks = web.Lists["Tasks"];
 

        foreach (SPListItem task in tasks.Items)
        {
            string assignedTo = Convert.ToString(task["Assigned To"]);

            Console.Out.WriteLine("> {0}", assignedTo);
        }
    }
}

This generates the following output:

> 37;#Brad Wright

> 40;#Daniel OConnor

> 46;#Charles

As mentioned, this is only part of the information we're after. To get the login name, we'd have to do some simple string parsing and then make a separate call to look up the user. Not a terrible amount of work, but more work, nonetheless.

Stepping through the debugger, I could see that the actual type of the field was SPFieldUserValue. My first attempt was to see if I could convert the value directly; no go. It turns out that the value retrieved (before calling the ToString()) is already a string. I ended up fumbling around with the very awkward GetFieldValue() method on the SPField class. It's not at all intuitive on how this method is supposed to be used, so I'm hoping this is useful:

using (SPSite site = new SPSite(siteUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList tasks = web.Lists["Tasks"];
 

        foreach (SPListItem task in tasks.Items)
        {
            string fieldValue = Convert.ToString(task["Assigned To"]);

            SPFieldUserValue assignedTo = (SPFieldUserValue)
                task.Fields["Assigned To"].GetFieldValue(fieldValue);

            Console.Out.WriteLine("> {0} ({1})", 
                assignedTo.User.Name, assignedTo.User.LoginName);
        }
    }
}

And here is the output

> Brad Wright (FP1\bwright)

> Daniel OConnor (FP1\doconnor)

> Charles (FP1\charles)

The call is all kind of awkward and is completely non-intuitive. It's easier to think of it as item.Fields["Some Field"].ConvertToNativeOutputType(fieldValue). So you can see, this is a much more convenient way of retrieving the user from a list item (or any typed return value) once you get the hang of the weird nomenclature and usability issues.

Posted by Charles Chen

Filed under: SharePoint Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.