Tutorial :SharePoint: Error on unregistering an EventReceiver form a ContentType



Question:

I've got some problems unregistering some eventreceivers form a contenttype. The contenttype and the receivers were deployed and registered by myself so I don't try to remove any MOSS built-in or internal eventreceivers.

I trying to archive this with the following code snippet:

using (SPSite site = new SPSite("http://wssdev06/"))          {              using (SPWeb web = site.RootWeb)              {                  // web.AllowUnsafeUpdates = true;                    SPContentType type = web.AvailableContentTypes[<ContentTypeName>];                    while (type.EventReceivers.Count > 0)                  {                      type.EventReceivers[0].Delete();                                          }                    type.Update();                    // web.AllowUnsafeUpdates = false;              }          }  

Unfortunately the command "type.Update()" throws an exception telling me that the collection cannot be modified. As you can see in the code I've already tried different things to solve this problem, as allowing unsafe updates or running this code with elevated privileges. But I always get the same exception.

So what am I doing wrong?


Solution:1

Your problem is that the "AvailableContentTypes" property returns you a READ-ONLY collection.

You should also use the 'ContentTypes' property, ans everything should be fine.

Regards,

Dug.


Solution:2

Is the type based on a publishing type? I have had issues changing those types. Otherwise you might try changing the entire SchemaXml of the type. I have found that this sometimes works when other methods do not.


Solution:3

You should be able to set type.ReadOnly = false to enable writing to the type.

As well, your SPWeb does not need to be disposed - see Roger Lamb's blog here for more details.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »