我正在使用Sharepoint 2010中的託管客戶端對象模型。並且我想要loginaNameAssignedTo用戶在任務列表中。如何使用客戶端對象模型從「AssignedTo」字段獲取Sharepoint用戶對象?
在服務器端對象模型中,我使用SPFieldUserValue.User.LoginName來獲取此屬性,但在客戶端對象模型中,FieldUserValue.User不存在。
我該如何解決這種情況?
感謝
我正在使用Sharepoint 2010中的託管客戶端對象模型。並且我想要loginaNameAssignedTo用戶在任務列表中。如何使用客戶端對象模型從「AssignedTo」字段獲取Sharepoint用戶對象?
在服務器端對象模型中,我使用SPFieldUserValue.User.LoginName來獲取此屬性,但在客戶端對象模型中,FieldUserValue.User不存在。
我該如何解決這種情況?
感謝
你得到列其爲FieldUserValue從列表,一旦你有你使用值查找ID,然後查詢對網站上的用戶信息列表。在下面的示例中,我緩存結果以防止多次查找相同的ID,因爲查詢可能很昂貴。
private readonly Dictionary<int, string> userNameCache = new Dictionary<int, string>();
public string GetUserName(object user)
{
if (user == null)
{
return string.Empty;
}
var username = string.Empty;
var spUser = user as FieldUserValue;
if (spUser != null)
{
if (!userNameCache.TryGetValue(spUser.LookupId, out username))
{
var userInfoList = context.Web.SiteUserInfoList;
context.Load(userInfoList);
var query = new CamlQuery { ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='ID' /><Value Type='int'>" + spUser.LookupId + "</Value></Eq></Where></Query></View>" };
var users = userInfoList.GetItems(query);
context.Load(users, items => items.Include(
item => item.Id,
item => item["Name"]));
if (context.TryExecuteQuery())
{
var principal = users.GetById(spUser.LookupId);
context.Load(principal);
context.ExecuteQuery()
username = principal["Name"] as string;
userNameCache.Add(spUser.LookupId, username);
}
}
}
return username;
}
這是代碼。我已經從任務列表中分配了一個AssignedTo字段的示例。我希望有所幫助。上述
public static User GetUserFromAssignedToField(string siteUrl)
{
// create site context
ClientContext ctx = new ClientContext(siteUrl);
// create web object
Web web = ctx.Web;
ctx.Load(web);
// get Tasks list
List list = ctx.Web.Lists.GetByTitle("Tasks");
ctx.Load(list);
// get list item using Id e.g. updating first item in the list
ListItem targetListItem = list.GetItemById(1);
// Load only the assigned to field from the list item
ctx.Load(targetListItem,
item => item["AssignedTo"]);
ctx.ExecuteQuery();
// create and cast the FieldUserValue from the value
FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];
Console.WriteLine("Request succeeded. \n\n");
Console.WriteLine("Retrieved user Id is: {0}", fuv.LookupId);
Console.WriteLine("Retrieved login name is: {0}", fuv.LookupValue);
User user = ctx.Web.EnsureUser(fuv.LookupValue);
ctx.Load(user);
ctx.ExecuteQuery();
return user;
}
一切爲我工作,但不是:
FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];
我用:
FieldUserValue[] fuv = targetListItem["AssignedTo"] as FieldUserValue[];
的fuv.LookupValue
可能包含顯示名稱,而不是登錄名,所以我的建議是(假設你有FieldUserValue
- fuv
我n個代碼(由@ekhanna爲descibed):使用ctx.Web.EnsureUser
var userId = fuv.LookupId;
var user = ctx.Web.GetUserById(userId);
ctx.Load(user);
ctx.ExecuteQuery();
工作就像一個魅力... – onzur 2013-03-11 20:08:20
LookupValue給我的顯示名稱,而不是登錄名。 – 2014-01-27 06:59:36