我正在成功使用它。我留下了我的日志记录和日志记录方法。
/// <summary>
/// This method is executed on feature activation.
/// It attaches the event receiver to the content type.
/// </summary>
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
LogMessage("FeatureActivated - Start");
SPSite site = (SPSite)properties.Feature.Parent;
LogMessage("FeatureActivated - 1");
SPWeb web = site.RootWeb;
LogMessage("FeatureActivated - 2");
//ListContentTypes(web);
SPContentType ctype = web.ContentTypes["Wells Project Task List"];
LogMessage("FeatureActivated - 3");
LogMessage("ctype name: " + ctype.Name.ToString());
if (ctype != null)
{
LogMessage("FeatureActivated - I have a content type. Web url: " + web.Url);
SPEventReceiverDefinition er = ctype.EventReceivers.Add();
er.Class = "Wells.SharePoint.ProjectManagementEventReceiver";
er.Assembly = "ProjectManagementEventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a1cb21c41d80b7ae";
er.Type = SPEventReceiverType.ItemAdded;
er.Name = "ItemAdded";
er.SequenceNumber = 10001;
er.Update();
ctype.Update(false);
LogMessage("FeatureActivated - After ctype.update");
web.Dispose();
}
else
LogMessage("CT not found: " + web.Url);
LogMessage("FeatureActivated - End");
}
static void ListContentTypes(SPWeb web)
{
foreach (SPContentType ct in web.ContentTypes)
{
LogMessage("CT: " + ct.Name.ToString());
}
}
/// <summary>
/// This method is executed on feature deactivation.
/// It removes the event receiver from the content type
/// </summary>
/// <param name="properties"></param>
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
LogMessage("Feature DeActivated - Start");
SPSite site = (SPSite)properties.Feature.Parent;
SPWeb web = site.OpenWeb();
SPContentType contentType = web.ContentTypes["NAME OF CONTENT TYPE"];
if (contentType != null)
{
LogMessage("im have a content type. Web url: " + web.Url);
int i;
//Use the above integer to loop through the event recievers on the first list and delete the above assembly
for (i = 0; i < contentType.EventReceivers.Count; i++)
{
LogMessage("ER Count: " + contentType.EventReceivers.Count);
if (contentType.EventReceivers[i].Assembly.Contains("ProjectManagementEventReceiver"))
{
contentType.EventReceivers[i].Delete();
LogMessage("Deleting event receiver from CT");
}
}
contentType.Update();
}
else
LogMessage("CT not found: " + web.Url);
LogMessage("Feature DeActivated - End");
}
static void LogMessage(string msg)
{
StreamWriter wrtr = null;
try
{
wrtr = new StreamWriter("C:\\Logs\\FeatureActivatedDeactivated.txt", true);
wrtr.WriteLine(msg + "--[" + System.DateTime.Now.ToString() + "]" + Environment.NewLine);
wrtr.WriteLine(Environment.NewLine + "==================================");
}
catch (Exception e)
{
throw e;
}
finally
{
if (wrtr != null)
{
wrtr.Close();
wrtr.Dispose();
}
}
}