我正在开发一个SharePoint 2010项目,我在其中有几个站点。每个站点下都包含一个包含新闻的列表,我想将事件接收器附加到这些列表中。
以下网站和列表是以编程方式创建的,但我无法附加我在VS2010解决方案中的事件接收器。
我试过这个:
SPList list = new SPSite(siteURL).OpenWeb().Lists[listName];
SPEventReceiverDefinitionCollection eventReceivers = list.EventReceivers;
SPEventReceiverDefinition eventReceiver = eventReceivers.Add();
eventReceiver.Name = receiverName;
eventReceiver.Synchronization = SPEventReceiverSynchronization.Synchronous;
eventReceiver.Type = SPEventReceiverType.ItemAdded;
eventReceiver.SequenceNumber = sequenceNumber;
eventReceiver.Assembly = assemblyFullName;
eventReceiver.Class = assemblyClassName;
eventReceiver.Data = receiverData;
eventReceiver.Update();
但它不起作用。
错误消息是“无法加载文件或程序集”Projekt_Test1 \,\,Version \ = 1.0.1777.23493 \,Culture \ = neutral \,PublicKeyToken \ = 49c7547d535382ab'或其依赖项之一。给定的程序集名称或代码库无效。(HRESULT异常:0x80131047)“
感谢您的帮助。
答案 0 :(得分:8)
我最终为此创建了一个List Extension方法:
public static void EnsureEventReceiver(this SPList list,IEnumerable<SPEventReceiverType> receiverTypes, Type eventHander, SPEventReceiverSynchronization synchronization, int sequenceNumber)
{
foreach (SPEventReceiverType spEventReceiverType in receiverTypes)
{
string name = list.Title + spEventReceiverType.ToString();
if (list.EventReceivers.Cast<SPEventReceiverDefinition>().All(i => i.Name != name))
{
SPEventReceiverDefinition eventReceiver = list.EventReceivers.Add();
eventReceiver.Name = name;
eventReceiver.Type = spEventReceiverType;
eventReceiver.Assembly = eventHander.Assembly.FullName;
eventReceiver.Class = eventHander.FullName;
eventReceiver.SequenceNumber = sequenceNumber;
eventReceiver.Synchronization = synchronization;
eventReceiver.Update();
}
}
}
警告,此方法的局限性:
你可以像这样使用它:
list.EnsureEventReceiver(
new[] { SPEventReceiverType.ItemAdded, SPEventReceiverType.ItemUpdated },
typeof(NewsItemsHandler),
SPEventReceiverSynchronization.Synchronous,
10000);
答案 1 :(得分:2)
我从未成功使用过你正在使用的eventReceivers.Add()
版本。
这是我正在使用的powershell framgent,它在C#中非常相似
$ev = $currentList.EventReceivers.Add([Microsoft.SharePoint.SPEventReceiverType]::ItemAdded, $assemblyName, $className);
答案 2 :(得分:2)
要考虑的事情: