Programmatically Adding to and Removing from a Person or Group Column

本文介绍如何使用SharePoint Object Model通过编程方式添加和移除任务分配中的用户或组。文中提供了具体的代码示例,展示了如何利用SPFieldUserValueCollection类来操作用户集合。

Using the UI, it is quite easy to add and remove users.  (Note: You must make sure the column allows multiple selections to add more than one user).  But how would this be done programmatically using the SharePoint Object Model?  This is a bit more complex since we somehow need to add or remove items from a list (e.g. both Robert King and Laura Callahan).  And this list is stored in a single field’s value.

The answer is to use a class called SPFieldUserValueCollection.  As you’ll guess, it’s a collection of SPFieldUserValue objects, and each SPFieldUserValue object basically represents a single user (SPUser) or group (SPGroup) from your site collection.

Here’s some code to help explain what I mean.  This code retrieves a single item from the Tasks list and iterates through each field user value.

//Get a handle to our Tasks list
SPList tasks = web.Lists["Tasks"];
//Select first in the list
SPListItem task = tasks.Items[0];

//Access value from AssignedTo and cast to SPFieldUserValueCollection
SPFieldUserValueCollection AssignedTo = (SPFieldUserValueCollection)task["AssignedTo"];

foreach (SPFieldUserValue fuv in AssignedTo)
{
    Console.WriteLine("LookupId = {0}, LookupValue = {1}", fuv.LookupId, fuv.LookupValue);
}

                foreach (SPFieldUserValue Value in Values)
                {
                    if (User != null)
                    {
                        SPUser User = Value.User;
                        Users.Add(User);
                    }
                    else
                    {
                        SPGroup Group = Web.Groups.GetByID(Value.LookupId);
                        Groups.Add(Group);
                        Users.AddRange(Group.Users);
                    }
                }
This results in the following console output for the single task shown above:

LookupId = 19, LookupValue = Robert King
LookupId = 16, LookupValue = Laura Callahan

For those curious, you can also take the value of the field and output as a string using syntax like: task[“AssignedTo”].ToString().  If you do, it will look like this:

19;#Robert King;#16;#Laura Callahan

(Note: this is the same way that a Lookup column works.  See this well-written blog article for more info on this.)

So, you should have a basic idea on how this is internally stored within SharePoint.  Let’s now get to the code which actually adds or remove users.  To do this, I wrote two simple helper methods that you’re welcome to use.  Here is the one that adds a user or group:

void AddPrincipal (SPListItem item, string column, SPPrincipal principal)
{
    SPFieldUserValueCollection fuvc = (SPFieldUserValueCollection)item[column];
    fuvc.Add(new SPFieldUserValue(item.ParentList.ParentWeb, principal.ID, principal.Name));
    item[column] = fuvc;
    item.Update();  
}
It’s pretty straight forward.  The reason I called the method AddPrincipal is that SPPrincipal is the base class for SPUser and SPGroup.  This allows it to be used for either object type.  The method takes the SPListItem, the name of the column and the SPPrincipal. Here’s how we would call it from our code:

SPUser user = web.SiteUsers["synergy\\lcallahan"];
AddPrincipal(task, "AssignedTo", user);
Calling it to add a group is the same.  Here is an example:

SPGroup group = web.SiteGroups["Home Owners"];
AddPrincipal(task, "AssignedTo", group);

Removing is a little trickier as we must first find the SPPrincipal.  Here is the code:

void RemovePrincipal(SPListItem item, string column, SPPrincipal principal)
{
    SPFieldUserValueCollection fuvc = (SPFieldUserValueCollection)item[column];
    foreach (SPFieldUserValue value in fuvc)
    {
        if (value.LookupId == principal.ID)
        {
            fuvc.Remove(value);
            item[column] = fuvc;
            item.Update();
            break;
        }
        //optionally throw an exception if not found
        //throw new System.ArgumentException ("Principal not found");
    }
}
Calling into the method is very simple.  Here we are removing a user and a group.

RemovePrincipal(task, "AssignedTo", user);
RemovePrincipal(task, "AssignedTo", group);

转载于:https://www.cnblogs.com/icedog/archive/2010/07/13/1776240.html

In Android development, encapsulating a website typically refers to creating an interface that allows you to interact with the website's content without exposing its underlying implementation details or hosting the entire site within your app. This is often done using webviews and APIs. Here's a basic explanation: 1. **WebView**: WebView is a built-in component that lets you display HTML, CSS, and JavaScript content inside an Android app. You can load websites by setting the WebView's `loadUrl()` method with the desired URL. ```java WebView webView = findViewById(R.id.web_view); webView.loadUrl("https://example.com"); ``` 2. **Content Providers (optional)**: If you need to access specific data from the website, you might consider using a Content Provider to fetch that information. For instance, if the website offers JSON data, you can create a custom content provider for your app to consume. 3. **API Integration**: If the website has an API, use Android's HTTP clients like `HttpClient` or later `OkHttp`, or even better, with Retrofit for a more structured approach. This allows you to make calls to the server programmatically. 4. **Separation of Concerns**: To maintain encapsulation, separate the code responsible for interacting with the website (the "adapter" layer) from your app's core logic. This helps keep your app clean and maintainable. ```java // Using Retrofit for API integration Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService service = retrofit.create(ApiService.class); Call<ApiResponse> call = service.getData(); call.enqueue(new Callback<ApiResponse>() { @Override public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) { // Handle API response } @Override public void onFailure(Call<ApiResponse> call, Throwable t) { // Handle errors } }); ``` **
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值