如何通过事件接收器更新当前项目中的字段值?

时间:2012-08-07 21:37:07

标签: sharepoint event-receiver

编辑:我意识到我在第二个代码块中的方法是不必要的。我可以通过在ItemUpdated中执行以下操作来完成同样的事情:

SPListItem thisItem = properties.ListItem;

thisItem.File.CheckOut();

thisItem["Facility Number"] = "12345";
thisItem.Update();

thisItem.File.CheckIn("force check in");

不幸的是,当“thisItem.Update();”时,我仍然收到相同的错误消息执行:沙盒代码执行请求被拒绝,因为沙盒代码主机服务太忙而无法处理请求

我最初在部署我的沙盒解决方案时收到了上述错误并使用了这个链接(http://blogs.msdn.com/b/sharepointdev/archive/2011/02/08/error-the-sandboxed-code -execution-request-was-refused-because-the-sandboxed-code-host-service-too-busy-to-handle-the-request.aspx)来修复它。


我正在尝试编写一个C#事件接收器,它可以在库中添加/更改文档时更改字段的值。我尝试使用以下代码:

public override void ItemUpdating(SPItemEventProperties properties)
{
    base.ItemUpdating(properties);
    string fieldInternalName = properties.List.Fields["Facility Number"].InternalName;
    properties.AfterProperties[fieldInternalName] = "12345";
}

不幸的是,这仅适用于某些领域。例如,如果我用“Source”替换“Facility Number”,代码将正确执行。这可能是因为我们使用的是第三方软件(称为KnowledgeLake),它使用Silverlight表单替换SharePoint中的默认编辑表单。无论如何,因为我对上面的代码提出了挑战(再次,因为我认为在ItemUpdating事件触发后Silverlight表单可能会覆盖该字段),我尝试了以下代码:

 public override void ItemUpdated(SPItemEventProperties properties)
 {

       base.ItemUpdated(properties);

       //get the current item
       SPListItem thisItem = properties.ListItem;

       string fieldName = "Facility Number";
       string fieldInternalName = properties.List.Fields[fieldName].InternalName;
       string fieldValue = (string)thisItem["Facility Number"];

       if (!String.IsNullOrEmpty(fieldValue))
       {
           //properties.AfterProperties[fieldInternalName] = "123456789";

           SPWeb oWebsite = properties.Web as SPWeb;
           SPListItemCollection oList = oWebsite.Lists[properties.ListTitle].Items;

           SPListItem newItem = oList.GetItemById(thisItem.ID);

           newItem.File.CheckOut();

           thisItem[fieldInternalName] = "12345";
           thisItem.Update();

           newItem.File.CheckIn("force");
       }
   }

首先,上面对我来说似乎有点笨拙,因为我很想使用AfterProperties方法。此外,执行“newItem.Update()”时出现以下错误:沙箱代码执行请求被拒绝,因为沙盒代码主机服务太忙而无法处理请求

我在这里遗漏了什么吗?我很乐意使用第一个代码块。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

Josh能够回答他自己的问题,这也帮助我解决了我的问题。这是一个有效的代码snippit。

public override void ItemUpdated(SPItemEventProperties properties)
{
 string internalName = properties.ListItem.Fields[columnToUpdate].InternalName;

 //Turn off event firing during item update
 base.EventFiringEnabled = false;

 SPListItem item = properties.ListItem;
 item[internalName] = newVal;
 item.Update();

 //Turn back on event firing
 base.EventFiringEnabled = true;

 base.ItemUpdated(properties);
}