WebPart.AfterDeserialize method

Called after a SharePoint Web Part's properties are deserialized from the SharePoint database or from a Web Part description file (.dwp). Suggested place for SharePoint Web Part upgrade code.

Namespace:  Microsoft.SharePoint.WebPartPages
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public virtual void AfterDeserialize()

The AfterDeserialize method supports upgrade scenarios where a new version of a Web Part needs to accommodate changes to properties that have been saved for a previous version of a Web Part. If a Web Part developer simply adds one or more new properties, no upgrade logic is required. However, if properties are deleted or renamed, or the values saved are changed, then overriding the AfterDeserialize method provides a way for handling these changes when a SharePoint Web Part is upgraded.

The following code example shows how to handle a situation when one or more properties have been removed from the later version of a Web Part. Because elements that the assembly cannot recognize will be added to the UnknownXmlElementCollection collection, the following code example shows iterating through that collection and removing the unknown elements.

For more information about using the AfterDeserialize method when upgrading Web Parts, see Upgrading a Web Part Assembly.

// Override the AfterDeserialize method to remove any items in 
// the UnknownXmlElementCollection within the MyWebPartNamespace
public override void AfterDeserialize()
        bool itemsRemoved = false;
        if (UnknownXmlElements.Count>0)
            XmlElement element;
            int index = UnknownXmlElements.Count - 1;

            // Loop from the end of the collection to eliminate the need to
            // update the index based on whether or not an item was deleted. 
            while (index >= 0)
                element = UnknownXmlElements[index];

                // Check if the element is within the namespace.
                // Do a case-insensitive match to be consistent with the
                // XmlSerializer.
                if (element.NamespaceURI == "MyWebPartNamespace")
                    // If the element is in the namespace, remove it from the collection.
                    itemsRemoved = true;
        // If your assembly is installed in the application's bin directory, which defaults to minimal trust, 
        // make sure that your Web Part assembly has UnsafeSaveOnGet permission or the following 
        // attempt to save changes will return an error.  
        if (itemsRemoved)
            SaveProperties = true;
         // Handle or ignore errors.