0

I am new SharePoint programming.

I have created event receiver on item adding for the document library that allows only .doc files to be uploaded, otherwise it gives error.

My code for event receiver is:

public override void ItemAdding(SPItemEventProperties properties)
{
    base.ItemAdding(properties);
    if (!properties.AfterUrl.EndsWith("doc"))
    {
       properties.Cancel = true;
       properties.ErrorMessage = "Only .doc files are accepted";
    }
}

Now I want to make it active only the time the feature is active, when the feature is deactivated the event receiver should also be disabled. I think it may be possible with FeatureDeactivating() method.

How to implement it? Please help.

1

Something like this in the Feature Deactivated event (if feature is site scoped, otherwise you would need to open the web and site a bit different as you see):

 using (SPSite site = new SPSite((properties.Feature.Parent as SPSite).ID))
 {
  using (SPWeb web = site.OpenWeb())
  {
   SPListCollection lists = web.Lists;
   SPList list = web.Lists["My List"];

   SPEventReceiverDefinitionCollection erdc = list.EventReceivers;
   List <SPEventReceiverDefinition> eventsToDelete = new List <SPEventReceiverDefinition>();

   foreach (SPEventReceiverDefinition erd in erdc)
   {
    if (erd != null)
    {
     try
     {
      eventsToDelete.Add(erd);
     }
     catch (Exception e)
     {
      Console.Write(e.ToString());
     }
    }
   }
   foreach (SPEventReceiverDefinition er in eventsToDelete)
   {
    //if(er.Type == SPEventReceiverType.ItemAdded)
    er.Delete();
   }  
  }
 }

from here : http://sarangasl.blogspot.se/2009/11/remove-event-receiver-in-sharepoint.html

  • The code runs without error but SPEventReceiverDefinitionCollection erdc = list.EventReceivers; fetches nothing.. @Robert Lindgren – users1100 Aug 6 '13 at 7:55
  • Strange, you are on the correct list on the correct web? – Robert Lindgren Aug 6 '13 at 7:58
  • Yes sir, I debugged the program and list object is also being created so it proves that list is correct.. – users1100 Aug 6 '13 at 8:01
0

You can try this:

SPContentType ct = web.ContentTypes[CtName];
if (ct != null && ct.EventReceivers != null && ct.EventReceivers.Count == 0)
{
    SPEventReceiverDefinition ev =
    ct.EventReceivers.Cast<SPEventReceiverDefinition>()
        .FirstOrDefault(e => e.Name == EventReceiverAddedName);
    if (ev == null)
        return;
    ev.Delete();
    ev.Update();
    ct.Update(true);
}

Really simplet to use. You will just need name of content type (where the event receiver is activated) and name of the assigned event receiver.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.