Turning off Audience Targeting on Page Libraries – Operation is not valid due to the current state of the object

Well .. this took a while to crack.
 
"Operation is not valid due to the current state of the object"
 
Anyone who has seen this will know it’s a pain to track down. This particular one was even more painful that usual, because it was being thrown from the "Modify Audience Targeting" page of a Pages Library in MOSS 2007!
 
Do I did some rooting around and found a great post from Gary Lapointe (https://stsadm.blogspot.com/2008/08/enabling-audience-targeting-on-list.html) showing how to enable (or disable) audience targeting on a list through code.
 
However, there was a bug so it gave me the same error message!
The problem is that the field that we are trying to delete (Audience Targeting) is Sealed. So you need to set "Sealed=False" .. (I also set "AllowDeletion=True" as well to be on the safe side!)
 
The working code (modified from Gary Lapointe’s original code) is as follows:
 
public static void SetTargeting(SPList list, bool enabled) 
        {  
                if (list == null) 
                    throw new SPException("List was not found."); 
               
                SPField targetingField = GetTargetingField(list); 
                if (enabled && (targetingField == null)) 
                { 
                    string createFieldAsXml = CreateFieldAsXml();
                    list.Fields.AddFieldAsXml(createFieldAsXml); 
                    list.Update(); 
                } 
                else if (!enabled && (targetingField != null))
                {
                    // make sure the field can be deleted!
                    targetingField.AllowDeletion = true;
                    targetingField.Sealed = false;
                    targetingField.Update();
                    list.Fields.Delete(targetingField.InternalName);
                    list.Update();
                } 
        }
You can see the highlighted section that I added to Garys code.
 
Cheers!
 
Martin